@tinkerlandai/longplay-react-native 0.10.19-rc.3 → 0.10.19

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/dist/index.js CHANGED
@@ -14,4 +14,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14
14
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15
15
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16
16
  SOFTWARE.
17
- */var ve=N.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Pt=N.record(N.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),gb=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),nn=Pt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.strictObject({id:N.uuid(),attributeKey:N.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!gb.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),yb=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:nn}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Yn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var Ab=N.record(N.uuid(),yb).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Yn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),jc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),Op=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(jc).min(1).max(100)}),bb=N.strictObject({id:N.string().min(1).max(128),condition:nn,gate:N.boolean().optional()}),kc={id:N.string().max(128).optional(),condition:nn.optional(),parentConditions:N.array(bb).max(50).optional(),filters:N.array(Op).max(20).optional()},xb=N.union([N.strictObject({...kc}),N.strictObject({...kc,force:ve,coverage:N.number().min(0).max(1).optional(),range:jc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...kc,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),Sb=N.strictObject({defaultValue:ve,rules:N.array(xb).max(100)}),ZP=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Sb).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Ib=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:nn,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(jc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),vb=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(Ib).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var wb=vb.safeExtend({filters:N.array(Op).optional()}),Ob=N.strictObject({experiments:N.record(N.uuid(),wb),savedGroups:Ab}),uo=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),WP=N.strictObject({snapshot:Ob,attributes:Pt,results:Pt,stickyBucketAssignmentDocs:N.record(N.string(),uo)}),YP=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function lr(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var Pb=qt.enum(["active","inactive"]),Cb=qt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},Pt),_b=qt.strictObject({id:qt.string().trim().min(1).max(255),name:qt.string().trim().min(1).max(255),status:Pb,metadata:Cb}),iC=_b.extend({internal_id:qt.uuid(),project_id:qt.uuid(),environment_id:qt.uuid(),created_at:qt.iso.datetime({offset:!0}),updated_at:qt.iso.datetime({offset:!0})}),Cp=qt.union([qt.strictObject({id:qt.string().trim().min(1).max(255)}),qt.strictObject({internalId:qt.uuid()})]),oC=qt.enum(["customer","merchandise","context"]),aC=qt.enum(["system","stored","request"]),sC=qt.enum(["customer","merchandise","mixed"]),Pp=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Tc(e,t={},n=new Set){if(lr(e).some(Pp))return!0;for(let r of Yn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Pp(i.attributeKey)||i?.type==="condition"&&Tc(i.condition,t,n))return!0}return!1}import{z as Eb}from"zod";var Rb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,Cn=Eb.string().max(16).regex(Rb,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var hC=te.enum(["draft","active","paused","archived"]),dr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),dn=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),_p=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],kb=te.discriminatedUnion("type",[..._p,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:nn})])})]),Nc=te.discriminatedUnion("type",[..._p,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),jb=te.strictObject({firstPurchaseOnly:te.boolean(),condition:nn}),gC=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:dr,duration:dn,appliesTo:kb,eligibility:jb,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!Tc(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),yC=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var lo=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:dr,duration:dn,appliesTo:Nc}).strict()}).strict(),Ep=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Np=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Dc=S.string().regex(/^(0|[1-9]\d{0,14})$/),bi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Tb=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),po=Tb,Xn=de.refine(e=>/[1-9]/.test(e)),Qt=S.iso.datetime({offset:!0}),Ra=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},Nb=S.array(S.object({upTo:Xn.nullable(),unitAmountMinor:Np,flatAmountMinor:S.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Ra(t.upTo)>Ra(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Db=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Xn,unitAmountMinor:Np}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Xn,tiers:Nb}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Fb=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),mo=S.object({currency:Ie,pricing:Db,billingCycle:Fb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Rp={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Dp=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Fp=S.discriminatedUnion("kind",[S.object({...Rp,kind:S.literal("auto_topup"),threshold:la,quantity:Xn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Dp.optional()}).strict(),S.object({...Rp,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:po,maxOutstandingMinor:po}).strict()]),kp={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Mp=S.discriminatedUnion("kind",[S.object({...kp,kind:S.literal("auto_topup"),threshold:la,quantity:Xn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Dp.optional(),purchaseAmountMinor:po,purchaseUnits:Xn}).strict(),S.object({...kp,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:po,maxOutstandingMinor:po,cashPrice:mo}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ka=S.object({id:S.uuid(),terms:Mp,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:Qt,acceptedAt:Qt.nullable(),effectiveAt:Qt.nullable(),revokedAt:Qt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),qp=S.object({authorizationId:S.uuid(),terms:Mp,setupUrl:S.url().nullable()}).strict(),Up=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Bp=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),Vp=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:Ot.optional(),limit:de.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Xn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&Ra(t)>Ra(i)}),"Notification thresholds must increase"),Mb=Vp.safeExtend({requestId:S.uuid()}),jp={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},qb=S.discriminatedUnion("action",[S.strictObject({...jp,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...jp,action:S.literal("remove")})]),Lp=S.union([Mb,qb]),Ub=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:Qt,endsAt:Qt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Bb=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:Ot.optional(),startsAt:Qt,endsAt:Qt,used:tn,reserved:tn,limit:de.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Xn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Xn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||de.safeParse(e.used).success&&de.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Vb=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:Qt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:Qt.nullable(),nextAttemptAt:Qt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),zp=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),Fc=S.object({authorizations:S.array(ka).max(100),limits:S.array(Vp).max(100),overages:S.array(Ub).max(100).optional(),windows:S.array(Bb).max(200),autoTopups:S.array(Vb).max(100),limited:S.boolean()}).strict(),Lb=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:de,amountMinor:bi,cashPrice:mo}).strict(),fo=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Qt.nullable(),endsAt:Qt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Dc,paidAmountMinor:Dc,refundedAmountMinor:Dc,createdAt:Qt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Qt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(Lb).max(100),linesLimited:S.boolean()}).strict(),$p=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),Gp=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.string().trim().min(1).max(500)}),Kp=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),Hp=S.object({rows:S.array(fo).max(100),nextCursor:S.uuid().nullable()}).strict(),Tp=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),zb=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(Tp).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:Tp.optional()})).max(20)})).max(100)}),Qp=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Jp=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:zb.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:dr,duration:dn,startedAt:Qt.nullable()})).max(20)});import{z as ho}from"zod";var Zp=ho.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Wp=ho.number().int().min(1).max(1e3),ja=ho.object({cap:de.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:ho.number().positive().max(1e4).nullable(),cycles:ho.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as pr}from"zod";var Yp=pr.strictObject({itemKey:pr.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:pr.uuid(),includedAmount:pr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:pr.number().int().min(0).max(1e4),terms:Ia,pricing:ao.optional(),unitAmountMinor:pr.number().int().min(0).max(1e8),productId:pr.string().min(1).max(255).nullable(),priceId:pr.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Xd(e.includedAmount,e.terms.units,e.quantity),Sa({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as ne}from"zod";var Mr=de.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),go=ne.string().min(1).max(120),Ta=ne.enum(["cap","overflow"]),pn=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},yo=e=>{try{return e()}catch{return!1}},Ao=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:Ta.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Mr,properties:Ot}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:Ta.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:de,properties:Ot,idempotencyKey:go}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Mr,properties:Ot,idempotencyKey:go,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Mr,properties:Ot.optional(),idempotencyKey:go}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Mr,idempotencyKey:go}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:go}).strict()]),Mc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:de,units:Mr,amount:tn,tier:ne.number().int().min(1).max(12).nullable()}).strict(),qr=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Xp(e,t){let n=e.reduce((r,i)=>r+pn(i.units,12),0n)-pn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var em=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:qr.refine(e=>/[1-9]/.test(e)),amount:tn}),ne.strictObject({funding:ne.literal("unbilled"),units:qr.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Mr,amount:tn,pricing:ne.array(Mc).min(1).max(12)}).strict().refine(e=>yo(()=>e.pricing.reduce((t,n)=>t+pn(n.units,6),0n)===pn(e.units,6)&&e.pricing.reduce((t,n)=>t+pn(n.amount,12),0n)===pn(e.amount,12)&&e.pricing.every(t=>pn(t.unitCost,6)*pn(t.units,6)===pn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Mr,authorizationId:ne.uuid()}).strict()]),Na=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),tm=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:de,requestedQuantity:de.optional(),overageBehavior:Ta.optional(),reason:Na.nullable(),allocations:ne.array(em).max(500)}).strict().refine(e=>yo(()=>e.allowed?e.reason===null&&Xp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>yo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&pn(e.requestedQuantity,6)>=pn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),bo=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:de,requestedQuantity:de.optional(),overageBehavior:Ta.optional(),accepted:ne.boolean(),reason:ne.enum([...Na.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(em).max(500)}).strict().refine(e=>yo(()=>e.accepted?e.reason===null&&Xp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>yo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&pn(e.requestedQuantity,6)>=pn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as Fe}from"zod";var Ur=Fe.iso.datetime({offset:!0}),nm=de.refine(e=>/[1-9]/.test(e)),rm=Fe.strictObject({interval:Zp.exclude(["lifetime"]),count:Wp}),$b=Fe.strictObject({action:Fe.literal("create"),requestId:Fe.uuid(),internal_feature_id:Fe.uuid(),entityId:Fe.uuid().nullable(),amount:nm.nullable(),expiresAt:Ur.nullable(),reset:rm.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),im=Fe.discriminatedUnion("action",[$b,Fe.strictObject({action:Fe.literal("update"),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative(),amount:nm.nullable(),expiresAt:Ur.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable()}),Fe.strictObject({action:Fe.enum(["add","subtract","set_remaining"]),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative(),amount:de}),Fe.strictObject({action:Fe.literal("revoke"),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative()})]),qc=Fe.strictObject({id:Fe.uuid(),internal_feature_id:Fe.uuid(),entityId:Fe.uuid().nullable(),amount:de.nullable(),reset:rm.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable(),startsAt:Ur,expiresAt:Ur.nullable(),revision:Fe.number().int().nonnegative(),revoked:Fe.boolean(),available:tn,held:tn,spent:tn}),om=Fe.strictObject({customerId:Fe.uuid(),after:Fe.uuid().nullable(),limit:Fe.number().int().min(1).max(100)}),am=Fe.strictObject({rows:Fe.array(qc).max(100),nextCursor:Fe.uuid().nullable()});import{z as ie}from"zod";var Bn=ie.iso.datetime({offset:!0}),sm=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),Gb=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Bn.nullable(),endsAt:Bn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),cm=ie.strictObject({invoice:fo,items:ie.array(ie.discriminatedUnion("kind",[Gb,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:de,reserved:de,amountMinor:bi,grossAmountMinor:bi,creditsAppliedMinor:bi,properties:Ot,cashPrice:mo,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:de,reserved:de,amountMinor:bi,cashPrice:mo})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),Kb=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Uc=ie.strictObject({from:Bn,to:Bn,entityId:ie.uuid().optional(),snapshotAt:Bn.nullable(),after:ie.strictObject({at:Bn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),um=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Bn,to:Bn,snapshotAt:Bn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:tn,refunded:tn,net:Kb})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Bn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:qr,amount:tn,pricing:ie.array(Mc).max(12),properties:Ot})).max(100),nextCursor:Uc.shape.after});import{z as D}from"zod";import{z as _n}from"zod";var Hb=_n.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Qb=_n.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Da=_n.strictObject({internal_feature_id:_n.uuid(),entityId:_n.uuid().nullable()}),lm=Da.extend({quantity:de,expectedRevision:_n.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:_n.string().min(1).max(120),properties:Ot.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),xo=Da.extend({operationId:_n.uuid().nullable(),usage:de,capacity:Hb.nullable(),remaining:Qb.nullable(),withinLimit:_n.boolean(),revision:_n.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:_n.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Jt=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),En=D.iso.datetime({offset:!0}),Jb=D.enum(["access","metered","credit"]),So={internal_feature_id:D.uuid(),key:Tr,name:D.string().min(1).max(120),kind:Jb},dm=D.object({customerId:D.uuid(),snapshotAt:En,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:En,benefitsAppliedAt:En.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.object({phase:D.enum(["paid","trial"]),startsAt:En,endsAt:En.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...So,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:Jt,held:Jt,debt:Jt,nextExpiresAt:En.nullable(),usage:xo.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.boolean()}).strict(),pm=D.enum(["source","usage","transaction","invoice","debt","settlement"]),Fa=D.object({at:En,id:D.uuid(),type:pm}).strict(),mm=D.object({type:pm.nullable(),resourceKey:Tr.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:Fa.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),xi={id:D.uuid(),occurredAt:En},Zb=D.discriminatedUnion("type",[D.strictObject({...xi,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:Jt,refunded:Jt,currency:Ie,externalId:D.string().nullable()}),D.object({...xi,...So,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Jt,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:En,expiresAt:En.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...xi,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:de,accepted:D.boolean(),reason:D.enum([...Na.options,"expired"]).nullable(),properties:Ot,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:En.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:qr,amount:Jt}),D.strictObject({funding:D.literal("unbilled"),units:qr}),D.object({...So,funding:D.literal("prepaid"),amount:Jt}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:de,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.object({...xi,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.object({...xi,...So,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:Jt}).strict(),D.object({...xi,...So,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:Jt}).strict()]),fm=D.object({customerId:D.uuid(),rows:D.array(Zb).max(50),nextCursor:Fa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as he}from"zod";var gm=he.object({customerId:he.uuid()}).strict(),ym=he.discriminatedUnion("action",[he.object({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("assign"),poolId:he.uuid(),memberCustomerId:he.uuid()}).strict(),he.strictObject({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("assign_entity"),poolId:he.uuid(),entityId:he.uuid()}),he.object({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("release"),poolId:he.uuid(),slotId:he.uuid()}).strict()]),Io=he.number().int().nonnegative(),Bc=he.iso.datetime({offset:!0}),Vc=he.strictObject({internalId:he.uuid(),id:he.string(),name:he.string().nullable(),version:he.number().int().positive()}),hm=he.enum(["active","past_due"]),Lc=he.strictObject({customerId:he.uuid(),licenses:he.array(he.strictObject({id:he.uuid(),linkId:he.uuid(),parent:he.strictObject({customerProductId:he.uuid(),status:hm,product:Vc}),product:Vc,planLicense:he.strictObject({id:he.uuid(),prepaidOnly:he.boolean(),isCustom:he.boolean()}).nullable(),granted:Io,included:Io,paidQuantity:Io,usage:Io,remaining:Io,createdAt:Bc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:he.array(he.strictObject({id:he.uuid(),linkId:he.uuid(),status:hm,product:Vc,entity:he.strictObject({internalId:he.uuid(),id:he.string().nullable(),name:he.string().nullable()}).nullable(),beneficiary:he.strictObject({internalId:he.uuid(),id:he.string().nullable(),name:he.string().nullable()}).nullable(),startedAt:Bc.nullable(),endedAt:Bc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:he.boolean()});import{z as fe}from"zod";var vo=fe.enum(["email","sms","voice","push"]),n_=fe.enum(["resend","twilio","fcm","apns"]);var r_=fe.string().regex(/^\+[1-9]\d{1,14}$/),Wb=fe.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Yb=fe.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Xb=fe.strictObject({subject:Yb,html:fe.string().min(1).max(131072).optional(),text:fe.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ex=fe.strictObject({body:fe.string().min(1).max(1600).refine(e=>e.trim().length>0)}),tx=fe.strictObject({text:fe.string().trim().min(1).max(4e3),language:fe.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:fe.number().int().min(1).max(900)}),nx=fe.record(fe.string().min(1).max(64),fe.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),rx=fe.strictObject({title:fe.string().trim().min(1).max(200),body:fe.string().trim().min(1).max(2e3),url:fe.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:nx.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Am=fe.discriminatedUnion("channel",[fe.strictObject({channel:fe.literal("email"),content:Xb}),fe.strictObject({channel:fe.literal("sms"),content:ex}),fe.strictObject({channel:fe.literal("voice"),content:tx}),fe.strictObject({channel:fe.literal("push"),content:rx})]),bm=fe.strictObject({requestId:fe.uuid(),customerId:fe.uuid(),connectionId:fe.uuid().optional(),message:Am,expiresAt:fe.iso.datetime({offset:!0})}),ix=fe.array(fe.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),ox=fe.discriminatedUnion("kind",[fe.strictObject({kind:fe.literal("all")}),fe.strictObject({kind:fe.literal("customers"),customerIds:ix})]),i_=fe.strictObject({name:fe.string().trim().min(1).max(120),connectionId:fe.uuid().optional(),message:Am,audience:ox,frequencyLimit:fe.number().int().min(1).max(100)}),xm=fe.strictObject({requestId:fe.uuid(),channel:vo,state:fe.enum(["allowed","denied"]),expectedRevision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Sm=fe.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Im=fe.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),o_=fe.strictObject({meter:Wb,estimatedUnits:fe.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:fe.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as Si}from"zod";var wo=Si.strictObject({internalFeatureId:Si.uuid(),name:Si.string().min(1).max(120),includedAmount:Si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Si.enum(["hour","day","week","month","year","lifetime"]),resetCount:Si.number().int().min(1).max(100),terms:Ia});var qa=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ma=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),Ii=re.object({paywall:sr.optional(),nodes:re.record(re.string(),re.object({base:Ma,picker:re.string().optional(),byPlan:re.record(re.string(),Ma).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(wo).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function vm(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function ax(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function wm(e){let t={};function n(r){var i;if(ax(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}import{z as er}from"zod";var Om=er.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ua=er.strictObject({tiers:er.array(er.strictObject({id:Om,name:er.string().trim().min(1).max(80)})).min(1).max(8),assignments:er.array(er.strictObject({productVersionId:er.string().min(1).max(200),tierId:Om,period:er.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Ba(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var sx=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Pm=ce.enum(sx),Cm=ce.object({source:Pm,layout:ce.enum(["full","compact"]),resourceKey:Tr.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Tt=ce.string().max(2e3),_m=ce.object({id:ce.string().max(100),label:Tt,detail:ce.array(Tt).max(12),value:Tt.optional(),status:Tt.optional(),facts:ce.array(ce.object({label:Tt,value:Tt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Tt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Tt}).strict()).max(3).optional()}).strict(),cx=ce.object({key:Tr,name:Tt,spendable:Tt,reserved:Tt,available:Tt,expiry:Tt.nullable(),sources:ce.array(_m).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),ux=ce.object({source:Pm,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Tt.optional(),resources:ce.array(cx).max(500),rows:ce.array(_m).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Tt,note:Tt,facts:ce.array(ce.object({label:Tt,value:Tt}).strict()).max(100)}).strict().optional(),membershipResult:Tt.optional()}).strict(),Em=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ux)}).strict(),x_=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.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:ce.string().max(100).optional()}).strict();import{z as K}from"zod";var vt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},km=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Ut=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!km.has(e),"Reserved UI identifier"),zc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),lx=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(zc).min(1).max(vt.enumValues),default:zc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function Gc(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var dx=lx.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),Gc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),px=["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 mx(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var Vr=K.lazy(()=>K.union([zc,K.strictObject({ref:Ut}),K.strictObject({op:K.enum(px),args:K.array(Vr).max(vt.expressionNodes)}).superRefine((e,t)=>{mx(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function Rn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Br(e,t,n){if(!e||typeof e!="object")return!0;if(!Rn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(km.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function vi(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>vt.expressionNodes||a.depth>vt.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Br(a.value,t,a.path))return;if(Rn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>vt.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var v_=K.unknown().superRefine((e,t)=>{vi(e,t,[],{nodes:0})}).pipe(Vr),$c=K.record(Ut,Vr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=vt.state,"UI assignments need 1\u201332 state keys"),fx=K.strictObject({target:Ut,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Vr,className:Ut.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),hx=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Ut,state:Ut}),K.strictObject({type:K.literal("input"),target:Ut,state:Ut,set:$c.optional()}),K.strictObject({type:K.literal("action"),target:Ut,set:$c}),K.strictObject({type:K.literal("carousel"),target:Ut,state:Ut,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Ut.optional(),nextTarget:Ut.optional(),inactiveTargets:K.array(Ut).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),gx=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:$c}),yx=K.strictObject({type:K.literal("mosaic_waves"),target:Ut,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Vr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),Ax=K.strictObject({type:K.literal("number_counter"),target:Ut,value:Vr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),bx=K.strictObject({state:K.record(Ut,dx).refine(e=>Object.keys(e).length<=vt.state,"Too many UI state keys").optional(),derived:K.record(Ut,Vr).refine(e=>Object.keys(e).length<=vt.derived,"Too many UI derived keys").optional(),bindings:K.array(fx).max(vt.bindings).optional(),controls:K.array(hx).max(vt.controls).optional(),timers:K.array(gx).max(vt.timers).optional(),effects:K.array(K.discriminatedUnion("type",[yx,Ax])).max(vt.effects).optional(),clock:K.boolean().optional()});function xx(e,t){if(!Br(e,t,[])||!Rn(e))return;for(let[r,i]of[["state",vt.state],["derived",vt.derived]]){let a=e[r];if(!Br(a,t,[r]))return;if(Rn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",vt.bindings],["controls",vt.controls],["timers",vt.timers],["effects",vt.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!Br(i,t,["effects",r]))return}if(Rn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Br(i,t,["state",r]))return;if(Rn(i)&&Array.isArray(i.values)&&i.values.length>vt.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(Rn(e.derived))for(let[r,i]of Object.entries(e.derived))vi(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!Br(o,t,[r,a])||!Rn(o))){if(r==="bindings")vi(o.expression,t,[r,a,"expression"],n);else if(Br(o.set,t,[r,a,"set"])&&Rn(o.set)){if(Object.keys(o.set).length>vt.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))vi(c,t,[r,a,"set",s],n)}if(n.nodes>vt.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())Rn(i)&&i.type==="number_counter"?vi(i.value,t,["effects",r,"value"],n):Rn(i)&&i.enabled!==void 0&&vi(i.enabled,t,["effects",r,"enabled"],n)}function Rm(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var jm=K.unknown().superRefine(xx).pipe(bx).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(h,d)=>{for(let g of Rm(h))i.has(g)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${g}`})};for(let[h,d]of Object.entries(e.derived??{}))Object.hasOwn(n,h)&&t.addIssue({code:"custom",path:["derived",h],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",h]);let o=new Set,s=new Set,c=h=>{if(o.has(h))return!1;if(s.has(h))return!0;o.add(h);for(let d of Rm(r[h]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(h),s.add(h),!0};for(let h of Object.keys(r))if(!c(h)){t.addIssue({code:"custom",path:["derived",h],message:"Cyclic UI derived references"});break}for(let[h,d]of(e.bindings??[]).entries())a(d.expression,["bindings",h,"expression"]);let u=new Set;for(let[h,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",h,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",h,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",h,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",h,"enabled"]);let l=(h,d)=>{for(let[g,R]of Object.entries(h))Object.hasOwn(n,g)||t.addIssue({code:"custom",path:[...d,g],message:"UI assignments can only update declared state"}),a(R,[...d,g])},p=new Set,m=new Set;for(let[h,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",h,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let g of d.inactiveTargets??[])(g===d.target||m.has(g))&&t.addIssue({code:"custom",path:["controls",h,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),m.add(g);if(d.type==="carousel")for(let g of["previousTarget","nextTarget"]){let R=d[g];R!==void 0&&((R===d.target||p.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",h,g],message:"Carousel navigation needs a distinct, exclusive button target"}),p.add(R))}if(d.type!=="action"){let g=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!g||d.type==="input"&&g.type==="enum"&&g.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",h,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(g?.type!=="number"||!Number.isInteger(g.min)||g.min<0||!Number.isInteger(g.max)||g.step!==1||d.initialIndex!==void 0&&!Gc(g,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",h],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&g?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",h,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",h,"set"])}for(let[h,d]of(e.timers??[]).entries())l(d.set,["timers",h,"set"])});import{z as ct}from"zod";var Sx=ct.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Va=ct.discriminatedUnion("type",[ct.object({type:ct.literal("fixed"),productVersionId:ct.string().min(1).max(200)}).strict(),ct.object({type:ct.literal("picker"),pickerId:Sx,allowedProductVersionIds:ct.array(ct.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Ix=ct.strictObject({min:ct.number().finite().min(1).max(1800),max:ct.number().finite().min(1).max(1800),viewport:ct.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Tm={desktopWidth:Ix.optional(),mobile:ct.enum(["sheet","fullscreen"]).optional(),backdrop:ct.enum(["none","scrim","dim","strong-dim","blur"]).optional()},kn=ct.discriminatedUnion("type",[ct.strictObject({type:ct.literal("modal"),size:ct.enum(["sm","md","lg"]),...Tm}),ct.strictObject({type:ct.literal("sheet"),size:ct.enum(["sm","md","lg"]),...Tm}),ct.strictObject({type:ct.literal("fullscreen")}),ct.strictObject({type:ct.literal("inline")})]);var wx=4,Tn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},Po=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ve=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ox=I.enum(["none","xs","sm","md","lg","xl"]),Px=I.enum(["none","sm","md","lg","full"]),Kc=I.string().regex(/^#[0-9a-fA-F]{6}$/),Qc=I.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Hc=I.union([Qc,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Nm=I.object({primary:Kc,background:Kc,text:Kc,radius:Px,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:Qc,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),Co=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ue=(e,t)=>I.number().int().min(e).max(t),Dm=I.union([I.enum(["fit","fill"]),Ue(1,1200)]),Cx=I.object({top:Ue(0,200),right:Ue(0,200),bottom:Ue(0,200),left:Ue(0,200)}).strict(),_x=I.object({top:Ue(-100,200),right:Ue(-100,200),bottom:Ue(-100,200),left:Ue(-100,200)}).strict(),Fm=I.object({x:Ue(0,100),y:Ue(0,100)}).strict(),Ex=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:Co}).strict(),I.object({type:I.literal("linear"),angle:Ue(0,360),stops:I.array(I.object({color:Co,at:Ue(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:Hc,fit:I.enum(["cover","contain"]),position:Fm.optional()}).strict()]),Rx=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Ue(0,200),I.object({topLeft:Ue(0,200),topRight:Ue(0,200),bottomRight:Ue(0,200),bottomLeft:Ue(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),kx=I.object({width:Ue(0,12),color:Co,style:I.enum(["solid","dashed"])}).strict(),jx=I.object({x:Ue(-40,40),y:Ue(-40,40),blur:Ue(0,80),spread:Ue(-20,40),color:Co}).strict(),Tx=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Ue(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:Co,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),Lr=I.object({width:Dm,height:Dm,padding:Cx,margin:_x,gap:Ue(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Ex,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Rx,border:kx,shadow:jx,text:Tx}).strict().partial(),an={id:Po,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:Lr.optional(),fallback:Ve.optional()},Nx=I.object({...an,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:Ve,variant:I.enum(["title","heading","body","caption"])}).strict(),Dx=I.object({...an,type:I.literal("image"),src:Hc,localizedSrc:I.record(Cn,Hc).optional(),alt:Ve,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Fm.optional()}).strict(),Fx=I.object({...an,type:I.literal("button"),label:Ve,variant:I.enum(["primary","secondary","link"]),action:Ve,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:qa.optional()}).strict(),Mx=I.object({...an,type:I.literal("divider")}).strict(),qx=I.object({...an,type:I.literal("customer_data"),title:Ve,data:Cm}).strict(),Ux=I.object({...an,type:I.literal("spacer"),size:Ox}).strict(),Bx=I.object({...an,type:I.literal("custom_html"),html:I.record(Cn,I.string().max(Tn.customHtml)),css:I.string().max(Tn.customCss),ui:jm.optional()}).strict(),Vx=I.object({...an,type:I.literal("price"),fallback:Ve,parts:I.object({current:Lr.optional(),original:Lr.optional(),period:Lr.optional()}).strict().optional()}).strict(),Lx=I.object({...an,type:I.literal("coupon_code"),label:Ve,fallback:Ve}).strict(),zx=I.object({...an,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:Ve,fallback:Ve}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),$x=I.object({...an,type:I.literal("plan_picker"),label:Ve,fallback:Ve,planIds:I.array(I.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.string().min(1).max(200).optional(),grouping:Ua.safeExtend({monthLabel:Ve,yearLabel:Ve,unavailableLabel:Ve}).optional(),states:I.object({selected:Lr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ba(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Gx=I.object({...an,type:I.literal("quantity_picker"),bind:qa.optional(),label:Ve,fallback:Ve,internalFeatureId:I.uuid(),minimumQuantity:Ue(0,1e4),maximumQuantity:Ue(0,1e4),defaultQuantity:Ue(0,1e4),step:Ue(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),Kx=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:Ve,keyboard:I.enum(["text","email","tel","url"]),maxLength:Ue(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:Ve,min:Ue(0,50),max:Ue(1,50)}).strict(),I.object({type:I.literal("select"),label:Ve,defaultIndex:Ue(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:Po.optional(),selectedStyle:Lr.optional()}).strict(),I.object({type:I.literal("tabs"),label:Ve,defaultIndex:Ue(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:Ve,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:Ve}).strict()]),jn={...an,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Ue(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:Kx.optional(),states:I.object({selected:Lr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:Ve.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:qa.optional()},Mm=I.lazy(()=>I.object({...an,type:jn.type,direction:jn.direction,align:jn.align,justify:jn.justify,children:I.array(Hx).max(Tn.children),productSlot:jn.productSlot,interaction:jn.interaction,states:jn.states,purpose:jn.purpose,purchaseAction:jn.purchaseAction,buttonVariant:jn.buttonVariant,bind:jn.bind}).strict()),Hx=I.lazy(()=>I.union([Mm,Nx,Dx,Fx,Mx,Ux,Bx,Vx,Lx,zx,$x,Gx,qx])),Qx=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),Oo={id:Ve,event:Ve,properties:I.record(Ve,Qx).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Jx=I.discriminatedUnion("type",[I.object({...Oo,type:I.literal("navigate"),close:I.literal(!1),pageId:Po}).strict(),I.object({...Oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...Oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...Oo,type:I.literal("open_url"),close:I.boolean(),url:Qc}).strict(),I.object({...Oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),Zx=I.object({defaultLocale:Cn,locales:I.record(Cn,I.record(Ve,I.string().max(Tn.stringLength)))}).strict(),Wx=I.enum(["popup","paywall","onboarding","page","banner"]);var Yx=I.object({kind:I.literal("screen"),schemaVersion:I.literal(wx),name:I.string().trim().min(1).max(80),surface:Wx,initialPageId:Po.optional(),presentation:kn,theme:Nm,pages:I.array(I.object({id:Po,name:I.string().trim().min(1).max(60),root:Mm,theme:Nm.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Tn.pages),strings:Zx,actions:I.array(Jx).max(Tn.actions)}).strict();function Zt(e,t){for(let n of e.pages)tr(n.root,t)}var mn=Yx.superRefine((e,t)=>{let n=Tn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(p=>p.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Tn.locales&&r(`\u6700\u591A ${Tn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Zt(e,(l,p)=>{if(c++,p>Tn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Tn.depth} \u5C42`)});function tr(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)tr(i,t,n+1,e)}function La(e){let t=[],n=new Set;return Zt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Xx(e,t,n){if(t.field==="html"){let r;return Zt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=_o(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function mr(e){let t=La(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!Xx(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function eS(e,t){let n=null;return tr(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function _o(e,t){for(let n of e.pages){let r=eS(n.root,t);if(r)return r}return null}import{z as $t}from"zod";var wt=$t.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Jc=$t.strictObject({type:$t.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:$t.boolean(),enum:$t.array($t.string().max(255)).min(1).max(100).optional()}),wi=Jc.extend({type:$t.enum([...Jc.shape.type.options,"array"]),items:Jc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),Oi=wi.safeExtend({source:$t.discriminatedUnion("type",[$t.strictObject({type:$t.literal("input")}),$t.strictObject({type:$t.literal("node")}),$t.strictObject({type:$t.enum(["parameter","attribute"]),key:wt})])}),q_=$t.record(wt,Oi),Zc=$t.record(wt,wt).refine(e=>Object.keys(e).length<=20);function xn(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>xn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&$t.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Wc(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Wc(e.items,t.items)}function za(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!xn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Pi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function qm(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!xn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as zr}from"zod";var Nn=zr.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Vn=zr.discriminatedUnion("source",[zr.strictObject({source:zr.literal("literal"),value:ve}),zr.strictObject({source:zr.literal("variable"),key:zr.string().min(1).max(255),path:Nn.optional()})]);function Um(e,t){if(!t)return e;for(let n of Nn.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Yc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=za(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(Um(n[e.key],e.path)))}function Xc(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!Nn.safeParse(r).success?null:{key:n,path:r}}function eu(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Zt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(vm))]}function $a(e){return eu(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function fn(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),p=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):p)+Number(u),h=m<=0?2-m+p:m>=p?m:p+1;n+=h+(c.startsWith("-")?1:0)-s.length}}return n}var fr=Ce.enum(["page","popup","banner"]),tS=3e5,Bm=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),nS=Ce.strictObject({inputs:Ce.record(Ve,Bm.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(Ve,Bm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),rS=Ce.strictObject({kind:fr,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:mn,contract:nS}),Ga=rS.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),fn(e)>tS&&n("Content document exceeds its byte budget",[])});function iS(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var oS=Ga.superRefine((e,t)=>{for(let n of $a(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!iS(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}mr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Vm=Ce.strictObject({id:Ce.uuid(),kind:fr,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),e1=Vm.extend({draft:Ga}),t1=Ce.strictObject({rows:Ce.array(Vm).max(200),nextCursor:Ce.uuid().nullable()}),tu=Ce.strictObject({id:Ce.uuid(),kind:fr,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:oS,createdAt:Ce.iso.datetime({offset:!0})}),n1=tu.omit({document:!0}),r1=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:fr,id:Ce.uuid(),document:Ga}),Ce.strictObject({action:Ce.literal("save"),kind:fr,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:Ga}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:fr,id:Ce.uuid(),revision:Ce.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as Lm}from"zod";var Ci={funnelId:Lm.uuid().optional(),funnelVersionId:Lm.uuid().optional()};import{z as Ka}from"zod";var Ha=Ka.strictObject({runId:Ka.uuid(),bindingId:Ka.uuid(),receiptId:Ka.uuid()});import{z as ut}from"zod";import{z as Le}from"zod";import{z as rt}from"zod";var l1=rt.discriminatedUnion("action",[rt.strictObject({action:rt.literal("create"),couponId:rt.uuid(),productBindingId:rt.uuid(),storeOfferId:rt.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:rt.enum(["introductory","promotional"])}),rt.strictObject({action:rt.literal("set_enabled"),id:rt.uuid(),revision:rt.number().int().nonnegative(),enabled:rt.boolean()})]),d1=rt.array(rt.strictObject({id:rt.uuid(),couponId:rt.uuid(),productBindingId:rt.uuid(),storeOfferId:rt.string().min(1).max(255).nullable(),storeOfferType:rt.enum(["introductory","promotional"]),enabled:rt.boolean(),revision:rt.number().int().nonnegative()})).max(500),_i=rt.strictObject({offerKind:rt.enum(["none","introductory","promotional"]),offerId:rt.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:rt.number().int().min(0).max(1e8),trialDays:rt.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),p1=rt.record(rt.uuid(),_i).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var nu=Le.object({type:Le.literal("native_purchase"),receiptId:Le.uuid(),orderId:Le.uuid(),productVersionId:Le.uuid(),provider:Le.enum(["apple","google"]),productId:Le.string().min(1).max(255),productKind:Ud,replacement:Le.strictObject({sourceOrderId:Le.uuid(),sourceProductId:Le.string().min(1).max(255),policy:Le.enum(["apple_store","google_full_price"]),sourceAccountTokens:Le.array(Le.uuid()).max(50)}).nullable(),appAccountToken:Le.uuid().optional(),obfuscatedAccountId:Le.string().min(1).max(64).optional(),obfuscatedProfileId:Le.uuid().optional(),basePlanId:Le.string().min(1).max(255).optional(),offerId:Le.string().min(1).max(255).optional(),offerKind:Le.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Le.number().int().nonnegative().max(1e8),discountMinor:Le.number().int().nonnegative().max(1e8),trialDays:Le.number().int().min(1).max(730).nullable(),seatBundle:Le.array(Le.strictObject({key:Le.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Le.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Le.strictObject({offerId:Le.string().min(1).max(255),keyId:Le.string().min(1).max(255),nonce:Le.uuid(),signature:Le.string().min(1).max(1024),timestamp:Le.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as f}from"zod";import{z as _e}from"zod/v4";import{z as aS}from"zod/v4";var sS=aS.registry(),{BillingInterval:zm}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:cS}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e),{withSpecDefault:uS}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(sS),{COMMON:$m}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:lS}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:dS}=(e=>({COMMON_SET:new Set(e)}))($m),{hasNoDuplicateCurrencies:Gm}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Km}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:pS}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:mS}={Infinite:"inf"},{TierBehavior:fS}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Hm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:hS}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:gS}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:yS}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:AS}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:Qm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e),{VIOLATION_MESSAGES:bS}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:Jm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:xS}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e,Jm),{InvoiceUsageEntrySchema:SS}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e),{AttachDiscountSchema:Zm}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e),{CustomLineItemSchema:IS}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e),{UnixMsTimestampSchema:vS}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:wS}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e),{ReissueInvoiceParamsSchema:Wm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e),{InvoiceModeParamsSchema:$r}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(_e),{InvoiceTemplateSchema:OS}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e),{BasePriceSchema:PS}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e,zm,cS),{CURRENCY_CODES:CS}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))($m,lS,dS),{ApiPriceProcessorsSchema:Ym}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,pS),{AllocatedBillingFieldSchema:_S}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e,hS),{CreditDimensionNameSchema:ES}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,gS,yS),{ApiCreditMatchSchema:Xm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(AS),{findCreditTierViolations:RS}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(bS),{ApiCreditMultiplierSchema:kS}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e,Xm),{ProviderMarkupsSchema:jS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,Jm),{InvoiceFeatureQuantitySchema:ef}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e,Hm,SS),{CreateInvoicePreviewSchema:ru}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e,wS),{SUPPORTED_SET:TS}=(e=>({SUPPORTED_SET:new Set(e)}))(CS),{ApiCreditDimensionBaseSchema:NS}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e,Xm),{refineGraduatedTiers:tf}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(RS),{ApiFeatureMarkupsOverrideSchema:DS}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e,jS,xS),{isValidCurrencyCode:FS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(TS),{ApiCreditDimensionSchema:MS}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e,NS,Qm,tf),{CurrencyCodeSchema:nf}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e,FS),{AdditionalCurrencyTierSchema:qS}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e,nf),{ApiCreditSchemaItemBaseSchema:rf}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e,ES,MS,kS),{ApiFlatCreditSchemaItemSchema:US}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(rf,_e),{AdditionalCurrencyPriceSchema:BS}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e,nf),{AdditionalCurrencyTierArraySchema:VS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,qS,Gm,Km),{ApiGraduatedCreditSchemaItemSchema:LS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(rf,_e,Qm,tf),{AdditionalCurrencyPriceArraySchema:of}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,BS,Gm,Km),{ApiUsageTierWithCurrenciesSchema:zS}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e,mS,VS),{ApiCreditSchemaItemSchema:$S}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,LS,US),{BasePriceParamsSchema:GS}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(PS,uS,_e,of),{PlanItemPriceParamsSchema:KS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e,of,zS,fS,zm,Hm,_S),{ApiFeatureOverrideSchema:HS}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e,$S,DS),{InvoiceBasePriceParamsSchema:af}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(GS,Ym),{InvoiceItemPriceParamsSchema:QS}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(KS,Ym),{InvoiceLicenseQuantitySchema:JS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e,af,ef),{InvoiceCustomizeItemSchema:ZS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e,QS,HS),{InvoiceCustomizeSchema:WS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e,af,ZS),{InvoicePlanParamsSchema:YS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e,WS,ef,JS,Zm),{CreateInvoiceParamsSchema:Ei}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e,YS,IS,Zm,vS);var uf=f.strictObject({requestId:f.uuid(),predecessorOperationId:f.uuid().optional(),invoiceMode:$r.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:_i.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(ya,f.number().int().min(0).max(1e4)).optional(),featureQuantities:f.record(f.uuid(),f.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:f.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Kr=f.strictObject({operationId:f.uuid()}),Bt=f.number().int().min(0).max(1e8),XS=f.strictObject({lineId:f.uuid(),productVersionId:f.uuid(),productName:f.string().min(1).max(80),interval:f.enum(["free","week","month","year","one_time"]),intervalCount:f.number().int().min(1).max(156).optional(),baseAmountMinor:Bt,seats:f.array(f.strictObject({key:ya,quantity:f.number().int().min(0).max(1e4),includedQuantity:f.number().int().min(0).max(1e4),maximumQuantity:f.number().int().min(0).max(1e4),unitAmountMinor:Bt})).max(20),prepaid:f.array(Yp).max(100).optional(),catalogAmountMinor:Bt,trial:Xi.nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Sa({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),lf=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),e0=f.strictObject({id:lf,name:f.string().min(1).max(40),percent_off:f.number().gt(0).max(100).optional(),amount_off:f.number().int().positive().optional(),currency:f.string().regex(/^[a-z]{3}$/).optional(),duration:f.enum(["once","repeating","forever"]),duration_in_months:f.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),t0=f.strictObject({subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.array(f.strictObject({id:f.string(),price_id:f.string(),quantity:f.number().int().nonnegative(),discounts:f.array(f.strictObject({id:f.string(),coupon:f.string(),start:f.number(),end:f.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.number().int().nonnegative(),amountMinor:f.number().int().positive(),periodStartMs:f.number(),periodEndMs:f.number()}),df=f.strictObject({invoiceMode:$r.optional(),append:t0.optional(),provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.enum(["payment","subscription"]),lineItems:f.array(f.strictObject({price:f.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.number().int().min(1).max(1e4),priceId:f.uuid(),productName:f.string().min(1).max(80),amountMinor:f.number().int().min(0).max(1e8),currency:f.string().regex(/^[a-z]{3}$/),interval:f.enum(["week","month","year","one_off"]),intervalCount:f.number().int().min(1).max(52),slot:f.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.strictObject({mode:f.enum(["graduated","volume"]),tiers:f.array(f.strictObject({upTo:f.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.number().int().min(0).max(1e8),flatAmountMinor:f.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.array(f.strictObject({coupon:lf,terms:e0})).max(1),trialPeriodDays:f.number().int().min(1).max(730).nullable(),metadata:f.strictObject({grooveCheckoutId:f.uuid(),grooveCustomerId:f.uuid()}),expiresAt:f.iso.datetime({offset:!0})}),Ri=f.strictObject({operationId:f.uuid(),merchantTerms:pi.optional(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:dr,duration:dn,amountMinor:Bt,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:Bt})).min(1).max(20),expiresAt:f.iso.datetime({offset:!0})}).nullable(),charge:f.strictObject({effectiveAt:f.iso.datetime({offset:!0}),periodEndsAt:f.iso.datetime({offset:!0}),debitMinor:Bt,discountMinor:Bt,taxMinor:Bt,totalMinor:Bt}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google","merchant"]),nativeOffer:_i.optional(),currency:Ie,lines:f.array(XS).min(1).max(20),catalogAmountMinor:Bt,automaticTax:f.boolean(),execution:f.union([df,oa]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ki=f.strictObject({operationId:f.uuid(),orderId:f.uuid(),append:f.boolean().optional(),invoiceMode:f.boolean().optional(),status:f.enum(["pending","complete","cancelled","failed"]),executor:f.enum(["indiana","merchant"]),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:f.union([df,oa]).nullable(),currency:Ie,catalogAmountMinor:Bt,taxMinor:Bt,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:nu.nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),quote:Ri.optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),authority:ga.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Ja=f.strictObject({enabled:f.literal(!0),featureIds:f.array(f.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),pf=f.strictObject({requestId:f.uuid(),invoiceMode:$r.optional(),membershipId:f.uuid(),carryOverBalances:Ja.optional(),carryOverUsages:Ja.optional(),membershipIds:f.array(f.uuid()).min(1).max(20).optional(),prorationBehavior:f.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.enum(["immediate","renewal","store"]),change:f.discriminatedUnion("type",[f.strictObject({type:f.literal("plan"),productVersionId:f.uuid()}),f.strictObject({type:f.literal("seats"),licenseKey:ya,quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("quantity"),internal_feature_id:f.uuid(),quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("cancel")}),f.strictObject({type:f.literal("uncancel")}),f.strictObject({type:f.literal("billing_cycle"),billingCycleAnchor:f.union([f.literal("now"),f.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Qa=f.string().regex(/^price_[A-Za-z0-9]+$/),sf=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),cf=f.strictObject({price:Qa.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),mf=f.strictObject({provider:f.literal("stripe"),invoiceMode:$r.optional(),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.enum(["update","cancel","schedule","release"]),update:f.strictObject({items:f.array(cf).max(20),remove:f.array(Qa).max(20),restoreItems:f.array(f.strictObject({price:Qa,quantity:f.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.number().int().positive().optional(),paymentBehavior:f.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.boolean().optional(),clearCancelAt:f.literal(!0).optional(),billingCycleAnchorNow:f.literal(!0).optional(),metadata:sf}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:Qa,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(cf).min(1).max(20),switchAt:f.number().int().positive(),interval:f.enum(["week","month","year"]),intervalCount:f.number().int().min(1).max(52),resetBillingCycleAnchor:f.literal(!0).optional(),metadata:sf}).nullable(),release:f.strictObject({schedule:f.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Za=f.strictObject({merchantTerms:pi.optional(),carryOverBalances:Ja.optional(),carryOverUsages:Ja.optional(),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),expiresAt:f.iso.datetime({offset:!0}),currency:Ie,creditMinor:Bt,debitMinor:Bt,discountMinor:Bt,taxMinor:Bt,totalMinor:Bt,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:f.union([mf,nr])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"subscription_change",e.currency)),n0=f.strictObject({operationId:f.uuid(),invoiceMode:f.boolean().optional(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.enum(["indiana","merchant"]),execution:f.union([mf,nr]).nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),quote:Za.optional(),authority:ga.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),r0=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.literal("store"),effectiveAt:f.null(),expiresAt:f.iso.datetime({offset:!0}),currency:Ie,creditMinor:f.null(),debitMinor:f.null(),discountMinor:f.null(),taxMinor:f.null(),totalMinor:f.null(),retainedProductVersionIds:f.array(f.uuid()).max(19),store:f.strictObject({provider:f.enum(["apple","google"]),productId:f.string().min(1).max(255),catalogAmountMinor:Bt,policy:f.enum(["apple_store","google_full_price"])})}),i0=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.literal("store"),effectiveAt:f.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.null(),nativePurchase:nu.nullable()}),ff=f.union([Za,r0]),iu=f.union([n0,i0]),ou=dc,Gr=da,hf=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),...Nr.shape}).refine(to,"A partial refund states amountMinor; a full refund refunds the remaining amount"),gf=f.strictObject({provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:ou,currency:f.string().regex(/^[a-z]{3}$/),metadata:f.strictObject({indianaRefundId:f.uuid()}),idempotencyKey:f.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),au=f.strictObject({operationId:f.uuid(),merchantTerms:pi.optional(),invoiceId:f.uuid(),providerInvoiceId:f.string().min(1).max(200),currency:Ie,paidMinor:Gr,refundedMinor:Gr,pendingMinor:Gr,amountMinor:ou,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),revokes:f.strictObject({customerProductIds:f.array(f.uuid()).max(100),subscriptionIds:f.array(f.string().min(1).max(200)).max(20)}),execution:f.union([gf,aa]),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Wa=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().min(1).max(200),status:f.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.enum(["indiana","merchant"]),currency:Ie,amountMinor:ou,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().min(1).max(200).nullable(),quote:au.optional(),execution:f.union([gf,aa]).nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),authority:ga.optional(),failureReason:f.string().min(1).max(200).nullable(),createdAt:f.iso.datetime({offset:!0}),completedAt:f.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),D1=f.strictObject({invoiceId:f.uuid(),currency:Ie,paidMinor:Gr,refundedMinor:Gr,pendingMinor:Gr,refundableMinor:Gr,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(Wa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),F1=f.strictObject({requestId:f.uuid(),...Nr.shape}).refine(to,"A partial refund states amountMinor; a full refund refunds the remaining amount");var yf=ut.strictObject({requestId:ut.uuid(),targets:ut.array(ut.strictObject({membershipId:ut.uuid(),action:ut.enum(["cancel","uncancel"]),timing:ut.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Ya=ut.strictObject({batchId:ut.uuid()}),o0=ut.strictObject({operationId:ut.uuid(),membershipIds:ut.array(ut.uuid()).min(1).max(20),provider:ut.enum(["stripe","apple","google"]),action:ut.enum(["cancel","uncancel"]),timing:ut.enum(["immediate","renewal"]),status:ut.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Za.nullable(),managementUrl:ut.url().nullable(),failureCode:ut.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Eo=ut.strictObject({batchId:ut.uuid(),ready:ut.boolean(),status:ut.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ut.iso.datetime({offset:!0}),acceptedAt:ut.iso.datetime({offset:!0}).nullable(),groups:ut.array(o0).min(1).max(100)});import{z as Te}from"zod";var a0=Te.string().trim().min(1).max(240),su={requestId:Te.uuid(),reason:a0},Xa=Te.discriminatedUnion("action",[Te.strictObject({...su,action:Te.literal("start"),productVersionId:Te.uuid(),entityId:Te.uuid().optional(),days:Te.number().int().min(1).max(730).optional()}),Te.strictObject({...su,action:Te.literal("extend"),membershipId:Te.uuid(),days:Te.number().int().min(1).max(730)}),Te.strictObject({...su,action:Te.literal("end"),membershipId:Te.uuid()})]),Af=Te.strictObject({operationId:Te.uuid()}),bf=Te.iso.datetime({offset:!0}),s0=Te.strictObject({provider:Te.literal("stripe"),executor:Te.enum(["indiana","merchant"]),accountId:Te.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Te.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Te.union([Te.literal("now"),bf]),prorationBehavior:Te.literal("none")}),cu=Te.strictObject({operationId:Te.uuid(),action:Te.enum(["start","extend","end"]),status:Te.enum(["pending","effective"]),managedBy:Te.enum(["indiana","stripe"]),membershipIds:Te.array(Te.uuid()).min(1).max(20),endsAt:bf.nullable(),execution:s0.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),L1=Te.strictObject({groupId:Te.uuid(),productVersionId:Te.uuid(),enabled:Te.boolean()});import{z as et}from"zod";var xf=et.strictObject({requestId:et.uuid(),currency:Ie,makeDefault:et.boolean()}),Sf=et.strictObject({setupId:et.uuid()}),c0=et.strictObject({provider:et.literal("stripe"),executor:et.literal("merchant"),accountId:et.string().regex(/^acct_[A-Za-z0-9]+$/),mode:et.literal("setup"),currency:et.string().regex(/^[a-z]{3}$/),customer:et.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:et.uuid(),metadata:et.strictObject({grooveProjectId:et.uuid(),grooveEnvironmentId:et.uuid(),grooveCustomerId:et.uuid(),groovePaymentSetupId:et.uuid()}),setDefaultPaymentMethod:et.boolean(),expiresAt:et.iso.datetime({offset:!0})}),uu=et.strictObject({id:et.uuid(),provider:et.literal("stripe"),status:et.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:et.boolean(),url:et.url().nullable(),createdAt:et.iso.datetime({offset:!0}),expiresAt:et.iso.datetime({offset:!0}),completedAt:et.iso.datetime({offset:!0}).nullable(),execution:c0.nullable()});import{z as Vt}from"zod";var If=Vt.union([Vt.string(),Vt.number(),Vt.boolean(),Vt.null()]),vf=Vt.strictObject({customerId:Vt.uuid()}),wf=Vt.strictObject({customerId:Vt.uuid(),provider:Vt.literal("stripe"),checkedAt:Vt.iso.datetime({offset:!0}),status:Vt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Vt.number().int().nonnegative(),differences:Vt.array(Vt.strictObject({subscriptionId:Vt.string().startsWith("sub_"),itemId:Vt.string().nullable(),field:Vt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:If,actual:If})).max(1e4)});import{z as we}from"zod";var es=we.iso.datetime({offset:!0}),ts=we.strictObject({createdAt:es,id:we.uuid()}),ns=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:ts.optional(),limit:we.number().int().min(1).max(100).optional()}),lu={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:es},u0=we.strictObject({...lu,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),l0=we.strictObject({...lu,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),d0=we.strictObject({...lu,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:es,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:es.nullable()}),Of=ns.extend({status:we.enum(["blocked","resolved"]).optional()}),Pf=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Cf=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),_f=we.strictObject({items:we.array(u0).max(100),nextCursor:ts.nullable()}),Ef=we.strictObject({items:we.array(l0).max(100),nextCursor:ts.nullable()}),Rf=we.strictObject({items:we.array(d0).max(100),nextCursor:ts.nullable()});import{z as ot}from"zod";var kf=ot.union([ot.strictObject({intent:ot.literal("read"),requestId:ot.uuid(),purchaseIntentId:ot.uuid()}),ot.strictObject({requestId:ot.uuid(),provider:ot.literal("apple"),purchaseIntentId:ot.uuid(),productId:ot.string().min(1).max(255).optional(),signedTransaction:ot.string().min(1).max(131072)}),ot.strictObject({requestId:ot.uuid(),provider:ot.literal("google"),purchaseIntentId:ot.uuid(),productId:ot.string().min(1).max(255).optional(),purchaseToken:ot.string().min(1).max(16384)})]),jf=ot.strictObject({requestId:ot.uuid(),orderId:ot.uuid(),purchaseIntentId:ot.uuid(),status:ot.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:ot.boolean(),completion:ot.strictObject({transactionIds:ot.array(ot.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:ot.boolean()}).nullable()});import{z as L}from"zod";var pu=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),p0=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),m0=3,Ro=20,f0=m0*Ro,du=L.strictObject({type:L.literal("product"),productId:pu}),Tf={type:L.literal("group"),key:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.string().trim().min(1).max(80)},h0=L.discriminatedUnion("type",[du,L.strictObject({...Tf,items:L.array(du).max(Ro)})]),g0=L.discriminatedUnion("type",[du,L.strictObject({...Tf,items:L.array(h0).max(Ro)})]),y0=L.array(g0).max(Ro).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>Ro||i>f0)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function mu(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:mu(t))}var ji=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:y0,metadata:p0}),A0=L.strictObject({product:L.record(L.string(),L.json()),prices:L.array(L.record(L.string(),L.json())),entitlements:L.array(L.record(L.string(),L.json())),freeTrials:L.array(L.record(L.string(),L.json())),licenses:L.array(L.record(L.string(),L.json()))}),Nf=ji.extend({id:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),state:L.enum(["active","archived"]),isCurrent:L.boolean(),revision:L.number().int().nonnegative(),publishedVersionId:L.uuid().nullable(),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Df=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:ji,productEvidence:L.record(pu,A0),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=mu(e.document);(!n.length||S0(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),b0=L.strictObject({rows:L.array(Nf).max(200),versions:L.array(Df).max(500)}),nE=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:ji}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:ji}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),rE=L.strictObject({record:Nf,version:Df.nullable()}),Ff=L.discriminatedUnion("type",[L.strictObject({type:L.literal("current")}),L.strictObject({type:L.literal("id"),id:L.uuid()}),L.strictObject({type:L.literal("lookup_key"),lookupKey:L.string().min(1).max(200)}),L.strictObject({type:L.literal("version"),versionId:L.uuid()})]),x0=L.strictObject({internalId:pu,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),iE=b0.extend({products:L.array(x0).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function S0(e){let t=[];mu(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as rs}from"zod";var Mf=rs.strictObject({id:rs.uuid(),offeringId:rs.uuid(),version:rs.number().int().positive(),document:ji});import{z as Et}from"zod";import{z as Ae}from"zod";import{z as Ti}from"zod";var is=Ti.strictObject({items:Ti.array(Ti.strictObject({productVersionId:Ti.string().min(1).max(200),label:Ti.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Ti.string().min(1).max(200).nullable(),grouping:Ua.optional()});function qf(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var fu=Ae.discriminatedUnion("type",[Ae.strictObject({type:Ae.literal("event"),event:Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),Ae.strictObject({type:Ae.literal("open_url"),url:Ae.url().refine(e=>new URL(e).protocol==="https:")})]),I0=mn,v0=Ae.discriminatedUnion("type",[Ae.object({type:Ae.literal("checkout"),product:Va}).strict(),Ae.object({type:Ae.literal("close")}).strict(),Ae.object({type:Ae.literal("action"),action:fu}).strict()]),Ni=Ae.object({schemaVersion:Ae.literal(3),kind:Ae.literal("paywall"),name:Ae.string().trim().min(1).max(80),presentation:kn,requirement:Pn.optional(),products:is,offeringVersionId:Ae.uuid().nullable(),offeringId:Ae.uuid(),screen:I0,buttons:Ae.record(Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),v0)}).strict(),bE=Ni.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of O0(e))t.addIssue({code:"custom",message:r});for(let r of w0(e))t.addIssue({code:"custom",message:r});mr(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function w0(e){let t=e.products.items.map(a=>a.productVersionId),n=wm(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!Ba(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Zt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Zt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function O0(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),tr(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let p=e.buttons[u];s.id!==n.id&&p&&p.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Uf=Ae.object({id:Ae.uuid(),projectId:Ae.uuid(),environmentId:Ae.uuid(),revision:Ae.number().int().nonnegative(),state:Ae.enum(["active","archived"]),publishedVersionId:Ae.uuid().nullable(),updatedAt:Ae.iso.datetime({offset:!0}),draft:Ni}).strict(),xE=Ae.object({rows:Ae.array(Uf).max(200),nextCursor:Ae.uuid().nullable()}).strict(),SE=Uf.omit({draft:!0}).extend({name:Ae.string(),productCount:Ae.number().int().nonnegative()}).strict(),IE=Ae.discriminatedUnion("action",[Ae.object({action:Ae.literal("save"),id:Ae.uuid().nullable(),revision:Ae.number().int().nonnegative(),document:Ni}).strict(),Ae.object({action:Ae.enum(["publish","archive"]),id:Ae.uuid(),revision:Ae.number().int().nonnegative()}).strict()]),vE=Ae.object({paywalls:Ae.array(Ae.object({id:Ae.uuid(),paywallId:Ae.uuid(),version:Ae.number().int().positive(),name:Ae.string().min(1).max(80),presentation:kn,buttons:Ni.shape.buttons}).strict()).max(500),limited:Ae.boolean()}).strict();import{z as Re}from"zod";import{z as Wt}from"zod";var Di=Wt.string().regex(/^[a-f0-9]{64}$/),P0=Ma.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Bf=Wt.strictObject({couponDigests:Wt.record(Wt.uuid(),Di),variables:Wt.record(Cn,Wt.record(Wt.uuid(),Wt.partialRecord(Wt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Wt.string()))),locales:Wt.record(Cn,Ii.extend({nodes:Wt.record(Wt.string(),Wt.strictObject({base:P0})),plans:Wt.object({}).strict(),pickers:Wt.object({}).strict()}).omit({paywall:!0}))});import{z as ze}from"zod";import{z as os}from"zod";var hu=os.strictObject({eventsEnabled:os.boolean(),experimentViewsEnabled:os.boolean(),featureUsageEnabled:os.boolean()}),RE=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Vf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var gu=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),C0=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(gu).max(100)}),_0=$.strictObject({id:$.string().min(1).max(255),condition:nn,gate:$.boolean().optional()}),E0=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),Lf={condition:nn.optional(),parentConditions:$.array(_0).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(C0).max(100).optional(),ranges:$.array(gu).max(20).optional(),meta:$.array(E0).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},Fi=$.strictObject({...Lf,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),yu=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),R0=$.strictObject({...Lf,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:gu.optional(),tracks:$.array($.strictObject({experiment:Fi,result:yu})).max(100).optional()}),k0=$.strictObject({defaultValue:ve.optional(),rules:$.array(R0).max(500).optional()}),ko=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:nn})])),Sn=$.strictObject({scope:De,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),k0),savedGroups:ko,experiments:$.record($.uuid(),Fi)});var jo=Sn.extend({analyticsConfig:hu,remoteFeatures:ze.array(ze.string().min(1).max(255)).max(500)}),Au=jo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),zf=ze.strictObject({attributes:Pt,features:ze.array(ze.string().min(1).max(255)).max(500).optional(),customerId:ze.uuid().optional()}),j0=ze.strictObject({value:ve,source:ze.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ze.boolean(),off:ze.boolean(),ruleId:ze.string(),experimentResult:yu.optional()}),as=ze.strictObject({generation:Sn.shape.generation,evaluatedAt:Sn.shape.evaluatedAt,expiresAt:Sn.shape.expiresAt,features:ze.record(ze.string(),j0),merchandiseContext:ze.strictObject({merchandiseId:ze.uuid(),merchandise:Pt}).optional()}),$f=ze.strictObject({customerId:ze.uuid().optional(),events:ze.array(ze.strictObject({eventUuid:ze.uuid(),timestamp:ze.iso.datetime({offset:!0}),name:ze.string().min(1).max(255),merchandise:Cp.optional(),properties:ze.record(ze.string(),ve).default({}),deviceId:ze.string().min(1).max(255).optional(),sessionId:ze.string().min(1).max(255).optional()})).min(1).max(100)}),Gf=ze.strictObject({inserted:ze.number().int().nonnegative(),duplicates:ze.number().int().nonnegative(),rejected:ze.number().int().nonnegative(),skipped:ze.number().int().nonnegative(),analyticsConfig:hu});import{z}from"zod";import{z as T0}from"zod";var Kf=T0.enum(["funnel-run/1","funnel-process/1"]),Hf="funnel-process/1";function bu(e,t=[]){let n=[];Zt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(La(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function Qf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Qf(t)??[])}}function N0(e){let t=e.pages.map(i=>{let a=Qf(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(La({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Jf(e,t=[]){let n=mn.parse(structuredClone(N0(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=bu(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as ht}from"zod";var ss=ht.strictObject({schemaVersion:ht.literal(1),renderKey:ht.string().min(1).max(256),routeTemplate:ht.string().startsWith("/").max(2048),selectors:ht.array(ht.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ht.array(ht.number().int().min(0)).min(1),absent:ht.array(ht.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Zf=ht.strictObject({renderKey:ht.string().min(1).max(256),routeKey:ht.string().min(1).max(256),stateKey:ht.string().min(1).max(256),documentKey:ht.string().min(1).max(256),documentHash:ht.string().regex(/^[a-f0-9]{64}$/),compositionKey:ht.string().min(1).max(256),entryMode:ht.enum(["hard","soft"]),match:ht.strictObject({present:ht.array(ht.number().int().min(0)),absent:ht.array(ht.number().int().min(0))})});import{z as Hr}from"zod";var D0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],xu="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",F0=Hr.string().regex(new RegExp(`^${xu}/${xu}/${xu}/manifest\\.json$`)),Wf=Hr.strictObject({kind:Hr.literal("gcs-resumable"),url:Hr.url(),bucket:Hr.enum(D0),objectKey:F0,byteLength:Hr.number().int().positive(),expiresAt:Hr.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var bt=M.string().min(1).max(256),hn=M.string().regex(/^[a-f0-9]{64}$/),cs=M.strictObject({versionId:M.uuid(),manifestDigest:hn,sourceGraphDigest:hn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:hn,elementKey:bt.optional(),nodeId:bt.optional(),contentHash:hn.optional(),renderKey:bt.optional()}),Yf=M.strictObject({pageKey:bt,documentKey:bt,expectedDocumentHash:hn,renderKey:bt.optional(),nodeId:bt,elementKey:bt,expectedContentHash:hn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),Xf=M.strictObject({versionId:M.uuid(),manifestDigest:hn,sourceGraphDigest:hn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:hn,renderKey:bt.optional(),patches:M.array(Yf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),M0=/^[a-z][a-z0-9-]{0,39}$/,To=M.string().regex(M0),Iu=M.enum(["web","ios","android"]),XE=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:To,platform:Iu,label:M.string().trim().min(1).max(100),sha256:hn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:bt,changesetId:M.uuid().nullable(),expectedRevision:hn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(Yf).max(200)})]),vu=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:To,platform:Iu,label:M.string(),sha256:hn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),q0=M.strictObject({key:To,platform:Iu,currentId:M.uuid().nullable()}),eR=M.strictObject({rows:M.array(vu).max(100),nextCursor:M.uuid().nullable(),clients:M.array(q0).max(20)}),Su=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),tR=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Su,runtime:Su,previews:Su})}),nR=M.strictObject({version:vu,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),rR=M.strictObject({version:vu,upload:Wf.nullable()}),iR=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:bt,path:M.string(),documentKey:bt,documentHash:hn,initialStateKey:bt,initialRenderKey:bt})),renders:M.array(Zf)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),oR=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:bt,key:bt,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),aR=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Mi}from"zod";var eh=Mi.strictObject({id:Mi.uuid(),name:Mi.string().trim().min(1).max(80),client:To,source:cs,event:Mi.enum(["screen_enter","button_click"]),cooldownSeconds:Mi.number().int().min(0).max(2592e3),behavior:Mi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Je}from"zod";var wu=ve,U0=["parameters","answers","results","variables"];function Ou(e){return U0.some(t=>e===t||e.startsWith(t+"."))}function Pu(e){let t={};for(let[r,i]of Object.entries(za(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Ou(r))),variables:t}}import{z as xt}from"zod";var us=xt.discriminatedUnion("kind",[xt.object({kind:xt.literal("ledger"),cursor:Fa}).strict(),xt.object({kind:xt.literal("billing"),cursor:xt.uuid()}).strict()]),B0=xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),hr=xt.record(xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xt.union([xt.string().max(500),xt.boolean(),xt.array(xt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),V0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Cu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Cu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||V0.test(n)||Cu(r,t+1)))}var L0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,gr=xt.record(B0,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Cu(e)&&!L0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var th=xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ls=xt.array(xt.object({variable:th,componentId:th,required:xt.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),AR=xt.object({bindings:ls,answers:hr,values:xt.record(xt.string(),ve).optional()}).strict();import{z as z0}from"zod";var ds=z0.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var _u=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nh=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),rh=gr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Eu=Je.record(_u,Je.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),$0=Vn,ih=Je.strictObject({type:Je.literal("external_task"),endpointId:Je.uuid(),taskKey:_u,inputs:Je.record(_u,$0).refine(e=>Object.keys(e).length<=20),outputs:Eu}),oh=Je.strictObject({maxAttempts:Je.number().int().min(1).max(5),retryDelaySeconds:Je.number().int().min(1).max(30),backoff:Je.enum(["fixed","exponential"]),requestTimeoutSeconds:Je.number().int().min(1).max(10),timeoutSeconds:Je.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var _R=Je.strictObject({outcome:Je.enum(["success","failure"]),data:rh});var ER=Je.discriminatedUnion("operation",[Je.strictObject({operation:Je.literal("signal"),runId:Je.uuid(),nodeId:nh,eventName:ds,eventId:Je.uuid(),data:rh}),Je.strictObject({operation:Je.literal("read_results"),runId:Je.uuid()})]),RR=Je.strictObject({scope:De,runId:Je.uuid(),eventId:Je.uuid(),accepted:Je.boolean()}),G0=Je.record(nh,wu),kR=Je.strictObject({scope:De,runId:Je.uuid(),results:G0});var Dn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},ah="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as tt}from"zod";var MR=tt.enum(["local","remote"]),Ru=tt.strictObject({port:tt.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:tt.array(tt.strictObject({expected:uo.nullable(),next:uo})).max(100),exposures:tt.array(ve).max(100),features:tt.array(ve).max(100)}),sh=tt.strictObject({type:tt.literal("evaluate"),receiptId:tt.uuid(),environmentId:tt.uuid(),policyRevision:tt.number().int().nonnegative(),attributes:Pt,sticky:tt.record(tt.string(),uo)}),ch=sh.extend({runId:tt.uuid(),versionId:tt.uuid(),nodeId:tt.string().min(1).max(64),visit:tt.number().int().nonnegative(),revision:tt.number().int().nonnegative()}),ku=sh.omit({type:!0,receiptId:!0}).extend({type:tt.literal("evaluate_segment")}),uh=tt.strictObject({nodeId:tt.string().min(1).max(64),result:Ru}),lh=ku.extend({runId:tt.uuid(),versionId:tt.uuid(),nodeId:tt.string().min(1).max(64),visit:tt.number().int().nonnegative(),revision:tt.number().int().nonnegative(),parameters:gr,answers:hr,variables:tt.record(tt.string(),ve)});import{z as ue}from"zod";var ju=ue.array(ue.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),ps=ue.intersection(Pt,ue.looseObject({tags:ju.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ms=ue.string().trim().max(80),fs=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),hs=ue.union([ue.email().max(254),ue.literal("")]),gs=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dh=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),ph=ue.object({externalUserId:dh.optional(),name:ms.default(""),email:hs.default(""),phone:fs.optional(),attributes:ps.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Qr=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:dh})]),qi=ue.strictObject({name:ms.optional(),email:hs.optional(),phone:fs.optional(),attributes:ps.optional(),fingerprint:gs.optional()}),ys=e=>!e.customerData||e.customer?.type==="externalUserId",As="customerData requires an externalUserId customer",Ui=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:ms,email:hs,phone:fs.optional(),attributes:ps,createdAt:ue.iso.datetime()}).strict(),mh=ue.object({customer:Ui,changed:ue.boolean(),replayed:ue.boolean()}).strict(),K0=ue.discriminatedUnion("type",[ue.object({type:ue.literal("id"),value:ue.uuid()}).strict(),ue.object({type:ue.literal("externalUserId"),value:ue.string().trim().min(1).max(255)}).strict()]),H0=ue.object({name:ms.optional(),email:hs.optional(),phone:fs.optional(),attributes:ps.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.array(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.strictObject({add:ju,remove:ju}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Tu=ue.object({lookup:K0}).strict(),fh=Tu.extend({requestId:ue.uuid(),patch:H0}).strict(),hh=ue.object({search:ue.string().trim().max(200).default(""),tag:ue.string().trim().max(40).default(""),planId:ue.string().max(200).default(""),versionId:ue.string().max(200).default(""),holdingStatus:ue.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),createdUntil:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),offset:ue.coerce.number().int().min(0).max(1e5).default(0),limit:ue.coerce.number().int().min(1).max(100).default(50)}).strict(),gh=ue.object({customers:Ui.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var No=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:wt,path:Nn.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),Q0=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),J0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:Qr,customerData:qi.optional(),attributes:Pt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},JR=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...J0}).refine(ys,As),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:Ru}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(uh).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),ZR=Z.strictObject({scope:De,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:Q0.nullable(),evaluation:Z.discriminatedUnion("type",[ch,lh]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),WR=Z.strictObject({scope:De,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Lt}from"zod";var yh=Lt.strictObject({type:Lt.literal("bundle"),paywall:Vn.optional(),offering:Vn.optional(),coupons:Vn,data:Vn}),Z0=e=>Lt.strictObject({type:Lt.literal(e),id:Lt.uuid()}),rk=Lt.strictObject({type:Lt.literal("bundle"),paywallVersionId:Lt.uuid().optional(),offeringVersionId:Lt.uuid().optional(),couponIds:Lt.array(Lt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var ik=Lt.strictObject({type:Lt.literal("bundle"),offering:Z0("offering_version").nullable(),paywall:Lt.strictObject({versionId:Lt.uuid(),paywallId:Lt.uuid(),offeringVersionId:Lt.uuid()}).nullable(),coupons:Lt.array(lo).max(20),data:ve});import{z as Fn}from"zod";import{z as In}from"zod";var Ah=In.union([In.string(),In.number().finite(),In.boolean(),In.null()]),W0=In.union([Ah,In.array(Ah).min(1).max(20)]),Y0=In.record(Nn,W0).refine(e=>Object.keys(e).length<=10),bh=In.strictObject({path:Nn,type:In.enum(["string","number","boolean","strings"]),nullable:In.boolean().optional(),aggregation:In.enum(["count","exists"]).optional(),where:Y0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var X0=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],xh=Fn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),eI=Vn,Sh=Fn.discriminatedUnion("type",[ih,Fn.strictObject({type:Fn.literal("claim_offer"),coupon:Vn}),Fn.strictObject({type:Fn.literal("event"),event:xh}),Fn.strictObject({type:Fn.literal("api"),operation:Fn.enum(X0),inputs:Fn.record(Nn,eI).refine(e=>Object.keys(e).length<=40),outputs:Fn.record(xh,bh).refine(e=>Object.keys(e).length<=20)})]);var dt=ds,tI=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),gn={id:dt,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},nI={success:dt,cancel:dt,unavailable:dt,failure:dt},Nu=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Du=Q.enum(["same_window","new_window"]),rI=Q.discriminatedUnion("type",[Q.strictObject({...gn,type:Q.literal("entry"),next:dt,triggers:Q.array(eh).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...gn,type:Q.literal("screen"),screenId:dt,presentation:kn,outputs:Q.record(dt,dt),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:wt}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...gn,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...No.options,yh,Q.strictObject({type:Q.literal("selection"),screenId:dt,offeringKey:wt})])}),Q.strictObject({...gn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:nn,target:dt})).min(1).max(50),default:dt}),Q.strictObject({...gn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(tI,dt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:dt}),Q.strictObject({...gn,type:Q.literal("action"),...nI,execution:oh,action:Sh,writes:Zc.optional()}),Q.strictObject({...gn,type:Q.literal("external_page"),appManifest:cs.optional(),url:Nu,openIn:Du,opened:dt,failed:dt}),Q.strictObject({...gn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:No.optional()}),Q.strictObject({...gn,type:Q.literal("wait"),writes:Zc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:dt}),Q.strictObject({type:Q.literal("event"),eventName:dt,outputs:Eu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:dt,timeout:dt})])})]),Fu=Q.strictObject({version:Q.literal(5),entry:dt,nodes:Q.array(rI).min(1).max(Dn.flowNodes)}),Mu=Fu.superRefine((e,t)=>{iI(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function bs(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function iI(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,p,m)=>{n.push(l),t?.({message:l,reason:p,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>Dn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Dn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let p of bs(l))p===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(p)||i(`Missing target ${p}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let p of bs(r.get(l)))u(p);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var qu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Ih(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of lr(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as q}from"zod";var Bi=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),xs=e=>q.record(q.string(),ve).refine(t=>fn(t)<=e,"Funnel evidence exceeds its byte budget"),Dk=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Bu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Vu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),Do=q.strictObject({schemaVersion:q.literal(1),kind:Bu,selector:Vu.nullable(),context:xs(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>fn(e)<=131072,"Node input exceeds its byte budget"),vh=q.strictObject({schemaVersion:q.literal(1),kind:Bu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:xs(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:xs(131072)}).refine(e=>fn(e)<=131072,"Node result exceeds its byte budget"),Fk=q.strictObject({schemaVersion:q.literal(1),operations:q.record(Bi,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:Bi,id:q.uuid()}).nullable()}))}).refine(e=>fn(e)<=65536,"Execution state exceeds its byte budget"),Jr={receiptId:q.uuid()},Uu=q.iso.datetime({offset:!0}),Mk=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:Bu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Jr,source:q.literal("client"),occurredAt:Uu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:Bi,eventName:Bi,data:xs(8192),source:q.literal("server"),occurredAt:Uu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Jr,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Jr,operation:Bi,reference:q.strictObject({type:Bi,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Jr,source:q.enum(["client","server"]),occurredAt:Uu,reference:q.string().min(1).max(128).optional()})})]);var vn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oI=z.discriminatedUnion("type",[z.strictObject({id:vn,type:z.literal("owned"),publicData:Bf.optional(),document:mn.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),z.strictObject({id:vn,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),Lu={executionContract:Kf.optional(),kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(oI).max(Dn.pages),references:z.record(vn,Vu).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:vn,screenId:vn,componentId:vn,required:z.boolean()})).max(Dn.questions),variables:z.record(wt,Oi).refine(e=>Object.keys(e).length<=Dn.logicNodes),outputSchema:wi,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(qu.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(qu.maxTransitions)})},rj=z.strictObject({...Lu,graph:Fu});function aI(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function Is(e){return Array.isArray(e)?e.some(Is):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===ah:Is(n))}function sI(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=Jf(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!_o(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),aI(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&Is(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Is(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function wh(e,t){for(let{message:n,reason:r,path:i}of sI(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Oh(e,t){let n=(h,d,g=[])=>t.addIssue({code:"custom",message:h,path:g,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(h=>[h.id,h])),a=(h,d)=>r.some(g=>g.type===h&&("id"in g?g.id:g.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(h=>h.type==="screen");(o.length!==i.size||o.some(h=>!i.has(h.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(h=>c.some(d=>h!==d&&d.startsWith(h+".")))&&n("Variable paths must not overlap","variable");function u(h,d){Object.hasOwn(e.variables,h)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let g=s.get(h)??new Set;g.add(d.id),s.set(h,g)}for(let[h,d]of e.graph.nodes.entries()){let g=["graph","nodes",h],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",g);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,C]of Object.entries(A)){u(C,d);let j=e.variables[C],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",g)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let C of d.couponIds)a("reward",C)||n("Coupons require Reward references","coupon",g)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let C=v.document.pages[0];if(!C){n("Owned screen requires a page","screen",g);continue}mr(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",g);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),tr(C.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",g),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",g),d.type==="end"&&d.output?.type==="literal"&&!xn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",g),d.type==="output"&&d.value.type==="literal"&&!xn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",g);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!Wc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let C of eu(v.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!Xc(C.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(d.type==="condition")for(let v of d.cases){for(let C of Yn(v.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let C of lr(v.condition))C.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,C]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!xn({type:C,nullable:!1},X)||!a(C,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==C))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[h,d]of e.graph.nodes.entries()){let g=d.type==="screen"?i.get(d.screenId):void 0,R=[...Ih(d,c),...g?.type==="owned"?$a(g.document).map(y=>Xc(y,c)?.key??y):[]];for(let y of new Set(R)){let C=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:bs(_)).some(C):!1};var m=C;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",h]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||C(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",h])}}(new Set(e.inputs.map(h=>h.variable)).size!==e.inputs.length||new Set(e.inputs.map(h=>`${h.screenId}:${h.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[h,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",h]);let g=i.get(d.screenId),R=g?.type==="owned"?_o(g.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",h]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",h]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",h])}}for(let[h,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",h]),d.source.type==="input"&&!e.inputs.some(g=>g.variable===h)&&n("Input variable requires a component binding","inputBinding",["variables",h]);let l=0,p=0;for(let h of e.screens)if(h.type==="owned"){for(let d of h.document.pages)tr(d.root,()=>{l++});p+=h.document.actions.length}(l>Dn.components||p>Dn.actions||fn(e)>Dn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var cI=z.strictObject({...Lu,graph:Mu}).superRefine(Oh),Vi=z.strictObject({...Lu,graph:Mu,displayName:z.string().trim().min(1).max(80)}).superRefine(Oh),ij=Vi.superRefine(wh),oj=cI.superRefine(wh),Ss=z.string().regex(Ft),Fo={requestId:z.uuid(),nodeId:vn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ss.optional()},uI=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:vn,answers:hr,selection:z.record(vn,z.union([z.string().max(200),z.boolean(),z.number().int().min(0).max(1e4)])).optional()}),z.strictObject({type:z.literal("paywall_quote"),featureQuantities:z.record(z.uuid(),z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:vn,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:_i.optional(),predecessor:z.strictObject({operationId:z.uuid().nullable(),generation:z.number().int().positive()}).optional()}),z.strictObject({type:z.literal("paywall_confirm"),operationId:z.uuid()}),z.strictObject({type:z.literal("paywall_cancel"),operationId:z.uuid()}),z.strictObject({type:z.literal("client_action"),receiptId:z.uuid(),outcome:z.enum(["success","cancel","failure","opened","failed"])})]),lI=z.object({nodeId:vn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(vn,z.object({resourceKey:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.number().int().min(1).max(1e5),after:us.nullable(),filter:z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ct=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:Qr.optional(),customerData:qi.optional(),locale:z.string().min(1).max(35),parameters:gr}).refine(ys,As),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:lI.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Ss.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Ss.optional()}),z.strictObject({operation:z.literal("submit"),...Fo,input:uI}),z.strictObject({operation:z.literal("back"),...Fo}),z.strictObject({operation:z.literal("shown"),...Fo}),z.strictObject({operation:z.literal("close"),...Fo}),z.strictObject({operation:z.literal("commit_segment"),...Fo,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Ss.optional()})]);function vs(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let g of Yn(d))l(g)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let g=t.savedGroups[d];g&&(i.add(d),c.set(d,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function p(d){for(let g of["hashAttribute","fallbackAttribute"])if(d[g]!==void 0&&Ou(d[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(d.condition);for(let g of d.parentConditions??[])m(g.id),u(g.condition)}function m(d,g=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){p(y);for(let A of y.tracks??[])p(A.experiment)}}))}function h(d){let g=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,g),a.push(()=>p(g)))}for(let d of e.graph.nodes){d.type==="feature"&&m(d.featureKey,!0),d.type==="split"&&h(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&m(d.configuration.featureKey,!0);let g=d.type==="output"?d.value:d.type==="end"?d.output:null;g?.type==="feature"&&m(g.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Ph(e,t){let n=[],r={};Zt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Zt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Ch(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Zt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as Mo}from"zod";var _h=Mo.object({defaultLocale:Cn,locales:Mo.record(Cn,Mo.object({name:Mo.string().max(80),description:Mo.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var dI=["customer_data","coupon_code"],Eh=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),pI=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ws=(e,t)=>new Set(e.map(t)).size===e.length,mI=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),fI=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),hI=ae.strictObject({stripe:ae.strictObject({prices:ae.array(mI).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Eh).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Eh,basePlanId:pI.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ws(e.stripe.prices,n=>n.currency)||e.apple&&!ws(e.apple.productIds,n=>n)||e.google&&!ws(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),gI=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(fI).max(50).refine(e=>ws(e,t=>t.featureId),"Duplicate benefit"),channels:hI,prepaid:ae.array(wo).max(100).optional()}),yI=ae.strictObject({digest:Di,content:ae.strictObject({discount:dr,duration:dn,appliesTo:Nc,displayCopy:_h.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),AI=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:Va}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:fu})]),Os=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:kn,screen:mn,products:is,catalog:ae.record(ae.uuid(),gI),buttons:ae.record(Ve,AI),coupons:ae.record(ae.uuid(),yI)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Ph(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),bu(r,dI).forEach(n),mr(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Zt(r,g=>{let R="bind"in g?g.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(y=>i.add(y)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(R=>R.featureId)));for(let g of o)l.has(g)||n("Feature text must read a displayed benefit");let p=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==p.length||p.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let h=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;h=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}h||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Rh=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var sn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},zu=Re.string().regex(/^[a-f0-9]{64}$/),$u=Re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Ku=De.extend({environmentId:Re.uuid()}),kh=Re.strictObject({features:Re.array(Re.string()).max(500),experiments:Re.record(Re.uuid(),Re.array(Re.string()).max(20)),savedGroups:Re.array(Re.string()).max(1e3)}),Hu=Re.strictObject({kind:Re.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.number().int().positive(),url:Re.string().min(1).max(2048),sha256:zu,byteLength:Re.number().int().positive().max(sn.maxArtifactBytes),generation:zu.optional()}),bI=Re.strictObject({state:Re.enum(["active","paused","archived"]),controlRevision:$u,evaluationMode:Re.enum(["local","remote"]),evaluationRevision:$u,currentVersionId:Re.uuid(),versions:Re.record(Re.uuid(),Re.strictObject({artifact:Re.string(),dependencies:kh,definitionDigest:Di.optional(),couponDigests:Re.record(Re.uuid(),Di).optional()}))}),Qu=Re.strictObject({kind:Re.literal("sdk_configuration"),schemaVersion:Re.literal(1),scope:Ku,revision:$u,generation:zu,policy:Re.strictObject({refreshIntervalSeconds:Re.number().positive().max(15),maxControlAgeSeconds:Re.number().positive().max(60)}),gb:Re.strictObject({features:Re.string().nullable(),pageExperiments:Re.string().nullable()}),artifacts:Re.record(Re.string(),Hu),funnels:Re.record(Re.uuid(),bI),paywalls:Re.record(Re.uuid(),Rh).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function _t(e){if(Array.isArray(e))return`[${e.map(_t).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${_t(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Ju(e){return rr(or(typeof e=="string"?new TextEncoder().encode(e):e))}function jh(e){return Ju(_t(e))}var Gu=class extends Error{constructor(n,r){super(n);Be(this,"dependency",r)}};function Th(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,p)=>e.graph.nodes.find(m=>l==="experiment"?m.type==="split"&&m.experimentId===p:l==="feature"&&n(m)===p)?.name,i=(l,p,m=r(p.type,p.resource))=>new Gu(l,{...p,...m?{step:m}:{}});for(let l of Object.values(e.references)){let p=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(p)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...p})}let a=vs(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let p=n(l);if(!p)continue;let m=a.features[p],h=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:p};if(!m||!h)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([m.defaultValue,...(m.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!xn(h,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,p)=>{for(let m of Yn(l)){if(s.has(m))continue;let h=t.savedGroups[m];if(!h)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:m},p);s.add(m),!Array.isArray(h)&&h.type==="condition"&&c(h.condition,p)}},u=(l,p)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},p)};for(let l of e.graph.nodes)if(l.type==="condition")for(let p of l.cases)c(p.condition,l.name);for(let[l,p]of Object.entries(a.features)){let m=r("feature",l);for(let h of p.rules??[]){c(h.condition,m);for(let d of[...h.parentConditions??[],...(h.tracks??[]).flatMap(g=>g.experiment.parentConditions??[])])u(d.id,m),c(d.condition,m);for(let d of h.tracks??[])c(d.experiment.condition,m)}}for(let[l,p]of Object.entries(a.experiments)){let m=r("experiment",l);c(p.condition,m);for(let h of p.parentConditions??[])u(h.id,m),c(h.condition,m)}for(let l of e.graph.nodes)if(l.type==="split"){let p=a.experiments[l.experimentId],m={type:"experiment",resource:l.experimentId};if(!p)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...m},l.name);for(let h of p.variations)if(typeof h!="string"||!Object.hasOwn(l.routes,h))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...m},l.name)}return kh.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,p])=>[l,p.variations.map(String)])),savedGroups:[...s].sort()})}function Nh(e){return Vi.parse(e)}var Dh=Et.strictObject({processContext:Ha.optional(),...Ci,selector:Et.discriminatedUnion("type",[Et.strictObject({type:Et.literal("paywall"),paywallId:Et.uuid()}),Et.strictObject({type:Et.literal("version"),versionId:Et.uuid()})]),customerId:Et.uuid().optional(),commerce:fi,locale:Et.string().min(1).max(35),requirement:Pn.optional()}),qo=Et.strictObject({id:Et.uuid(),paywallId:Et.uuid(),version:Et.number().int().positive(),document:Ni.omit({requirement:!0,offeringId:!0}),offering:Et.strictObject({id:Et.uuid()}),content:Et.strictObject({environmentId:Et.uuid(),offeringVersionId:Et.uuid(),artifact:Hu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Ii,check:sr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Zr=Et.strictObject(qo.shape).omit({document:!0,offering:!0}).extend({content:qo.shape.content.unwrap()});function Fh(e,t){let n=Os.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return qo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Yt}from"zod";var Mh={requestId:Yt.uuid(),sourceId:Yt.uuid(),expectedAvailable:Jt},qh=Yt.discriminatedUnion("action",[Yt.strictObject({...Mh,action:Yt.enum(["add","subtract","set_remaining"]),amount:de}),Yt.strictObject({...Mh,action:Yt.literal("edit"),granted:de,expiresAt:Yt.iso.datetime({offset:!0}).nullable(),nextResetAt:Yt.iso.datetime({offset:!0}).nullable(),expectedRevision:Yt.number().int().nonnegative()})]),Zu=Yt.strictObject({sourceId:Yt.uuid(),available:Jt,held:Jt,spent:Jt,adjustmentGrantId:Yt.uuid().nullable()}),Uh=Zu.extend({granted:Jt,expiresAt:Yt.iso.datetime({offset:!0}).nullable(),nextResetAt:Yt.iso.datetime({offset:!0}).nullable(),revision:Yt.number().int().nonnegative()});import{z as yn}from"zod";var Bh=yn.discriminatedUnion("action",[yn.object({action:yn.literal("upsert"),externalId:yn.string().min(1).max(128),name:yn.string().trim().min(1).max(80)}).strict(),yn.object({action:yn.literal("archive"),entityId:yn.uuid()}).strict()]),Vh=yn.object({id:yn.uuid(),externalId:yn.string().min(1).max(128),name:yn.string().min(1).max(80),archived:yn.boolean()}).strict();import{z as Gt}from"zod";import{z as Yr}from"zod";var zh=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Lh=Yr.string().regex(/.+\/.+/),Wu=Yr.number().min(-100),Wr=Yr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),xI=Yr.strictObject({input:Wr,output:Wr,cache_read:Wr.optional(),cache_write:Wr.optional(),reasoning:Wr.optional(),input_audio:Wr.optional(),output_audio:Wr.optional()}),Yu=(e,t)=>Yr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),iT=Yr.strictObject({defaultMarkup:Wu,providerMarkups:Yu(Yr.string().min(1),Wu),modelMarkups:Yu(Lh,Wu),customModels:Yu(Lh,xI.partial())});import{z as xe}from"zod";var Xr=xe.iso.datetime({offset:!0}),yr=xe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),SI=xe.discriminatedUnion("kind",[xe.object({kind:xe.literal("absolute"),from:Xr,to:Xr}).strict(),xe.object({kind:xe.literal("last_days"),days:xe.union([xe.literal(1),xe.literal(7),xe.literal(30),xe.literal(90)])}).strict(),xe.object({kind:xe.literal("billing_cycles"),membershipId:xe.uuid(),count:xe.number().int().min(1).max(12),includeCurrent:xe.boolean()}).strict()]),$h=xe.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),II=xe.object({key:xe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:xe.array(xe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ei=xe.object({range:SI,timezone:$h,filterBy:xe.array(II).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:xe.enum(["hour","day","week","month"]),internal_feature_id:xe.uuid().nullable(),entityId:xe.uuid().nullable(),topN:xe.number().int().min(1).max(50).nullable(),groupBy:xe.union([xe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),xe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid()}).strict().nullable(),limit:xe.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Gh=xe.object({from:Xr,to:Xr,interval:xe.enum(["hour","day","week","month"]),timezone:$h,rows:xe.array(xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid(),consumedUnits:yr,refundedUnits:yr,reservedUnits:yr,charged:yr,refunded:yr,reserved:yr,netUnits:yr,netCharged:yr}).strict()).max(100),nextCursor:xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid()}).strict().nullable()}).strict();var Li=Gt.string().regex(/^(0|[1-9]\d{0,29})$/),Kh=Gt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Xu=Gt.strictObject({bucket:Gt.iso.datetime({offset:!0}),group:Gt.string().max(240),isOther:Gt.boolean(),internal_feature_id:Gt.uuid()}),Hh=Gt.strictObject({...ei.shape,groupBy:Gt.union([Gt.enum(["customer","entity","entitlement"]),Gt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Xu.nullable()}).superRefine((e,t)=>{let n=ei.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Qh=Gt.strictObject({from:Gt.iso.datetime({offset:!0}),to:Gt.iso.datetime({offset:!0}),interval:ei.shape.interval,timezone:ei.shape.timezone,rows:Gt.array(Gt.strictObject({...Xu.shape,eventCount:Li,units:Kh,tokenEventCount:Li,tokens:Gt.strictObject(Object.fromEntries(zh.map(e=>[e,Li]))),totalTokens:Li,providerCostEventCount:Li,providerCostUsd:Kh,invalidTelemetryEventCount:Li})).max(100),nextCursor:Xu.nullable()});import{z as St}from"zod";var Jh=St.object({requestId:St.uuid(),items:St.array(St.object({customerId:St.uuid(),command:Ao.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),Zh=St.object({batchId:St.uuid(),after:St.number().int().min(-1).max(999),limit:St.number().int().min(1).max(100)}).strict(),Wh=St.object({batchId:St.uuid(),status:St.enum(["queued","complete"]),total:St.number().int().min(1).max(1e3),processed:St.number().int().min(0).max(1e3),items:St.array(St.object({position:St.number().int().min(0).max(999),customerId:St.uuid(),idempotencyKey:St.string().min(1).max(120),status:St.enum(["queued","accepted","rejected","failed"]),receipt:bo.nullable(),errorCode:St.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:St.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var vI=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Yh=k.enum(["draft","active","paused","archived"]),Xh=k.string().min(1).max(256),eg=k.array(Xh).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),wI=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),OI=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:wI.nullable()}),PI=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(OI).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:Xh,duration:dn}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:dn,rollover:k.boolean(),productIds:eg})]),CI=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),tg=k.object({key:CI,name:k.string().trim().min(1).max(80),configuration:PI}).strict(),ng=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),el=k.object({code:ng,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),rg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:eg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),ig={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:Yh,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},_I=tg.extend(ig).strict(),EI=rg.safeExtend(ig).strict(),AT=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:vI,status:Yh}),bT=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:tg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),xT=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:rg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),og=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),ag=k.object({code:ng,requestId:k.uuid()}).strict(),sg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),RI=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:dn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),cg=k.discriminatedUnion("type",[RI,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:dn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),ug=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),lg=k.object({id:k.uuid(),programId:k.uuid(),code:el.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),ST=k.object({rows:k.array(_I).max(100),nextCursor:k.uuid().nullable()}).strict(),IT=k.object({rows:k.array(EI).max(100),nextCursor:k.uuid().nullable()}).strict(),kI=el.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),jI=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),vT=k.object({codes:k.array(kI).max(100),redemptions:k.array(jI).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),wT=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:el}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Ln={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Uo=e=>new Set(e).size===e.length,tl=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),TI=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Bo=W.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),NI=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),dg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var pg=W.strictObject({id:W.uuid(),repo:TI,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Bo).min(1).max(4).refine(Uo),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(Uo),include:W.array(dg).min(1).max(16),exclude:W.array(dg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Uo),maxAgeHours:W.number().int().min(1).max(720)}),mg=pg.extend({revision:W.number().int().positive()}),CT=W.strictObject({repository:pg,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),fg=W.strictObject({repositoryId:W.uuid(),branch:Bo}),DI=W.array(tl).max(Ln.keys).refine(Uo),hg=W.strictObject({repository:mg.omit({keyIds:!0}),branch:Bo,keys:DI,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),FI=W.strictObject({filePath:NI,startingLineNumber:W.number().int().min(1).max(1e7)}),nl=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Bo,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Ln.files),sourceBytes:W.number().int().min(0).max(Ln.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Ln.files)}),features:W.array(W.strictObject({key:tl,refs:W.array(FI).max(Ln.referencesPerKey)})).max(Ln.keys)}).superRefine((e,t)=>{Uo(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>Ln.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),rl=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),MI=rl.extend({repositoryId:W.uuid(),branch:Bo,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:nl.shape.coverage}),qI=W.strictObject({repositories:W.array(mg).max(Ln.repositories),scans:W.array(MI).max(Ln.repositories*Ln.branches)}),UI=W.strictObject({key:tl,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),_T=W.strictObject({available:W.boolean().default(!0),settings:qI,expectedTargets:W.number().int().min(0).max(80),features:W.array(UI).max(2001),truncated:W.boolean()});import{z as Ee}from"zod";var cn=Ee.string().min(1).max(200),Ps=Ee.iso.datetime({offset:!0}),Vo=Ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),il=Ee.number().int().min(0).max(1e12),Ag=Ee.number().int().min(1).max(1e12),gg={...Ht,type:Ee.literal("coupon.redeemed"),grantId:Ee.uuid()},yg={...Ht,type:Ee.literal("usage.observed"),merchantTransactionId:cn,resource:cn,unit:cn,quantity:Ag},BI=Ee.strictObject({...Ht,type:Ee.literal("fulfillment.updated"),operationId:Ee.uuid(),merchantFulfillmentId:cn,status:Ee.enum(["pending","applied","failed"])}),VI=Ee.strictObject({...Ht,type:Ee.literal("benefit.claimed"),merchantBenefitId:cn,resource:cn,unit:cn,quantity:Ag,expiresAt:Ps.nullable(),revision:Vo}),LI=Ee.strictObject({...Ht,type:Ee.literal("benefit.closed"),merchantBenefitId:cn,status:Ee.enum(["failed","expired","canceled"]),revision:Vo}),zI=Ee.strictObject({...Ht,type:Ee.literal("benefit.updated"),merchantBenefitId:cn,status:Ee.enum(["active","expired","revoked"]),remainingQuantity:il.nullable(),expiresAt:Ps.nullable(),revision:Vo}),$I=Ee.strictObject({...Ht,type:Ee.literal("authorization.updated"),merchantAuthorizationId:cn,kind:Ee.literal("auto_topup"),status:Ee.enum(["pending","effective","revoked","failed"]),termsReference:cn.nullable(),revision:Vo}),GI=Ee.strictObject({...Ht,type:Ee.literal("balance.observed"),resource:cn,unit:cn,availableQuantity:il,reservedQuantity:il,periodStartsAt:Ps.nullable(),periodEndsAt:Ps.nullable(),revision:Vo}),bg=Ee.union([Ee.discriminatedUnion("type",[...ld,BI,VI,LI,zI,$I,GI]),Ee.strictObject({...gg,productVersionId:Ee.uuid(),subscriptionId:Ee.string().trim().min(1).max(255)}),Ee.strictObject({...gg,merchandiseId:Ee.uuid()}),Ee.strictObject({...yg,operation:Ee.literal("consume")}),Ee.strictObject({...yg,operation:Ee.literal("reverse"),reversalOf:cn})]),xg=Ee.strictObject({id:Ee.uuid(),eventId:Ee.string().min(1).max(200),source:Ee.literal("merchant"),providerVerified:Ee.literal(!1),outcome:Ee.string().min(1).max(100)});import{z as oe}from"zod";var Sg=Wm,KI=Sg.extend({invoice_id:Sg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ol=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),HI=ol.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),Ig=oe.strictObject({items:oe.array(HI).max(50),nextCursor:oe.uuid().nullable()}),DT=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:ol}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:ol}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),vg=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:Ei}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:KI})]),al=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),wg=al.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),zi=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:al.nullable(),errorCode:oe.string().nullable()}),Og=oe.strictObject({items:oe.array(al).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(zi).max(50),operationsLimited:oe.boolean()});var QI=w.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Pg={scope:De,permissions:w.array(QI),expiresAt:w.iso.datetime().nullable()},_N=w.discriminatedUnion("kind",[w.object({...Pg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Pg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),V=w.object({requestId:w.uuid(),scope:De}).strict(),JI=ph.safeExtend({fingerprint:gs.optional()}).strict(),ZI=V.extend({customer:Ui,created:w.boolean()});function Cg(){return V.extend({offer:lo.nullable(),reason:Ep.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:bm,response:V.extend({message:w.object({messageId:w.uuid(),channel:vo,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:V.extend({message:w.object({id:w.uuid(),channel:vo,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:Sm,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:Im,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Jl,response:V.extend({installation:kr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Zl,response:V.extend({installation:kr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:na,response:V.extend({installation:kr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:vo}),response:V.extend({preference:Js})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:xm,response:V.extend({preference:Js})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:V.extend({templates:Ig})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:Ei}),response:V.extend({preview:ru})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:Ei}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:zi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:vg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:zi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:V.extend({operation:zi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:V.extend({invoices:Og})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:V.extend({invoice:wg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:fg,response:V.extend({config:hg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:nl,response:V.extend({receipt:rl})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:V.extend({payload:jo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:zf,response:V.merge(as)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:$f,response:V.merge(Gf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:V.extend({balance:Uh})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:qh}),response:V.extend({balance:Zu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.uuid(),config:Sc,model_markups:xa})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:Da}),response:V.extend({usage:xo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:lm}),response:V.extend({usage:xo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:im}),response:V.extend({grant:qc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:om,response:V.extend({grants:am})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(kf.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(Ft).optional()}))),response:V.extend({operation:jf})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:xf.extend({customerId:w.uuid().optional()}),response:V.extend({setup:uu})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Sf.extend({customerId:w.uuid().optional()}),response:V.extend({setup:uu})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:yf.safeExtend({customerId:w.uuid()}),response:V.extend({batch:Eo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[Xa.options[0].extend({customerId:w.uuid()}),Xa.options[1].extend({customerId:w.uuid()}),Xa.options[2].extend({customerId:w.uuid()})]),response:V.extend({trial:cu})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Af.extend({customerId:w.uuid()}),response:V.extend({trial:cu})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ns,response:V.extend({subscriptions:_f})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ns,response:V.extend({purchases:Ef})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Of,response:V.extend({conflicts:Rf})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Pf,response:V.extend({resolution:Cf})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:vf,response:V.extend({verification:wf})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:uf.safeExtend({...Ci,customerId:w.uuid().optional()}),response:V.extend({quote:Ri})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:bg,response:V.extend({record:xg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional(),merchantConfirmation:io.optional()}),response:V.extend({operation:ki})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:ki})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:pf.safeExtend({customerId:w.uuid().optional()}),response:V.extend({quote:ff})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional(),merchantConfirmation:io.optional()}),response:V.extend({operation:iu})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:iu})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:hf.safeExtend({customerId:w.uuid()}),response:V.extend({quote:au})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Kr.extend({customerId:w.uuid(),merchantConfirmation:io.optional()}),response:V.extend({operation:Wa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Kr.extend({customerId:w.uuid()}),response:V.extend({operation:Wa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:zp,response:V.extend({controls:Fc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Fp,response:V.extend({prepared:qp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Up,response:V.extend({authorization:ka})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Qp,response:V.extend({coupons:Jp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Bp,response:V.extend({authorization:ka})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Kp,response:V.extend({invoices:Hp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Gp.extend({customerId:w.uuid()}),response:V.extend({operation:zi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:$p,response:V.extend({invoice:fo})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:Lp}).strict(),response:V.extend({controls:Fc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:Bh}).strict(),response:V.extend({entity:Vh})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:Hh}),response:V.extend({analytics:Qh})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:ei}).strict(),response:V.extend({analytics:Gh})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jh,response:V.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Zh,response:V.extend({batch:Wh})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Bd.extend({customerId:w.string().min(1).optional()}),response:V.extend({check:sr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:fr,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:V.extend({content:tu})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Dh,response:V.extend({paywall:Zr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Ha.optional(),...Ci,selector:Ff,customerId:w.string().min(1).optional(),commerce:fi,requirement:Pn.optional()}),response:V.extend({offering:Mf,candidates:w.array(Ac).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:sr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:V.extend({holdings:dm})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:mm}).strict(),response:V.extend({ledger:fm})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:sm.extend({customerId:w.uuid().optional()}),response:V.extend({detail:cm})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Uc.safeExtend({customerId:w.uuid().optional()}),response:V.extend({statement:um})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Ao.options[0]}).strict(),response:V.extend({quote:tm})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:de.optional(),properties:Ot.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:de.optional(),properties:Ot.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:V.extend({receipts:w.array(bo).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Ao.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:bo})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:ag,response:V.extend({redemption:og})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:ug,response:V.extend({referralCode:lg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:sg,response:V.extend({checkout:cg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:gm,response:V.extend({seats:Lc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:ym,response:V.extend({seats:Lc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:JI,response:ZI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Tu,response:V.extend({customer:Ui})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:hh,response:V.extend(gh.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fh,response:V.extend(mh.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:V.extend(ar.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:V.extend(ar.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:V.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:gs.optional()}),response:V.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(ar.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:V.extend({customer:Ui,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:Cg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:V.extend({offers:w.array(lo)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:kd,response:V.extend({operation:fc})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:jd,response:V.extend({operation:fc})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...Ci,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Cg()}},EN={recordMerchantEvent:O.recordMerchantEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,grantModelBenefit:O.grantModelBenefit,readModelBenefit:O.readModelBenefit,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as sl}from"zod";var Lo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function cl(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>on(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new Lo("Required GB Feature is unavailable");i=Wn(e.featureKey,t),o=i.value,Object.assign(r,Pi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Lo("Required GB Experiment is unavailable");if(a=Ea(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new Lo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Wn(e.configuration.featureKey,t).value;o={type:"offering_version",id:sl.uuid().parse(u)},Object.assign(r,Pi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,Pi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function _g(e,t,n){sl.uuid().parse(e),sl.number().int().nonnegative().parse(t);let r=rr(or(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as H}from"zod";var Ar=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),WI=H.enum(["running","waiting","completed","closed","ineligible","failed"]),ul=H.discriminatedUnion("type",[ku,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:Ar.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:Nu,openIn:Du}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:Ar})]),Cs=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),YI={id:Ar,presentation:kn,outputs:H.array(Ar).max(250),inputs:ls,values:H.record(H.string(),ve).optional(),offeringKey:wt.optional(),capabilities:Ii,customerData:Em,dataCursors:H.record(Ar,us.nullable())},XI=H.strictObject({...YI,content:H.strictObject({type:H.literal("document"),document:mn})}),zo=H.strictObject({id:H.uuid(),source:Cs,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:Ar,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:WI,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:hr,parameters:gr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:XI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([qo,Zr]),quote:Ri.nullable(),operation:ki.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:ul.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),_s=H.strictObject({scope:De,run:zo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ri.nullable(),operation:ki.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:Ar,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:Ar,visit:H.number().int().nonnegative(),document:mn,answers:hr,inputs:ls,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Eg=_s.extend({run:zo.extend({paywall:zo.shape.paywall.unwrap().extend({resolution:Zr}).nullable()})});var Rg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as be}from"zod";import{z as Rt}from"zod";var ev=Rt.strictObject({selector:Rt.string().min(1).max(2048),action:Rt.enum(["set","append","remove"]),attribute:Rt.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:Rt.string().max(5e4).optional(),parentSelector:Rt.string().max(2048).optional(),insertBeforeSelector:Rt.string().max(2048).optional()}),tv=Rt.strictObject({variation:Rt.string().min(1).max(128),description:Rt.string().max(2e3).default(""),css:Rt.string().max(1e5).default(""),js:Rt.string().max(1e5).default(""),domMutations:Rt.array(ev).max(200).default([]),iam:Xf.optional(),renderGuard:ss.optional()}),ll=tv.omit({variation:!0,description:!0,iam:!0}),nv=Fi.omit({variations:!0,active:!0}).extend({changeId:Rt.string().regex(/^[a-f0-9]{64}$/),variations:Rt.tuple([ll,ll]).rest(ll).refine(e=>e.length<=20)}),kg=Rt.strictObject({trackExposures:Rt.boolean(),environmentId:Rt.uuid(),generation:Rt.string().regex(/^[a-f0-9]{64}$/),experiments:Rt.array(nv).max(100),savedGroups:ko});var $o=be.string().regex(/^[a-f0-9]{64}$/),uD=be.strictObject({iam:$o,executionContracts:be.union([be.tuple([be.literal("funnel-run/1")]),be.tuple([be.literal("funnel-process/1")])]).default(["funnel-run/1"])}),rv=be.strictObject({release:$o,render:ss,button:be.strictObject({selector:be.string().min(1).max(512),elementKey:be.string().min(1).max(256),tag:be.enum(["button","a","input"])}).nullable()}),lD=be.strictObject({scope:De.extend({environmentId:be.uuid()}),release:$o,validatedAt:be.iso.datetime({offset:!0}),validUntil:be.iso.datetime({offset:!0}),entries:be.array(be.strictObject({id:be.uuid(),funnelId:be.uuid(),versionId:be.uuid(),event:be.enum(["screen_enter","button_click"]),target:rv})).max(4e3)}),jg=be.strictObject({operation:be.literal("entry_start"),funnelId:be.uuid(),versionId:be.uuid(),entryId:be.uuid(),release:$o,requestId:be.uuid(),locale:be.string().min(1).max(35).default("en")}),Tg=be.strictObject({scope:De,suppressed:be.literal(!0),reason:be.enum(["frequency","in_progress"]),retryAt:be.iso.datetime({offset:!0}).nullable()}),dD=be.strictObject({experimentId:be.uuid(),splitNodeId:be.string().min(1).max(128)}),iv=be.strictObject({experimentId:be.uuid(),experimentKey:be.string().min(1).max(128),variationKey:be.string().min(1).max(128),inExperiment:be.boolean(),generation:be.string().min(1).max(256)}),Go=be.strictObject({operation:be.literal("page_experiments"),release:$o,usedReceiptIds:be.array(be.uuid()).max(20).default([]),customerToken:be.string().regex(Ft).optional()}),Ng=be.strictObject({scope:De,runId:be.uuid(),assignments:be.array(iv.extend({receiptId:be.uuid()})).max(100),payload:kg});var Mn=se.literal(Hf),ov=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),dl=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Dg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:dl}),se.strictObject({type:se.literal("customer"),customer:Qr,customerData:qi.optional()})]),pl=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),av=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:pl.omit({runId:!0,requestId:!0}).nullable()}),sv=se.union([ul,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),cv=zo.omit({authenticated:!0}).extend({identity:av,instruction:sv.nullable()}),uv=se.discriminatedUnion("operation",[Ct.options[2].omit({customerToken:!0}),Ct.options[3].omit({customerToken:!0}),Ct.options[4].omit({customerToken:!0}),Ct.options[5].omit({customerToken:!0}),Ct.options[6].omit({customerToken:!0}),Ct.options[7].omit({customerToken:!0})]),Es={contract:Mn,customerToken:se.string().regex(Ft)},Fg={contract:Mn,requestId:se.uuid(),runToken:ov,externalUserId:Qr.options[1].shape.value},Mg=se.discriminatedUnion("operation",[se.strictObject({contract:Mn,operation:se.literal("describe")}),se.strictObject({contract:Mn,operation:se.literal("start"),source:Dg,funnelId:Ct.options[0].shape.funnelId,requestId:se.uuid(),locale:Ct.options[0].shape.locale,parameters:Ct.options[0].shape.parameters}),jg.omit({operation:!0}).extend({contract:Mn,operation:se.literal("entry_start"),source:Dg}),se.strictObject({...Fg,operation:se.literal("bind_customer"),guestToken:dl,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Fg,operation:se.literal("binding_status"),guestToken:dl.optional()}),Ct.options[1].omit({operation:!0,customerToken:!0}).extend({...Es,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),Ct.options[8].omit({operation:!0,customerToken:!0}).extend({...Es,operation:se.literal("review")}),Go.omit({customerToken:!0}).extend(Es),se.strictObject({...Es,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:uv})]),ml=_s.omit({run:!0}).extend({contract:Mn,run:cv,settlement:_s.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),SD=Tg.extend({contract:Mn}),ID=se.discriminatedUnion("operation",[Mg.options[1].omit({contract:!0,source:!0,requestId:!0}),Mg.options[2].omit({contract:!0,source:!0,requestId:!0})]),vD=ml.extend({binding:pl,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),wD=se.discriminatedUnion("state",[se.strictObject({contract:Mn,scope:De,state:se.literal("not_accepted")}),se.strictObject({contract:Mn,scope:De,state:se.literal("conflict")}),se.strictObject({contract:Mn,scope:De,state:se.literal("bound"),binding:pl})]),OD=se.strictObject({contract:Mn,scope:De,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as Me}from"zod";var $i=Me.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ug=Me.strictObject({entry:$i,nodes:Me.array(Me.strictObject({id:$i,type:Me.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Me.record(Me.string(),$i),writes:Me.record(wt,wt),resources:Me.strictObject({screenId:$i.optional(),paywallVersionId:Me.uuid().optional(),couponId:Me.uuid().optional(),couponIds:Me.array(Me.uuid()).max(20).optional(),experimentId:Me.uuid().optional(),featureKey:Me.string().optional(),offeringVersionId:Me.uuid().optional()})})).min(1).max(500)}),qg={scope:De,funnelId:Me.uuid(),versionId:Me.uuid(),evaluationRevision:Me.number().int().nonnegative(),expiresAt:Me.iso.datetime({offset:!0}).nullable(),topology:Ug},Rs=Me.discriminatedUnion("evaluationMode",[Me.strictObject({...qg,evaluationMode:Me.literal("local"),growth:Sn,conditions:Me.record($i,Me.array(Me.strictObject({condition:nn,port:Me.string()})))}),Me.strictObject({...qg,evaluationMode:Me.literal("remote")})]),lv=Rs.options[0].extend({evaluation:Me.strictObject({maxTransitions:Me.number().int().min(1).max(1e4),variables:Me.record(wt,Oi),outputSchema:wi,terminals:Me.record($i,Me.strictObject({outcome:Me.enum(["completed","closed","ineligible","failed"]),output:No.nullable()}))})});function dv(e){return Ug.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Me.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function fl(e){let t=Vi.parse(e.document),n=e.evaluationMode==="local"?Sn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:dv(t)};return Rs.parse(e.evaluationMode==="remote"?r:{...r,growth:vs(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function Bg(e){let t=fl(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Vi.parse(e.document);return lv.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as at}from"zod";var Vg=at.string().regex(/^[a-f0-9]{64}$/),pv=Fi.omit({variations:!0,active:!0}).extend({changeId:Vg,variations:at.array(at.strictObject({urlRedirect:at.string().max(2048)})).min(2).max(20)}),Lg=at.strictObject({environmentId:at.uuid(),trackExposures:at.boolean(),generation:Vg,experiments:at.array(pv).max(100),savedGroups:ko}),mv=at.strictObject({eventUuid:at.uuid(),timestamp:at.iso.datetime({offset:!0}).optional(),deviceId:at.string().min(1).max(128),sessionId:at.string().min(1).max(128).optional(),url:at.url().max(2048),pageTitle:at.string().max(512).optional(),experimentKey:at.string().min(1).max(255),variationKey:at.string().min(1).max(64)}),qD=at.strictObject({events:at.array(mv).min(1).max(20)}),UD=at.strictObject({inserted:at.number().int().nonnegative(),duplicates:at.number().int().nonnegative(),skipped:at.number().int().nonnegative(),rejected:at.array(at.strictObject({index:at.number().int().nonnegative(),reason:at.string()}))});import{z as pt}from"zod";var gl=32,fv=522240;function yl(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var hv=pt.strictObject({nodeId:pt.string().min(1).max(64),visit:pt.number().int().nonnegative(),revision:pt.number().int().nonnegative()}),hl=pt.record(pt.string(),ve),gv=pt.strictObject({id:pt.uuid(),nodeId:pt.string().min(1).max(64),visit:pt.number().int().nonnegative(),input:pt.strictObject({schemaVersion:Do.shape.schemaVersion,kind:Do.shape.kind,selector:Do.shape.selector,contract:Do.shape.contract}),context:hl,removed:pt.array(pt.string()).max(100),attributes:hl,removedAttributes:pt.array(pt.string()).max(100),result:vh,offeringVersionId:pt.uuid().nullable(),events:pt.strictObject({entered:pt.string().regex(/^[1-9][0-9]{0,18}$/),decision:pt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),GD=pt.strictObject({schemaVersion:pt.literal(1),mode:pt.enum(["local","remote"]),versionId:pt.uuid(),generation:pt.number().int().positive(),base:hv,context:hl,steps:pt.array(gv).min(1).max(gl)}).refine(e=>fn(e)<=fv,"Segment exceeds its byte budget");var yv=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Ko(e){return Array.isArray(e)?e.some(Ko):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Ko(n):!yv.test(t))}function zg(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>Ko(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||Ko(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||Ko(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Al=class extends Error{constructor(n,r){super(r);Be(this,"code",n);this.name="FunnelLocalCalculationError"}},$g=(e,t)=>new Al(e,t),Av=e=>({experiments:e.experiments,features:e.features});function bv(e,t=$g){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Ai(e.growth.savedGroups),i=Av(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Wn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=cl({id:c.id,name:c.id,type:"condition",cases:m.map(h=>({condition:h.condition,target:c.outputs[h.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=cl({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=h.value,u=h.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let p=c.outputs[u]??(u==="value"?c.id:void 0);if(!p)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:p,...l===void 0?{}:{value:l}}}}}function xv(e,t){let n=Rs.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=bv(n,t);return(o,s)=>(i(),Sv(a,o,s))}function Sv(e,t,n){let r=Pt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function Iv(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(p=>p.next.attributeName===s.attributeName&&p.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function Gg(e,t,n,r=$g){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,p=!1,m,h=R=>zg(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(m??(m=xv(e,r)),Iv(m,R,{attributes:Pu({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<gl;R++){let y=a.get(u);if(!y||!yl(y)||h(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let C=y.type==="end"?y.output:y.value;if(A=C?.type==="feature"?d(y.id):{...A,port:"value",value:C?.type==="literal"?C.value:C?.type==="variable"?Yc({source:"variable",key:C.key,...C.path?{path:C.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},C&&(A.value===void 0||!xn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(fn({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let C=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(C===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=Pi(y,{value:C});qm(t.variables,y,j),Object.assign(o,j)}for(let C of A.sticky)s[`${C.next.attributeName}||${C.next.attributeValue}`]=structuredClone(C.next);if(y.type==="end"||y.type==="output"){p=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let g=a.get(u);return{steps:c,...!p&&g&&(!yl(g)||h(g))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Be(this,"code",n);Be(this,"status",i);Be(this,"requestId",a);Be(this,"commandRequestId");Be(this,"retryable");Be(this,"recovery");Be(this,"retryAfterSeconds");Be(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=ra(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var Ho=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},vv=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function zn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Kg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||De.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function p(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let C=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await vv(x);if(!/^[a-f0-9]{64}$/.test(C))throw new b("INVALID_STATE","Push credential digest is invalid");return C}function m(x){let v=kr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function h(x,v){let C=u(),j={installationId:C.installationId,publicKey:C.publicKey,issuedAt:new Date().toISOString(),...v},_=await C.sign(ed(x,C.scope,j));return{...j,signature:_}}let d=(x,v,C)=>t.requestWithCredential?t.requestWithCredential(x,v,C):t.request(x,v);async function g(){let x=u(),v=i,C=r?await(t.session?.access()??r):null,j=zn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,At=Wl.parse(await h("detach",{sequence:Se,platform:x.platform}));try{let Ye=await t.request("push/installations/detach",{...x.scope,...At},"POST",{installationDetach:!0});if(!Ye||typeof Ye!="object"||!("installation"in Ye))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Ne=m(Ye.installation);if(Ne.bound||Ne.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ye){if(Ye instanceof b&&Ye.status===404)_=Ye;else if(!(Ye instanceof b)||Ye.status!==412)throw Ye}_||zn(x,Ye=>({...Ye,detachSeq:Ye.detachSeq===Se?null:Ye.detachSeq}))}if(l(v),!C){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await h("bind",{sequence:o,platform:x.platform,credentialDigest:await p(C)}));l(v);let ye=X.response.parse(await d(X.path,le,C));l(v);let ke=m(ye.installation);if(!ke.bound||ke.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&zn(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),ke}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let C=O.readPushInstallation,j=C.request.parse(await h("read",{credentialDigest:await p(v)}));l(x);let _=C.response.parse(await d(C.path,j,v));return l(x),m(_.installation)}function y(x=g){let v=s.catch(()=>{}).then(x);return s=v,v.catch(C=>{try{e?.onError?.(C instanceof Error?C:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,C){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await g(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let ye=zn(j,Ne=>C?Ne:{...Ne,addressSeq:Ho(Ne.addressSeq)}),Se=await h(C?"recovery_confirm":"recovery_request",{...x,sequence:ye.addressSeq,credentialDigest:await p(le),...C?{challenge:C}:{}}),At=C?Xl.parse(Se):Yl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Ye=await d(`push/installations/recovery/${C?"confirm":"request"}`,At,le);if(l(_),X!==a||zn(j,Ne=>Ne).addressSeq!==ye.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Ne=O.updatePushAddress.response.parse(Ye),it=m(Ne.installation);if(!it.bound||it.identitySeq!==o||it.addressSeq!==ye.addressSeq||it.connectionId!==x.connectionId||it.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return it}if(!Ye||typeof Ye!="object"||!("recovery"in Ye))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Qs.parse(Ye.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Qs.parse(await A(v,x))},async confirm(v,C){return kr.parse(await A(C,x,v))}}},identify(x){if(!e)return;o=zn(e,C=>({...C,identitySeq:Ho(C.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{zn(e,x=>{let v=Ho(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,C=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=zn(x,X=>{if(X.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Ho(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await g()})},tokenObserver(){u();let x=++a,v=i;return async C=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=zn(j,Se=>({...Se,addressSeq:Ho(Se.addressSeq)})),le=O.updatePushAddress,ye=le.request.parse(await h("address",{...C,sequence:X.addressSeq,credentialDigest:await p(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,ye,_);return l(v),x!==a||zn(j,Se=>Se).addressSeq!==X.addressSeq?null:m(le.response.parse(ke).installation)}}}}import{ZodError as wv}from"zod";function Hg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof wv?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=Hg(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):Hg(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function Qg(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var Jg={name:"@tinkerlandai/longplay-sdk",version:"0.10.19-rc.3",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function We(e){return typeof e=="string"?e:String(e)}var Pv=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Cv(e){return e.replace(Pv,"$1\uFFFD")}function Il(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function iy(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function Zg(e){let t;if(Array.isArray(e)){let n=e.map(We);if(n.length===2)return n}else if((t=iy(e))!=null){let n=Il(t.next()),r=Il(t.next());if(!n.done&&!r.done)return[We(n.value),We(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Wg="0123456789ABCDEF",_v=/(?:%[0-9A-Fa-f]{2})+/g;function $n(e){return`%${Wg[e>>4&15]}${Wg[15&e]}`}function oy(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?$n(e):String.fromCharCode(e):e<=2047?$n(192|e>>6)+$n(128|63&e):e<=65535?$n(224|e>>12)+$n(128|e>>6&63)+$n(128|63&e):$n(240|e>>18)+$n(128|e>>12&63)+$n(128|e>>6&63)+$n(128|63&e)}function vl(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function wl(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(_v,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function Zo(e){return e<=31||e>126}function Ev(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return Zo(e)}}function kl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return Zo(e)}}function Rv(e){return kl(e)||e===39}function Ol(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return kl(e)}}function Ds(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Ol(e)}}function Yg(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return Ds(n)}})(e)}}function ay(e,t){return oy(e=e||0,t)}function Gn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=oy(o,t,n)}return i}function jl(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([wl(i.slice(0,a),!0),wl(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Pl(e){let t="";for(let n=0;n<e.length;n++){let r=Gn(e[n][0],Yg,!0),i=Gn(e[n][1],Yg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var kv=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],jv=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Tv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Nv=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Dv(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[Fv,Mv,qv,Xg]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function Uv(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function sy(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Qo(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function Bv(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&sy(Nv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Qo(Xg,t[i]);)i--;let a=n+1;for(;a<t.length&&Qo(Xg,t[a]);)a++;if(!(i>=0&&a<t.length&&Qo(Mv,t[i])&&Qo(qv,t[a])))return!1}return!0}var Vv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Lv=/\p{Script=Latin}/u;function zv(e){return!Vv.test(e)||!Lv.test(e)}var br=36,js=1,Cl=26,$v=38,Gv=700,Kv=72,Hv=128,Qv=2147483647;function ey(e){return String.fromCharCode(e+22+75*+(e<26))}function Jv(e,t,n){let r=0;for(e=n?Math.floor(e/Gv):e>>1,e+=Math.floor(e/t);e>(br-js)*Cl>>1;r+=br)e=Math.floor(e/(br-js));return Math.floor(r+(br-js+1)*e/(e+$v))}function Zv(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=Hv,o=0,s=Kv;for(;r<t.length;){let c=Qv;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let p=o;for(let m=br;;m+=br){let h=m<=s?js:m>=s+Cl?Cl:m-s;if(p<h)break;n+=ey(h+(p-h)%(br-h)),p=Math.floor((p-h)/(br-h))}n+=ey(p),s=Jv(o,r+1,r===i),o=0,r++}}o++,a++}return n}function bl(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=vl(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function ty(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function cy(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function uy(e){return e.length===2&&cy(e.codePointAt(0),e.codePointAt(1))}function ny(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function gt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function ly(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function _l(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,l=0,p=0;for(;p<4&&(u=vl(c[s]))>=0;)l=(l<<4)+u,s++,p++;if(c[s]===46){if(p===0||o>6)return null;s-=p;let m=0;for(;c[s]!==void 0;){let h=0;if(m>0)if(c[s]===46&&m<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(h=10*h+vl(c[s]),h>255)return null;s++}i[o]=256*i[o]+h,m++,m%2==0&&o++}if(m!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return ny(r)?null:Gn(r,Zo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let p=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!sy(kv,p)||Qo(Fv,p))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let p of u){let m=p.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(p))continue;let h=Uv(p,m);if(h){l+=h;continue}let d=jv.indexOf(m);l+=d<0?p:Tv[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(Dv(u)||l&&(/^\p{Mark}/u.test(u)||!Bv(u)||!zv(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${Zv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:wl(e));return n===null||ny(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(bl(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let l=bl(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=bl(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function El(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,p=0;for(let m=0;m<s.length;++m)s[m]!==0?(p>l&&(c=u,l=p),u=-1,p=0):(u===-1&&(u=m),++p);return p>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function dy(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function py(e){return e.username!==""||e.password!==""}function xl(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",$e=null,B,Ts=!1,Ns=!1,ti=!1,yt;function An(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),E=0,U=e,Oe="",$e=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ts=!1,Ns=!1,ti=!1,yt=r||0;let i=Wv;switch(r){case 3:case 4:i=Fs;break;case 5:i=Nl;break;case 6:i=ni;break;case 7:i=xr;break;case 8:i=Kn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?qn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function qn(e){return e!=null&&e>65535?2:1}function my(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Wv=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Oe=U.slice(E,n).toLowerCase(),E=n,Yv(n<U.length?e:void 0)}else return yt?1:(--E,ee(t,e)?fy(G(U,E)):0)},Yv=e=>{let t=E;if(e===58){if(yt){if(gt(B.scheme)!==gt(Oe))return 0;if((py(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,yt?(B.port===ly(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?Dl(G(U,E)):0:gt(B.scheme)&&$e!==null&&$e.scheme===B.scheme?ee(t,e)?Xv(G(U,E)):0:gt(B.scheme)?ee(t,e)?tw(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?ew(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?gy(G(U,E)):0))}else return yt?1:(Oe="",E=-1,ee(t,e)?fy(G(U,E)):0)},fy=e=>{let t=E;return $e===null||$e.opaquePath&&e!==35?1:$e.opaquePath&&e===35?(B.scheme=$e.scheme,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,B.fragment="",ee(t,e)?Kn(G(U,E)):0):$e.scheme==="file"?(E--,ee(t,e)?Dl(G(U,E)):0):(E--,ee(t,e)?Tl(G(U,E)):0)},Xv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?qs(G(U,E)):0):(E--,ee(t,e)?Tl(G(U,E)):0)},ew=e=>{let t=E;return e===47?ee(t,e)?Gi(G(U,E)):0:(E--,ee(t,e)?Un(G(U,E)):0)},Tl=e=>{let t=E;return B.scheme=$e.scheme,e===47||gt(B.scheme)&&e===92?ee(t,e)?ry(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,B.path=$e.path.slice(),B.query=$e.query,e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Un(G(U,E)):0):ee(t,e)?Tl(G(U,E)):0)},ry=e=>{let t=E;return gt(B.scheme)&&(e===47||e===92)?ee(t,e)?qs(G(U,E)):0:e===47?ee(t,e)?Gi(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,E--,ee(t,e)?Un(G(U,E)):0)},tw=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?qs(G(U,E)):0},qs=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Gi(G(U,E)):0):ee(t,e)?qs(G(U,E)):0},Gi=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!gt(B.scheme))){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&gt(B.scheme))break;n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Gi(G(U,E)):0}if(e===64){Ts&&(Oe=`%40${Oe}`),Ts=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!Ns){Ns=!0;continue}let i=ay(r,Ds);Ns?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Gi(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&gt(B.scheme)?Ts&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?Fs(G(U,E)):0):(Oe+=my(e),ee(t,e)?Gi(G(U,E)):0)},Fs=e=>{let t=E;if(yt&&B.scheme==="file")return E--,ee(t,e)?Fl(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!gt(B.scheme))){let n=E+qn(e);for(e===91?ti=!0:e===93&&(ti=!1);n<U.length;){let r=G(U,n);if(r==null||!ti&&r===58||r===35||r===47||r===63||r===92&&gt(B.scheme))break;r===91?ti=!0:r===93&&(ti=!1),n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Fs(G(U,E)):0}else if(e===58&&!ti){if(Oe===""||yt===4)return 1;let n=_l(Oe,!gt(B.scheme));return n===null?1:(B.host=El(n),Oe="",ee(t,e)?Nl(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&gt(B.scheme)){if(E--,gt(B.scheme)&&Oe==="")return 1;if(yt&&Oe===""&&(py(B)||B.port!==null))return 1;let n=_l(Oe,!gt(B.scheme));return n===null?1:(B.host=El(n),Oe="",yt?0:ee(t,e)?ni(G(U,E)):0)}else return Oe+=my(e),ee(t,e)?Fs(G(U,E)):0},Nl=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Nl(G(U,E)):0}else if(yt||e==null||e===35||e===47||e===63||e===92&&gt(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===ly(B.scheme)?null:n,Oe="",yt)return 0}return yt?1:(E--,ee(t,e)?ni(G(U,E)):0)}else return 1};function hy(e,t){let n=e.length-t;if(n<2)return!1;if(cy(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var Dl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?nw(G(U,E)):0:$e?.scheme==="file"?(B.host=$e.host,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(B.query=null,hy(U,E)?B.path=[]:dy(B),E--,ee(t,e)?Un(G(U,E)):0):ee(t,e)?Dl(G(U,E)):0):(E--,ee(t,e)?Un(G(U,E)):0)},nw=e=>{let t=E;return e===47||e===92?ee(t,e)?Fl(G(U,E)):0:($e!==null&&$e.scheme==="file"&&(!hy(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})($e.path[0])&&B.path.push($e.path[0]),B.host=$e.host),E--,ee(t,e)?Un(G(U,E)):0)},Fl=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Fl(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!yt&&uy(Oe))return ee(t,e)?Un(G(U,E)):0;if(Oe==="")return B.host="",yt?0:ee(t,e)?ni(G(U,E)):0;{let n=_l(Oe,!gt(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=El(n),Oe="",yt?0:ee(t,e)?ni(G(U,E)):0)}}return 1},ni=e=>{let t=E;return gt(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Un(G(U,E)):0):!yt&&e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):!yt&&e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Un(G(U,E)):0):(yt&&B.host===null&&B.path.push(""),ee(t,e)?ni(G(U,E)):0)},Un=e=>{let t=E;if(e!=null&&e!==47&&(!gt(B.scheme)||e!==92)&&(yt||e!==63&&e!==35)){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||gt(B.scheme)&&r===92||!yt&&(r===63||r===35))break;n+=qn(r)}Oe+=Gn(U.slice(E,n),Ol),E=n,e=G(U,n)}if(e==null||e===47||gt(B.scheme)&&e===92||!yt&&(e===63||e===35)){let n=gt(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Oe)?(dy(B),e!==47&&!n&&B.path.push("")):ty(Oe)&&e!==47&&!n?B.path.push(""):ty(Oe)||(B.scheme==="file"&&B.path.length===0&&uy(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):ee(t,e)?Un(G(U,E)):0}else return Oe+=ay(e,Ol),ee(t,e)?Un(G(U,E)):0},gy=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?xr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Kn(G(U,E)):0;if(e!=null){let n=E+qn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=qn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Gn(r.slice(0,-1),Zo)+"%20":B.path[0]+=Gn(r,Zo),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?xr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Kn(G(U,E)):0}return ee(t,e)?gy(G(U,E)):0},xr=e=>{let t=E,n=E;if(e!=null){if(yt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=gt(B.scheme)?Rv:kl;B.query+=Gn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!yt?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):ee(t,e)?xr(G(U,E)):0},Kn=e=>{let t=E;return e!=null&&(B.fragment+=Gn(U.slice(E),Ev),E=U.length),ee(t,e)?Kn(G(U,E)):0};function Rl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function yy(e){switch(e.scheme){case"blob":{let t=An(Rl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":yy(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Ze=Symbol("URLImpl"),wn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=We(t),n!=null&&(n=We(n));let r=null;if(n!=null&&(r=An(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=An(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=We(t),n!==void 0&&(n=We(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=We(t),n!==void 0&&(n=We(n));let r=null;return n!=null&&(r=An(n,null,null,0),r==null)?!1:An(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=Rl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ze].url)}set href(t){let n=An(t=We(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze].url=n,this[Ze].query&&Sl(this[Ze].query,n.query)}get origin(){return yy(this[Ze].url)}get protocol(){return`${this[Ze].url.scheme}:`}set protocol(t){An(`${t=We(t)}:`,this[Ze].url,null,2)}get username(){return this[Ze].url.username}set username(t){t=We(t),xl(this[Ze].url)||(function(r,i){r.username=Gn(i,Ds)})(this[Ze].url,t)}get password(){return this[Ze].url.password}set password(t){t=We(t),xl(this[Ze].url)||(function(r,i){r.password=Gn(i,Ds)})(this[Ze].url,t)}get host(){let{url:t}=this[Ze];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=We(t),this[Ze].url.opaquePath||An(t,this[Ze].url,null,3)}get hostname(){let{url:t}=this[Ze];return t.host!=null?t.host:""}set hostname(t){t=We(t),this[Ze].url.opaquePath||An(t,this[Ze].url,null,4)}get port(){let{url:t}=this[Ze];return t.port!=null?`${t.port}`:""}set port(t){t=We(t);let{url:n}=this[Ze];xl(n)||(t?An(t,n,null,5):n.port=null)}get pathname(){return Rl(this[Ze].url)}set pathname(t){t=We(t);let{url:n}=this[Ze];n.opaquePath||(n.path=[],An(t,n,null,6))}get search(){let{url:t}=this[Ze];return t.query?`?${t.query}`:""}set search(t){t=We(t);let{url:n,query:r}=this[Ze];if(!t)n.query=null,r&&Sl(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",An(i,n,null,7),r&&Sl(r,n.query)}}get searchParams(){let t=this[Ze],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Ms;return o[lt].url=i,o[lt].serialized=a==null,a&&(o[lt].list=jl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ze];return t.fragment?`#${t.fragment}`:""}set hash(t){t=We(t);let{url:n}=this[Ze];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",An(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(wn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var lt=Symbol("URLSearchParamsImpl"),rw=Symbol.dispose||Symbol.for("dispose");function Sl(e,t){t?e[lt].list=jl(t):e[lt].list.length=0,e[lt].serialized=t==null}function ks(e){if(e.url){let t=Pl(e.list);(function(r,i){r[Ze].url.query=i})(e.url,t||null),e.serialized=!0}}var iw=typeof Iterator<"u"?Iterator:Object,Jo=class extends iw{constructor(t,n){super(),this[lt]={ptr:t,map:n,index:0}}next(){let t=this[lt];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[rw](){}},Ms=class{constructor(t){let n=this[lt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Zg(t[i]));else if((r=iy(t))!=null){let i;for(;!(i=Il(r.next())).done;)n.list.push(Zg(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=Cv(o),c=We(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=We(t);i=i[0]==="?"?i.substring(1):i,n.list=jl(i)}}get size(){return this[lt].list.length}append(t,n){t=We(t),n=We(n),this[lt].list.push([t,n]);let r=this[lt];r.url&&r.serialized?(function(a,o){let s=a[Ze].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Pl([[t,n]])):ks(r)}delete(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[lt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ks(this[lt])}get(t){t=We(t);let{list:n}=this[lt];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=We(t);let n=[],{list:r}=this[lt];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[lt];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=We(t),n=We(n);let{list:r}=this[lt],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&ks(this[lt])}sort(){this[lt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ks(this[lt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[lt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Jo(this[lt],t=>t)}keys(){return new Jo(this[lt],t=>t[0])}values(){return new Jo(this[lt],t=>t[1])}toString(){return Pl(this[lt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ms.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Sr="https://api.longplayai.com";function Ay(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let p of[...a.keys()])try{p()}catch{}};function s(p){let m=++r;i=void 0,t=void 0;for(let h of[...a.values()])try{h?.()}catch{}m===r&&(t=p,o())}let c=()=>s();function u(p,m=!1){let h=ar.safeParse(p);if(!h.success||m&&Date.parse(h.data.expiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<Date.parse(h.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return h.data}async function l(){if(i)return i;let p=typeof t=="object"?t:void 0,m=r;if(!p||Date.parse(p.refreshExpiresAt)<=Date.now())throw p&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let h=(async()=>{try{let d=await e(p.refreshToken);if(m!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(d,!0);if(g.customerId!==p.customerId||g.sessionId!==p.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,{...g}}catch(d){throw m!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=h;try{return await h}finally{i===h&&(i=void 0)}}return{identify(p){let m=typeof p=="string"?p:u(p),h=typeof m=="string"?m:m.accessToken;if(!h.trim()||/\s/.test(h)||h.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(m)},reset:c,subscribeIdentity(p,m){return a.set(p,m),()=>{a.delete(p)}},access(){let p=typeof t=="object"?t:void 0;if(p&&Date.parse(p.expiresAt)<=Date.now()+3e4){let h=r;return l().then(()=>{let d=n();if(h!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let m=n();if(!m)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var by=Symbol("IndianaNoContent");function Ir(e,t,n=wn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?De.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??Sr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,p=null,m=new Set,h=e.session??Ay(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:C,...j}=x;return j});function d(){l+=1,p=null;for(let A of m)A.abort();m.clear()}let g=h.subscribeIdentity(d);function R(){u||h.reset()}async function y(A,x={},v="POST",C={},j){let _=C.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||m.add(le);let ye=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),ke,Se=new Promise((Ne,it)=>{ke=()=>it(ye()),le.signal.addEventListener("abort",ke,{once:!0})}),At=setTimeout(()=>le.abort(),C.timeoutMs??c),Ye=async()=>{let Ne=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...C.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Xs]:ec.current,[od]:Jg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...C.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw ye();let it;try{it=Ne.status===204?by:await Ne.json()}catch{throw le.signal.aborted?ye():new b(Ne.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Ne.status,Ne.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw ye();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Ne.ok){let ft=Ys.safeParse(it),Xt=ft.success&&(!Jn.safeParse(ft.data.error.code).success||rd(ft.data.error.code,Ne.status)),Cr=Xt?ft.data.error.code:"HTTP_ERROR",_r=ra(Cr,Ne.status,{retryAfter:Ne.headers.get("Retry-After"),recovery:Xt?ft.data.error.recovery:void 0,reason:Xt?ft.data.error.reason:void 0});throw new b(Cr,Xt?ft.data.error.message:"Longplay request failed",Ne.status,Ne.headers.get("X-Request-Id")??(ft.success?ft.data.requestId:void 0),{..._r,...ft.success&&ft.data.error.retryable===!1?{retryable:!1}:{},..._r.retryAfterSeconds===void 0&&ft.success&&ft.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ft.data.error.retryAfterSeconds}:{}})}if(Ne.headers.get(Xs)!==ec.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&it!==by){let ft=it&&typeof it=="object"&&"scope"in it?it:it&&typeof it=="object"&&"configuration"in it?it.configuration:null;if(!ft||typeof ft!="object"||!("scope"in ft))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Xt=De.safeParse(ft.scope);if(!Xt.success||Xt.data.projectId!==a.projectId||Xt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let ii=Ne.headers.get("X-Indiana-Telemetry-Subject");if(ii){if(!/^[a-f0-9]{64}$/.test(ii))throw new b("INVALID_RESPONSE","Invalid telemetry identity");p!==ii&&(p=ii,t?.(p))}return it};try{return await Promise.race([Ye(),Se])}catch(Ne){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Ne instanceof b?Ne:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(At),le.signal.removeEventListener("abort",ke),m.delete(le)}}return{session:h,requestWithCredential(A,x,v,C={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",C,v)},subjectKey:()=>p,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=De.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}h.identify(A)},reset:R,dispose(){u||(u=!0,g(),d())},request(A,x={},v="POST",C={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(C.installationDetach)return y(A,x,v,C);let j=l;try{let _=h.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,C,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function xy(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!Ft.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Ml(e,t,n,r){if(!Ld(e,t)||n!==void 0&&t.observation&&t.observation.subject.customerId!==n||r!==void 0&&t.observation!==void 0&&(t.observation.subject.scope.projectId!==r.projectId||t.observation.subject.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","The access requirement or Customer changed");return t}function vr(e,t,n){if(e.requirement){if(!t)throw new b("INVALID_RESPONSE","The requested access check is missing");Ml(e.requirement,t,e.customerId,n)}}function Ge(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var ow={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Sy(e){return{async checkEntitlement(t){Ge(t);let n=O.checkEntitlement,r=n.request.parse(t),i=await ge(e,n,r);return Ml(r.requirement,i.check,void 0,i.scope),i},async readHoldings(t={}){return ge(e,ow,t)}}}function Iy(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Ge(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Ge(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function vy(e){return{async setupPayment(t){Ge(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Ge(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Ge(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Ge(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Ge(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Ge(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Ge(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ge(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ge(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Ge(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function wy(e){return{async previewUpdate(t){Ge(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Ge(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Ge(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Ge(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Ge(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Ge(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Ge(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Oy(e){return{async redeemReward(t){return Ge(t),(await ge(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ge(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ge(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Py(e){return{...Sy(e),...Iy(e),...vy(e),...wy(e),...Oy(e)}}function Cy(e){return{async resolveContent(t){Ge(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Ge(t);let n=O.resolvePaywall,r=n.request.parse(t),i=await ge(e,n,r);return vr(r,i.paywall.check,i.scope),i},async resolveOffering(t){Ge(t);let n=O.resolveOffering,r=n.request.parse(t),i=await ge(e,n,r);return vr(r,i.check,i.scope),i}}}var ql=e=>new TextEncoder().encode(JSON.stringify(e)).length,_y=16384;function Ey(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,p().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,g={},R={}){if(c(),r&&Date.now()<r.until&&!Vf(r.config,d))return;h();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:g,...R}]}).events[0];if(ql({events:[y]})>_y)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function p(d=!1){if(c(),o)return o;let g=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let x=[],v=ql({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ql(_)+(x.length?1:0);if(x.length&&v+X>_y)break;x.push(_),v+=X}let C=O.trackEvents,j=await ge(e,C,{events:x},void 0,{keepalive:d});if(g!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let m;function h(){if(m||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&p(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),m=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:p,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){m?.(),m=void 0}}}function Ul(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:Pt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},p=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function m(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>m(v.id,A))))}let h=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?p():structuredClone(o.features[y]??p()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||m(y)?p():structuredClone(Wn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],C=(async()=>{let j=as.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=Pt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:C};try{await C}finally{s?.loading===C&&(s=null)}}function g(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?jo.parse(x):null,C=v??Sn.parse(x);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===C.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:ye,expiresAt:ke,...Se}=C;if(_t(le)!==_t(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=C.evaluatedAt,t.expiresAt=C.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&g(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(C.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in C&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(C),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=Ai(t.savedGroups),l.trackedFeatureUsage={},u(),g(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=Pt.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),g()},evalFeature:h,isOn(y){return h(y).on},isOff(y){return h(y).off},getFeatureValue(y,A){let x=h(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function Ry(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function aw(e){let t=Ry(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function ky(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,p=!1,m=async()=>{if(p||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ye=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,ye,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(ke.scope.projectId!==r.projectId||ke.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ke.payload.analyticsConfig),ke},h=await m(),d=!0,g,R=ye=>{try{u.onError?.(ye)}catch{}},y=(ye,ke,Se)=>{try{let At=Ry(Se);n.track(ye,ke,At?{merchandise:At}:{})}catch(At){R(At)}},A=Ul({assertUsable:i?.assertFeatures,scope:h.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,h.payload):(await m()).payload,evaluateRemote:async ye=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...ye,attributes:aw(ye.attributes)});if(Se.scope.projectId!==h.scope.projectId||Se.scope.environment!==h.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(ye,ke,Se)=>y("Experiment Viewed",{experimentId:ye.key,variationId:ke.key},Se),onFeatureUsage:(ye,ke,Se)=>y("Feature Evaluated",{feature:ye,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(g),!i&&(p||l!==a||!A.expiresAt||(g=setTimeout(()=>{C().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function C(){try{return await x()}finally{v()}}let j=()=>{p||C().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!p&&i.fresh&&C().catch(R)});function le(){p||(p=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(ye){throw le(),ye}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:C,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as sw}from"zod";function jy(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=sw.object({funnelId:Cs.shape.id,funnelVersionId:Cs.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering,c=s.request.parse(a(o)),u=await ge(e,s,c);return vr(c,u.check,u.scope),u},async resolvePaywall(o){let s=O.resolvePaywall,c=s.request.parse(a(o)),u=await ge(e,s,c);return vr(c,u.paywall.check,u.scope),u},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Ty(e){let t=Ir(e),n=t.request,r;try{r=Kg(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=xy(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ey(n,i.isIdentified),o=ky(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Qg(n,r),...Py(n),...Cy(n),forFunnel(s){return i.assertActive(),jy(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ki(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ki(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ki(a,Reflect.get(t,i)))}function Us(e,t){let n=Eg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Hi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Bs(e){let t=Ft.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Hi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Ct.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=Ir({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=Us(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ki(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function Bl(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((p,m)=>{s=()=>m(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let p=await Promise.race([r.read(),c]);if(p.done){o=!0;break}if(a+=p.value.length,a>t)throw n.error("limit");i.push(p.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let p of i)u.set(p,l),l+=p.length;return u}async function Ny(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Bl(e,t,n))}function Vs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Ju(n)===t.sha256}async function Ls(e,t){let n=Zr.parse(t),{artifact:r,environmentId:i}=n.content,a=new wn(e.baseUrl??Sr).origin,o=new wn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((p,m)=>{c=setTimeout(()=>{let h=new b("TIMEOUT","Public Paywall read timed out");s.abort(h),m(h)},sn.initializationMs)}),l=(async()=>{let p=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(p.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>r.byteLength)throw p.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let m=await Bl(p,r.byteLength,{signal:s.signal,error:h=>new b("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Vs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Fh(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Dy=(e,t)=>new b(e,t);var cw=3,uw=2e3;function lw(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function dw(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===cw||!lw(n))throw n;await new Promise(r=>setTimeout(r,t*uw))}}async function Vl(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=pw(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await dw(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function pw(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=fl({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:Sn.parse(o)}),c=mw(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function mw(e,t,n){return Gg(e,t,n,Dy)}import{z as bn}from"zod";var Fy=Ct.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),My=bn.strictObject({schemaVersion:bn.literal(1),scope:De,runId:bn.uuid(),funnelId:bn.uuid(),versionId:bn.uuid(),processBindingIds:bn.record(bn.uuid(),bn.uuid().nullable()).optional(),command:Fy.optional(),closeCommand:Fy.refine(e=>e.operation==="close").optional(),purchase:bn.strictObject({receiptId:bn.uuid(),operationId:bn.uuid(),generation:bn.number().int().nonnegative()}).optional(),closed:bn.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),rn=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),zs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function qy(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:My.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let p=await a();if(p.entry&&n!==null&&r(p.entry)!==n)throw rn();let m=u(p.entry,p.revision);if(zs(p.entry,m)){t=p.revision;return}let h=await e.write(p.revision,m);if(h!==null){if(!Number.isSafeInteger(h)||h<=p.revision)throw rn();t=h;return}}throw rn()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let p={...u.processBindingIds};delete p[l],u={...u,processBindingIds:p}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw rn();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=My.parse(u),p=l.command;return!p||n!==null&&r(l)!==n?Promise.reject(rn()):(n??(n=r(l)),o(()=>s((m,h)=>{if(m&&!zs(r(m),r(l)))throw rn();if(m&&l.processBindingIds){for(let[d,g]of Object.entries(l.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,d)&&m.processBindingIds[d]!==g)throw rn();m={...m,processBindingIds:{...m.processBindingIds,...l.processBindingIds}}}if(!m){if(h!==t&&p.operation!=="close")throw rn();return l}if(!m.command)return{...m,command:p,...p.operation==="close"?{closed:!0}:{}};if(p.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===p.requestId||m.closeCommand&&!zs(m.closeCommand,p))throw rn();return{...m,closeCommand:p,closed:!0}}if(!zs(m.command,p))throw rn();return m})))},observePurchase(u,l,p,m){return o(()=>s((h,d)=>{if(!h&&d!==t||h&&r(h)!==r({...u,schemaVersion:1}))throw rn();if(h?.purchase&&h.purchase.generation>l.generation)return c(h,m);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw rn();return p?!h?.purchase||h.purchase.operationId!==l.operationId?c(h,m):c(h.command?{...h,purchase:void 0}:null,m):c({schemaVersion:1,...u,...h,purchase:l},m)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function Uy(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Sr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function By(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(p){if(n&&(n.projectId!==p.projectId||n.environment!==p.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...p})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(p,m="Run identity changed during the request"){if(p!==i||s)throw new b("IDENTITY_CHANGED",m)},assertRun(p){if(r&&(p.id!==r.id||p.source.type!==r.source.type||p.source.id!==r.source.id||p.source.versionId!==r.source.versionId||p.locale!==r.locale||!Ki(p.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&p.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(p,m,h,d,g){if(!(p.operation==="review"&&r&&r!==h&&m.run.revision<=r.revision)&&!(r&&m.run.revision===r.revision&&d!==void 0&&d<u)&&(p.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&r&&m.run.nodeId===r.nodeId&&m.run.visit===r.visit&&m.run.revision===r.revision&&(m.run.screen=r.screen,(r.paywall?.quote?.operationId===m.review?.activeOperationId||!r.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=r.paywall)),!(r?.paywall&&m.run.paywall&&r.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||m.run.revision>=r.revision)r=m.run;else if(!g)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(p){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!Ft.test(p))throw new b("INVALID_TOKEN","Customer credential required");o(),c=p},subscribe(p){return l.add(p),()=>l.delete(p)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function wr(e){let{customerToken:t,...n}=e;return n}var fw=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Vy({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,p=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();p.catch(()=>{});async function m(y){e&&await p;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:wr(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!fw(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function h(y){let A=Ct.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return g(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(wr(a))!==JSON.stringify(wr(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(wr(i))!==JSON.stringify(wr(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=m(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function g(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:p,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let C=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=C&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==C&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?C:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,ye=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=ye?.operationId??le?.quote?.operationId??ke?.operationId,At=le?.receiptId??ke?.receiptId,Ye=X?.selectionGeneration??u?.generation??0;if(e&&Se&&At&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Ye>=u.generation)){let Ne={receiptId:At,operationId:Se,generation:Ye},it=ye?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},Ne,it,j),t.assertCurrent(x),(!u||Ne.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(it?u?.operationId===Ne.operationId&&(u=void 0):u=Ne)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:h,settle:g,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function Or(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Hi.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=Ir({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=By(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Uy(e):void 0),o=a&&qy(a),s=Vy({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),C=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,ye=()=>{},ke=new Promise((Se,At)=>{ye=()=>At(X.reason),X.addEventListener("abort",ye,{once:!0}),le=setTimeout(()=>At(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",ye)}}n.assertCurrent(x);let j={...A,...C?{customerToken:C}:{}},_=A.operation==="page_experiments"?Go.parse(j):Ct.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!C?{[Rg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,C=()=>n.assertCurrent(v);o&&await s.ready,C();let j=n.view,_=Us(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(C(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(C(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let p=s.submit,m=null,h=new WeakMap;function d(A){let x=h.get(A);if(x)return x;let v=R(A);return h.set(A,v),v}let g=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(m)return m;g=!0;let v=n.generation,C=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await Vl(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let ye=!0;Vl(e.configuration,_).then(({prediction:ke})=>{ye&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=ke)}).catch(()=>{});try{x=await p({operation:"commit_segment",requestId:_g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{ye=!1,i=null}}}return x})();m=C;try{return await C}finally{m===C&&(m=null)}}let y={get configuration(){return g?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(wr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(wr(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return Ls(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let C=n.view?.id;if(!C)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Ng.parse(await c(Go.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==C||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(p(s.pending)):d(p({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(p(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?p(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(p(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function Ly(e){if(!Ft.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=Bs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Or({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function zy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function $y(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function Gy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function Ky(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function Hy(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function Qy(e,t){if(!Ft.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=Ir(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,p=null,m=null,h=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function g(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector});vr(n,v.paywall.check,v.scope);let C=await Ls(e,v.paywall);if(d(),t.paywallVersionId?C.id!==t.paywallVersionId:C.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!zy(C,i)||C.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=C,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(m){if(p===x)return m;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(p&&p!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");p=x,h++}let C=p,j=h,_=x==="read"&&m===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let ye=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x},...x==="confirm"&&v.merchantTerms?{merchantConfirmation:_d(v.merchantTerms)}:{}});return $y(ye.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(ye.operation):(s=Ky(s,ye.operation),(x!=="read"||_&&m===null)&&h===j&&p===C&&(p=null),structuredClone(s))})();if(x!=="read"){m=le;let ye=()=>{m===le&&(m=null)};le.then(ye,ye)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return Hy({quote:o,operation:s,requestId:l,pending:u!==null||p!==null,destroyed:a})},get pendingCancellation(){return!a&&p==="cancel"},refresh:g,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let C=qf(v.product,x.selection,i.capabilities);if(!C)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Ch(i.document.screen,C,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:C,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||p||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let ye=O.previewAttach,ke=await ge(r.request,ye,_);return d(),Gy(ke.quote,{productVersionId:C,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=ke.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await g(),y}catch(x){throw y.destroy(),x}}function Jy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let h=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,h)).catch(()=>{})}),l=e.nativeEvents?.(h=>{!n||!e.nativeModule||typeof h?.requestId!="string"||(async()=>{let d=await n;if(h.instanceId!==d)return;if(h.kind==="credential"){let y=r,A=null;try{if(!o&&h.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,h.requestId,A)}return}let g=!1,R=r;try{if(o||h.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(h.action),g=!o&&r===R}finally{await e.nativeModule.acknowledge(d,h.requestId,g)}})().catch(()=>{})});async function p(h,d={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let C=(async()=>{if(await g.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await g.reset(A,R),c();i=R})();a={epoch:R,task:C}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await g.invoke(A,h,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function m(h,d){let g=await p(h,d);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(h){return m("showFunnel",{runToken:h})},showPaywall(h){return m("showPaywall",h)},showContent(h){return m("showContent",h)},purchaseSubscription(h,d){return p("purchaseSubscription",{operationId:h,accepted:d})},switchSubscription(h,d){return p("switchSubscription",{operationId:h,accepted:d})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(h){return p("manageSubscriptions",h?{productId:h}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var hw=O.trackUsage.request.shape.command,gw=O.trackUsage.response;function yw(e){let t=De.parse(e.scope),n=Ty({...e,scope:t}),r={...e,scope:t,session:n.session},i=Jy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return Ly({...r,customerToken:s()})},resumeFunnel(c){return s(),Or({...r,runToken:c})},paywall(c){return Qy(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=hw.parse(c),l=a,p;try{p=await e.usageReporter(u)}catch(h){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):h}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let m=gw.parse(p);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}import{z as Sw}from"zod";import{z as Wo}from"zod";var Aw=Wo.record(Wo.string().regex(/^[a-f0-9]{64}$/),Wo.strictObject({at:Wo.number(),text:Wo.string()})),ri=2*1048576,bw=100;function xw(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Zy(e,t){let n=t===void 0?xw():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(p){if(!n)return null;let m;try{let h=await Promise.race([Promise.resolve().then(()=>n.getItem(p)),new Promise(d=>{m=setTimeout(()=>d(null),bw)})]);return typeof h=="string"&&h.length<=ri&&new TextEncoder().encode(h).byteLength<=ri?h:null}catch{return null}finally{clearTimeout(m)}}function l(){if(c)return c;let p=(async()=>{try{let m=await u(`${e}:artifacts`);if(m)return Aw.parse(JSON.parse(m))}catch{}return{}})();return c=p,p.finally(()=>{c===p&&(c=void 0)}),p}return{async readManifest(){return u(e)},writeManifest(p){!n||p.length>ri||new TextEncoder().encode(p).byteLength>ri||(s=p,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let m=s;try{await n.setItem(e,m)}catch{}s===m&&(s=void 0)}}finally{o=!1}})))},async readArtifact(p){let m=(await l())[p],h=Date.now();return m&&h>=m.at&&h-m.at<=sn.retentionMs?m.text:void 0},writeArtifact(p,m){if(!n||m.length>ri)return;let h=r.get(p);if(h?.text===m||!h&&r.size>=128)return;let d=new TextEncoder().encode(m).byteLength;i-(h?.byteLength??0)+d>ri||(r.set(p,{text:m,byteLength:d}),i+=d-(h?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let g=new Map(r);try{let R={...await l()},y=Date.now();for(let[C,j]of g)R[C]={at:y,text:j.text};let A={},x=2,v=0;for(let[C,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>sn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[C]:j})).byteLength;x+_>ri||v>=128||(A[C]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of g)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),Pr=()=>performance.now(),Wy=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Iw(e){let t=Ku.parse(e.scope),n=new wn(e.origin??Sr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new wn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${_t(t)}`,s=Zy(o,e.storage),c,u=0,l=0,p=!1,m=!1,h=0,d=0,g,R,y,A,x=0,v=new Set,C=new Set,j=new Map,_=new Map,X=0,le=!1;function ye(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!m&&!p&&!!c&&Pr()<u&&Date.now()<l;function At(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ye(Y,J,pe){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+pe>sn.maxCacheBytes);){let me=j.entries().next().value;X-=me[1].byteLength,j.delete(me[0])}j.set(Y,{text:J,byteLength:pe}),X+=pe}}function Ne(Y,J,pe){return Ny(Y,J,{signal:pe,error:me=>Pe("INVALID_RESPONSE",me==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function it(Y){let J=new wn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function Yo(Y,J,pe=!1){let me=await i(it(Y),{method:"GET",credentials:"omit",redirect:"error",cache:pe?"default":"no-cache",signal:J,headers:{}});if(me.status===429){let nt=me.headers.get("retry-after")??"";x=/^\d+$/.test(nt)?Number(nt)*1e3:Math.max(0,Date.parse(nt)-Date.now())||15e3}if(!me.ok&&me.status!==304)throw Pe(`CONFIGURATION_HTTP_${me.status}`,"Configuration synchronization failed");return me}function ii(Y,J,pe){let me=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),nt=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),st=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),un=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![me,nt,st,un].every(Number.isFinite)||nt<=me||nt-me>sn.maxControlAgeMs||me>st+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let zt=Math.min(nt-me,pe.maxControlAgeSeconds*1e3,sn.maxControlAgeMs)-Math.max(un,st-me,0)-(Pr()-J);if(zt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Pr()+zt}function ft(){if(clearTimeout(y),clearTimeout(A),m||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?ft():ye()},Math.max(1,u-Pr())),Wy(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Xt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),Wy(y)}async function Xt(){if(m)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=h,J=new AbortController;R=J;let pe=(async()=>{if(!le){le=!0;try{let ea=await s.readManifest();if(ea&&!c){let Qn=Qu.parse(JSON.parse(ea));_t(Qn.scope)===_t(t)&&(c=Qn)}}catch{}}J.signal.throwIfAborted();let Ke=c,un=Pr(),Kt=await Yo(a,J.signal);Kt.status===304&&(!Ke||!Kt.headers.has("x-indiana-config-validated-at")||!Kt.headers.has("x-indiana-config-valid-until")||!Kt.headers.has("age"))&&(Kt=await Yo(a,J.signal));let zt=Kt.status===304?Ke:Qu.parse(JSON.parse(await Ne(Kt,sn.maxManifestBytes,J.signal))),{generation:oi,...ai}=zt,Hn=Kt.headers.get("etag");if(_t(zt.scope)!==_t(t)||jh(ai)!==oi||Hn!==`"${oi}"`&&Hn!==`W/"${oi}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(zt.revision<Ke.revision||zt.revision===Ke.revision&&zt.generation!==Ke.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ea,Qn]of Object.entries(Ke?.funnels??{})){let Rr=zt.funnels[ea];if(Rr&&(Rr.controlRevision<Qn.controlRevision||Rr.evaluationRevision<Qn.evaluationRevision||Rr.controlRevision===Qn.controlRevision&&Rr.state!==Qn.state||Rr.evaluationRevision===Qn.evaluationRevision&&Rr.evaluationMode!==Qn.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let Er=ii(Kt,un,zt.policy);if(J.signal.throwIfAborted(),Y!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=zt,u=Er,l=Date.now()+Math.max(0,Er-Pr()),p=!1,d=0,x=0,s.writeManifest(_t(zt)),ye(),structuredClone(zt)})(),me=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs),nt=new Promise((Ke,un)=>J.signal.addEventListener("abort",()=>un(J.signal.reason),{once:!0})),st=Promise.race([pe,nt]).catch(Ke=>{throw d++,(Ke instanceof Sw.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,p=!0,ye()),Ke}).finally(()=>{clearTimeout(me),g===st&&(g=void 0),ft()});return g=st,st}async function Cr(Y){let J=Y.sha256,pe=ai=>Vs(ai,Y);it(Y.url);let me=j.get(J);if(me){if(me.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,me),me.text}let nt=_.get(J);if(nt){if(nt.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return nt.promise}let st=new AbortController;C.add(st);let Ke=h,un=(async()=>{try{let Er=await s.readArtifact(J);if(Er&&pe(Er)){if(st.signal.throwIfAborted(),m||Ke!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Ye(J,Er,Y.byteLength),Er}}catch{}st.signal.throwIfAborted();let ai=await Yo(Y.url,st.signal,!0),Hn=await Ne(ai,Y.byteLength,st.signal);if(!pe(Hn))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||Ke!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Ye(J,Hn,Y.byteLength),s.writeArtifact(J,Hn),Hn})(),Kt=setTimeout(()=>st.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),sn.initializationMs),zt=new Promise((ai,Hn)=>st.signal.addEventListener("abort",()=>Hn(st.signal.reason),{once:!0})),oi=Promise.race([un,zt]).finally(()=>{clearTimeout(Kt),C.delete(st),_.delete(J)});return _.set(J,{promise:oi,byteLength:Y.byteLength}),oi}async function _r(){return Se()||await Xt(),At(),c}async function Qi(Y){let J,pe=new Promise((me,nt)=>{J=setTimeout(()=>nt(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs)});try{return await Promise.race([Y(),pe])}finally{clearTimeout(J)}}function Ji(Y,J){if(At(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function zl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let pe=Y.artifacts[J];if(pe.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let me=Au.parse(JSON.parse(await Cr(pe)));if(_t(me.scope)!==_t({projectId:t.projectId,environment:t.environment})||me.generation!==pe.generation||me.remoteFeatures.some(nt=>Object.hasOwn(me.features,nt)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ji(Y),{...me,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Pr())).toISOString()}}async function $l(Y,J){let pe=await _r(),me=pe.funnels[Y];J&&(!me||me.evaluationMode==="local"&&!me.versions[J])&&(g&&await g,pe=await Xt()),Ji(pe,Y);let nt=pe.funnels[Y];if(nt.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let st=J??nt.currentVersionId,Ke=nt.versions[st];if(!Ke)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(pe.artifacts[Ke.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[un,Kt]=await Promise.all([Cr(pe.artifacts[Ke.artifact]).then(zt=>Nh(JSON.parse(zt))),nt.evaluationMode==="local"?zl(pe):void 0]);if(Kt&&_t(Th(un,Kt))!==_t(Ke.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ji(pe,Y),{document:un,growth:Kt,versionId:st,control:structuredClone(nt),manifest:structuredClone(pe)}}async function Gl(Y,J){try{return await $l(Y,J)}catch(pe){if(!(pe instanceof b)||!(pe.code==="CONFIGURATION_CHANGED"||pe.code==="CONFIGURATION_HTTP_404"&&Se()))throw pe;let me=c?.generation;if(g&&await g,await Xt(),pe.code!=="CONFIGURATION_CHANGED"&&c?.generation===me)throw pe;return $l(Y,J)}}function $s(){p=!0,ye(),Xt().catch(ke)}let Xo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&$s()};function Yy(Y){if(m)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",$s),window.addEventListener("focus",Xo),document.addEventListener("visibilitychange",Xo)),ft()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Kl())}}function Kl(){typeof window<"u"&&(window.removeEventListener("online",$s),window.removeEventListener("focus",Xo),document.removeEventListener("visibilitychange",Xo))}return{scope:Object.freeze({...t}),refresh:Xt,subscribe:Yy,assertFresh:At,assertFeatures(Y){At();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-Pr()):0},async features(){return Qi(async()=>zl(await _r()))},pageExperiments:()=>Qi(async()=>{let Y=await _r(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let pe=Y.artifacts[J];if(pe.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let me=Lg.parse(JSON.parse(await Cr(pe)));if(me.environmentId!==t.environmentId||me.generation!==pe.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Ji(Y),me}),funnel:(Y,J)=>Qi(()=>Gl(Y,J)),paywall:(Y,J)=>Qi(async()=>{let pe=await _r(),me=pe.paywalls?.[Y];if(!me||!J&&me.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let nt=J??me.currentVersionId,st=me.versions[nt],Ke=st&&pe.artifacts[st.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let un=Os.parse(JSON.parse(await Cr(Ke)));return Ji(pe),{document:un,versionId:nt,version:st.version,control:structuredClone(me),manifest:structuredClone(pe)}}),async localFunnel(Y,J){let pe=await Qi(()=>Gl(Y,J));if(!pe.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:me,remoteFeatures:nt,...st}=pe.growth;return Bg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:pe.versionId,evaluationMode:"local",evaluationRevision:pe.control.evaluationRevision,document:pe.document,payload:st})},assertFunnel(Y,J,pe){At();let me=c.funnels[Y];if(!me||me.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(me.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&me.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(pe!==void 0&&!me.versions[pe])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Kl(),ye(),v.clear();for(let Y of C)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function vw(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&_t(n)!==_t(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Hi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=Bs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Or({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function Ll(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function ww(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(m){let h,d=new Promise((g,R)=>{h=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),d])}finally{clearTimeout(h)}}function c(m){throw m instanceof b&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),m}function u(m,h){if(h!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=ml.parse(m);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)Ll(j,d.run);d.run.instruction?.type==="authentication_required"&&Ll(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:g,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,C=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:g.binding!==null,instruction:R?.type==="authentication_required"?null:R},...C?{settlement:C}:{}}}let l=m=>(a.has(m)||a.set(m,t?.run.identity.binding?.id??null),a.get(m));async function p(m){let h=r,d=t?.run.identity.binding?.id??null,g=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(m.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(g)}let R;if(m.operation==="get"){let{operation:y,customerToken:A,...x}=m;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(g)}else if(m.operation==="review")R=await s(()=>e.adapter.review(m.receiptId)).catch(g);else{if(m.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=m;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(g)}}return u(R,h)}return{get view(){return t?.run??null},get controller(){return n},async open(m){let h=r,d=await s(()=>e.adapter.open(m)).catch(c);if(u(d,h),!n){n=Or({...e,runToken:d.runToken,process:{request:p,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let g=n,R=g.submit;g.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await g.settle?.(y.requestId),await g.get();let x=g.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let g of n.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(g.requestId);return{run:t.run,controller:n}},async syncIdentity(){let m=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),m),await n?.get();for(let h of n?.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(h.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(m){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:m}},subscribe(m){return i.add(m),()=>{i.delete(m)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,Iw as createConfigurationSync,Ul as createFeatureClient,ww as createFunnelProcess,vw as createLocalFunnelClient,yw as createLongplayReactNative};
17
+ */var ve=N.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Pt=N.record(N.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),gb=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),nn=Pt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.strictObject({id:N.uuid(),attributeKey:N.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!gb.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),yb=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:nn}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Yn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var Ab=N.record(N.uuid(),yb).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Yn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),jc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),Op=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(jc).min(1).max(100)}),bb=N.strictObject({id:N.string().min(1).max(128),condition:nn,gate:N.boolean().optional()}),kc={id:N.string().max(128).optional(),condition:nn.optional(),parentConditions:N.array(bb).max(50).optional(),filters:N.array(Op).max(20).optional()},xb=N.union([N.strictObject({...kc}),N.strictObject({...kc,force:ve,coverage:N.number().min(0).max(1).optional(),range:jc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...kc,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),Sb=N.strictObject({defaultValue:ve,rules:N.array(xb).max(100)}),ZP=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Sb).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Ib=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:nn,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(jc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),vb=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(Ib).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var wb=vb.safeExtend({filters:N.array(Op).optional()}),Ob=N.strictObject({experiments:N.record(N.uuid(),wb),savedGroups:Ab}),uo=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),WP=N.strictObject({snapshot:Ob,attributes:Pt,results:Pt,stickyBucketAssignmentDocs:N.record(N.string(),uo)}),YP=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function lr(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var Pb=qt.enum(["active","inactive"]),Cb=qt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},Pt),_b=qt.strictObject({id:qt.string().trim().min(1).max(255),name:qt.string().trim().min(1).max(255),status:Pb,metadata:Cb}),iC=_b.extend({internal_id:qt.uuid(),project_id:qt.uuid(),environment_id:qt.uuid(),created_at:qt.iso.datetime({offset:!0}),updated_at:qt.iso.datetime({offset:!0})}),Cp=qt.union([qt.strictObject({id:qt.string().trim().min(1).max(255)}),qt.strictObject({internalId:qt.uuid()})]),oC=qt.enum(["customer","merchandise","context"]),aC=qt.enum(["system","stored","request"]),sC=qt.enum(["customer","merchandise","mixed"]),Pp=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Tc(e,t={},n=new Set){if(lr(e).some(Pp))return!0;for(let r of Yn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Pp(i.attributeKey)||i?.type==="condition"&&Tc(i.condition,t,n))return!0}return!1}import{z as Eb}from"zod";var Rb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,Cn=Eb.string().max(16).regex(Rb,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var hC=te.enum(["draft","active","paused","archived"]),dr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),dn=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),_p=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],kb=te.discriminatedUnion("type",[..._p,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:nn})])})]),Nc=te.discriminatedUnion("type",[..._p,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),jb=te.strictObject({firstPurchaseOnly:te.boolean(),condition:nn}),gC=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:dr,duration:dn,appliesTo:kb,eligibility:jb,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!Tc(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),yC=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var lo=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:dr,duration:dn,appliesTo:Nc}).strict()}).strict(),Ep=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Np=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Dc=S.string().regex(/^(0|[1-9]\d{0,14})$/),bi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Tb=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),po=Tb,Xn=de.refine(e=>/[1-9]/.test(e)),Qt=S.iso.datetime({offset:!0}),Ra=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},Nb=S.array(S.object({upTo:Xn.nullable(),unitAmountMinor:Np,flatAmountMinor:S.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Ra(t.upTo)>Ra(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Db=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Xn,unitAmountMinor:Np}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Xn,tiers:Nb}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Fb=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),mo=S.object({currency:Ie,pricing:Db,billingCycle:Fb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Rp={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Dp=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Fp=S.discriminatedUnion("kind",[S.object({...Rp,kind:S.literal("auto_topup"),threshold:la,quantity:Xn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Dp.optional()}).strict(),S.object({...Rp,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:po,maxOutstandingMinor:po}).strict()]),kp={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Mp=S.discriminatedUnion("kind",[S.object({...kp,kind:S.literal("auto_topup"),threshold:la,quantity:Xn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Dp.optional(),purchaseAmountMinor:po,purchaseUnits:Xn}).strict(),S.object({...kp,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:po,maxOutstandingMinor:po,cashPrice:mo}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ka=S.object({id:S.uuid(),terms:Mp,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:Qt,acceptedAt:Qt.nullable(),effectiveAt:Qt.nullable(),revokedAt:Qt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),qp=S.object({authorizationId:S.uuid(),terms:Mp,setupUrl:S.url().nullable()}).strict(),Up=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Bp=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),Vp=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:Ot.optional(),limit:de.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Xn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&Ra(t)>Ra(i)}),"Notification thresholds must increase"),Mb=Vp.safeExtend({requestId:S.uuid()}),jp={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},qb=S.discriminatedUnion("action",[S.strictObject({...jp,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...jp,action:S.literal("remove")})]),Lp=S.union([Mb,qb]),Ub=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:Qt,endsAt:Qt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Bb=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:Ot.optional(),startsAt:Qt,endsAt:Qt,used:tn,reserved:tn,limit:de.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Xn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Xn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||de.safeParse(e.used).success&&de.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Vb=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:Qt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:Qt.nullable(),nextAttemptAt:Qt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),zp=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),Fc=S.object({authorizations:S.array(ka).max(100),limits:S.array(Vp).max(100),overages:S.array(Ub).max(100).optional(),windows:S.array(Bb).max(200),autoTopups:S.array(Vb).max(100),limited:S.boolean()}).strict(),Lb=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:de,amountMinor:bi,cashPrice:mo}).strict(),fo=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Qt.nullable(),endsAt:Qt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Dc,paidAmountMinor:Dc,refundedAmountMinor:Dc,createdAt:Qt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Qt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(Lb).max(100),linesLimited:S.boolean()}).strict(),$p=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),Gp=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.string().trim().min(1).max(500)}),Kp=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),Hp=S.object({rows:S.array(fo).max(100),nextCursor:S.uuid().nullable()}).strict(),Tp=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),zb=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(Tp).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:Tp.optional()})).max(20)})).max(100)}),Qp=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Jp=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:zb.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:dr,duration:dn,startedAt:Qt.nullable()})).max(20)});import{z as ho}from"zod";var Zp=ho.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Wp=ho.number().int().min(1).max(1e3),ja=ho.object({cap:de.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:ho.number().positive().max(1e4).nullable(),cycles:ho.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as pr}from"zod";var Yp=pr.strictObject({itemKey:pr.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:pr.uuid(),includedAmount:pr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:pr.number().int().min(0).max(1e4),terms:Ia,pricing:ao.optional(),unitAmountMinor:pr.number().int().min(0).max(1e8),productId:pr.string().min(1).max(255).nullable(),priceId:pr.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Xd(e.includedAmount,e.terms.units,e.quantity),Sa({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as ne}from"zod";var Mr=de.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),go=ne.string().min(1).max(120),Ta=ne.enum(["cap","overflow"]),pn=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},yo=e=>{try{return e()}catch{return!1}},Ao=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:Ta.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Mr,properties:Ot}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:Ta.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:de,properties:Ot,idempotencyKey:go}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Mr,properties:Ot,idempotencyKey:go,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Mr,properties:Ot.optional(),idempotencyKey:go}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Mr,idempotencyKey:go}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:go}).strict()]),Mc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:de,units:Mr,amount:tn,tier:ne.number().int().min(1).max(12).nullable()}).strict(),qr=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Xp(e,t){let n=e.reduce((r,i)=>r+pn(i.units,12),0n)-pn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var em=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:qr.refine(e=>/[1-9]/.test(e)),amount:tn}),ne.strictObject({funding:ne.literal("unbilled"),units:qr.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Mr,amount:tn,pricing:ne.array(Mc).min(1).max(12)}).strict().refine(e=>yo(()=>e.pricing.reduce((t,n)=>t+pn(n.units,6),0n)===pn(e.units,6)&&e.pricing.reduce((t,n)=>t+pn(n.amount,12),0n)===pn(e.amount,12)&&e.pricing.every(t=>pn(t.unitCost,6)*pn(t.units,6)===pn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Mr,authorizationId:ne.uuid()}).strict()]),Na=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),tm=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:de,requestedQuantity:de.optional(),overageBehavior:Ta.optional(),reason:Na.nullable(),allocations:ne.array(em).max(500)}).strict().refine(e=>yo(()=>e.allowed?e.reason===null&&Xp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>yo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&pn(e.requestedQuantity,6)>=pn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),bo=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:de,requestedQuantity:de.optional(),overageBehavior:Ta.optional(),accepted:ne.boolean(),reason:ne.enum([...Na.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(em).max(500)}).strict().refine(e=>yo(()=>e.accepted?e.reason===null&&Xp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>yo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&pn(e.requestedQuantity,6)>=pn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as Fe}from"zod";var Ur=Fe.iso.datetime({offset:!0}),nm=de.refine(e=>/[1-9]/.test(e)),rm=Fe.strictObject({interval:Zp.exclude(["lifetime"]),count:Wp}),$b=Fe.strictObject({action:Fe.literal("create"),requestId:Fe.uuid(),internal_feature_id:Fe.uuid(),entityId:Fe.uuid().nullable(),amount:nm.nullable(),expiresAt:Ur.nullable(),reset:rm.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),im=Fe.discriminatedUnion("action",[$b,Fe.strictObject({action:Fe.literal("update"),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative(),amount:nm.nullable(),expiresAt:Ur.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable()}),Fe.strictObject({action:Fe.enum(["add","subtract","set_remaining"]),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative(),amount:de}),Fe.strictObject({action:Fe.literal("revoke"),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative()})]),qc=Fe.strictObject({id:Fe.uuid(),internal_feature_id:Fe.uuid(),entityId:Fe.uuid().nullable(),amount:de.nullable(),reset:rm.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable(),startsAt:Ur,expiresAt:Ur.nullable(),revision:Fe.number().int().nonnegative(),revoked:Fe.boolean(),available:tn,held:tn,spent:tn}),om=Fe.strictObject({customerId:Fe.uuid(),after:Fe.uuid().nullable(),limit:Fe.number().int().min(1).max(100)}),am=Fe.strictObject({rows:Fe.array(qc).max(100),nextCursor:Fe.uuid().nullable()});import{z as ie}from"zod";var Bn=ie.iso.datetime({offset:!0}),sm=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),Gb=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Bn.nullable(),endsAt:Bn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),cm=ie.strictObject({invoice:fo,items:ie.array(ie.discriminatedUnion("kind",[Gb,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:de,reserved:de,amountMinor:bi,grossAmountMinor:bi,creditsAppliedMinor:bi,properties:Ot,cashPrice:mo,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:de,reserved:de,amountMinor:bi,cashPrice:mo})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),Kb=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Uc=ie.strictObject({from:Bn,to:Bn,entityId:ie.uuid().optional(),snapshotAt:Bn.nullable(),after:ie.strictObject({at:Bn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),um=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Bn,to:Bn,snapshotAt:Bn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:tn,refunded:tn,net:Kb})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Bn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:qr,amount:tn,pricing:ie.array(Mc).max(12),properties:Ot})).max(100),nextCursor:Uc.shape.after});import{z as D}from"zod";import{z as _n}from"zod";var Hb=_n.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Qb=_n.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Da=_n.strictObject({internal_feature_id:_n.uuid(),entityId:_n.uuid().nullable()}),lm=Da.extend({quantity:de,expectedRevision:_n.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:_n.string().min(1).max(120),properties:Ot.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),xo=Da.extend({operationId:_n.uuid().nullable(),usage:de,capacity:Hb.nullable(),remaining:Qb.nullable(),withinLimit:_n.boolean(),revision:_n.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:_n.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Jt=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),En=D.iso.datetime({offset:!0}),Jb=D.enum(["access","metered","credit"]),So={internal_feature_id:D.uuid(),key:Tr,name:D.string().min(1).max(120),kind:Jb},dm=D.object({customerId:D.uuid(),snapshotAt:En,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:En,benefitsAppliedAt:En.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.object({phase:D.enum(["paid","trial"]),startsAt:En,endsAt:En.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...So,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:Jt,held:Jt,debt:Jt,nextExpiresAt:En.nullable(),usage:xo.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.boolean()}).strict(),pm=D.enum(["source","usage","transaction","invoice","debt","settlement"]),Fa=D.object({at:En,id:D.uuid(),type:pm}).strict(),mm=D.object({type:pm.nullable(),resourceKey:Tr.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:Fa.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),xi={id:D.uuid(),occurredAt:En},Zb=D.discriminatedUnion("type",[D.strictObject({...xi,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:Jt,refunded:Jt,currency:Ie,externalId:D.string().nullable()}),D.object({...xi,...So,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Jt,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:En,expiresAt:En.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...xi,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:de,accepted:D.boolean(),reason:D.enum([...Na.options,"expired"]).nullable(),properties:Ot,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:En.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:qr,amount:Jt}),D.strictObject({funding:D.literal("unbilled"),units:qr}),D.object({...So,funding:D.literal("prepaid"),amount:Jt}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:de,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.object({...xi,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.object({...xi,...So,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:Jt}).strict(),D.object({...xi,...So,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:Jt}).strict()]),fm=D.object({customerId:D.uuid(),rows:D.array(Zb).max(50),nextCursor:Fa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as he}from"zod";var gm=he.object({customerId:he.uuid()}).strict(),ym=he.discriminatedUnion("action",[he.object({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("assign"),poolId:he.uuid(),memberCustomerId:he.uuid()}).strict(),he.strictObject({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("assign_entity"),poolId:he.uuid(),entityId:he.uuid()}),he.object({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("release"),poolId:he.uuid(),slotId:he.uuid()}).strict()]),Io=he.number().int().nonnegative(),Bc=he.iso.datetime({offset:!0}),Vc=he.strictObject({internalId:he.uuid(),id:he.string(),name:he.string().nullable(),version:he.number().int().positive()}),hm=he.enum(["active","past_due"]),Lc=he.strictObject({customerId:he.uuid(),licenses:he.array(he.strictObject({id:he.uuid(),linkId:he.uuid(),parent:he.strictObject({customerProductId:he.uuid(),status:hm,product:Vc}),product:Vc,planLicense:he.strictObject({id:he.uuid(),prepaidOnly:he.boolean(),isCustom:he.boolean()}).nullable(),granted:Io,included:Io,paidQuantity:Io,usage:Io,remaining:Io,createdAt:Bc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:he.array(he.strictObject({id:he.uuid(),linkId:he.uuid(),status:hm,product:Vc,entity:he.strictObject({internalId:he.uuid(),id:he.string().nullable(),name:he.string().nullable()}).nullable(),beneficiary:he.strictObject({internalId:he.uuid(),id:he.string().nullable(),name:he.string().nullable()}).nullable(),startedAt:Bc.nullable(),endedAt:Bc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:he.boolean()});import{z as fe}from"zod";var vo=fe.enum(["email","sms","voice","push"]),n_=fe.enum(["resend","twilio","fcm","apns"]);var r_=fe.string().regex(/^\+[1-9]\d{1,14}$/),Wb=fe.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Yb=fe.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Xb=fe.strictObject({subject:Yb,html:fe.string().min(1).max(131072).optional(),text:fe.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ex=fe.strictObject({body:fe.string().min(1).max(1600).refine(e=>e.trim().length>0)}),tx=fe.strictObject({text:fe.string().trim().min(1).max(4e3),language:fe.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:fe.number().int().min(1).max(900)}),nx=fe.record(fe.string().min(1).max(64),fe.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),rx=fe.strictObject({title:fe.string().trim().min(1).max(200),body:fe.string().trim().min(1).max(2e3),url:fe.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:nx.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Am=fe.discriminatedUnion("channel",[fe.strictObject({channel:fe.literal("email"),content:Xb}),fe.strictObject({channel:fe.literal("sms"),content:ex}),fe.strictObject({channel:fe.literal("voice"),content:tx}),fe.strictObject({channel:fe.literal("push"),content:rx})]),bm=fe.strictObject({requestId:fe.uuid(),customerId:fe.uuid(),connectionId:fe.uuid().optional(),message:Am,expiresAt:fe.iso.datetime({offset:!0})}),ix=fe.array(fe.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),ox=fe.discriminatedUnion("kind",[fe.strictObject({kind:fe.literal("all")}),fe.strictObject({kind:fe.literal("customers"),customerIds:ix})]),i_=fe.strictObject({name:fe.string().trim().min(1).max(120),connectionId:fe.uuid().optional(),message:Am,audience:ox,frequencyLimit:fe.number().int().min(1).max(100)}),xm=fe.strictObject({requestId:fe.uuid(),channel:vo,state:fe.enum(["allowed","denied"]),expectedRevision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Sm=fe.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Im=fe.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),o_=fe.strictObject({meter:Wb,estimatedUnits:fe.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:fe.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as Si}from"zod";var wo=Si.strictObject({internalFeatureId:Si.uuid(),name:Si.string().min(1).max(120),includedAmount:Si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Si.enum(["hour","day","week","month","year","lifetime"]),resetCount:Si.number().int().min(1).max(100),terms:Ia});var qa=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ma=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),Ii=re.object({paywall:sr.optional(),nodes:re.record(re.string(),re.object({base:Ma,picker:re.string().optional(),byPlan:re.record(re.string(),Ma).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(wo).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function vm(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function ax(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function wm(e){let t={};function n(r){var i;if(ax(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}import{z as er}from"zod";var Om=er.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ua=er.strictObject({tiers:er.array(er.strictObject({id:Om,name:er.string().trim().min(1).max(80)})).min(1).max(8),assignments:er.array(er.strictObject({productVersionId:er.string().min(1).max(200),tierId:Om,period:er.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Ba(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var sx=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Pm=ce.enum(sx),Cm=ce.object({source:Pm,layout:ce.enum(["full","compact"]),resourceKey:Tr.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Tt=ce.string().max(2e3),_m=ce.object({id:ce.string().max(100),label:Tt,detail:ce.array(Tt).max(12),value:Tt.optional(),status:Tt.optional(),facts:ce.array(ce.object({label:Tt,value:Tt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Tt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Tt}).strict()).max(3).optional()}).strict(),cx=ce.object({key:Tr,name:Tt,spendable:Tt,reserved:Tt,available:Tt,expiry:Tt.nullable(),sources:ce.array(_m).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),ux=ce.object({source:Pm,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Tt.optional(),resources:ce.array(cx).max(500),rows:ce.array(_m).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Tt,note:Tt,facts:ce.array(ce.object({label:Tt,value:Tt}).strict()).max(100)}).strict().optional(),membershipResult:Tt.optional()}).strict(),Em=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ux)}).strict(),x_=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.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:ce.string().max(100).optional()}).strict();import{z as K}from"zod";var vt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},km=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Ut=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!km.has(e),"Reserved UI identifier"),zc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),lx=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(zc).min(1).max(vt.enumValues),default:zc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function Gc(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var dx=lx.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),Gc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),px=["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 mx(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var Vr=K.lazy(()=>K.union([zc,K.strictObject({ref:Ut}),K.strictObject({op:K.enum(px),args:K.array(Vr).max(vt.expressionNodes)}).superRefine((e,t)=>{mx(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function Rn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Br(e,t,n){if(!e||typeof e!="object")return!0;if(!Rn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(km.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function vi(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>vt.expressionNodes||a.depth>vt.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Br(a.value,t,a.path))return;if(Rn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>vt.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var v_=K.unknown().superRefine((e,t)=>{vi(e,t,[],{nodes:0})}).pipe(Vr),$c=K.record(Ut,Vr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=vt.state,"UI assignments need 1\u201332 state keys"),fx=K.strictObject({target:Ut,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Vr,className:Ut.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),hx=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Ut,state:Ut}),K.strictObject({type:K.literal("input"),target:Ut,state:Ut,set:$c.optional()}),K.strictObject({type:K.literal("action"),target:Ut,set:$c}),K.strictObject({type:K.literal("carousel"),target:Ut,state:Ut,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Ut.optional(),nextTarget:Ut.optional(),inactiveTargets:K.array(Ut).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),gx=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:$c}),yx=K.strictObject({type:K.literal("mosaic_waves"),target:Ut,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Vr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),Ax=K.strictObject({type:K.literal("number_counter"),target:Ut,value:Vr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),bx=K.strictObject({state:K.record(Ut,dx).refine(e=>Object.keys(e).length<=vt.state,"Too many UI state keys").optional(),derived:K.record(Ut,Vr).refine(e=>Object.keys(e).length<=vt.derived,"Too many UI derived keys").optional(),bindings:K.array(fx).max(vt.bindings).optional(),controls:K.array(hx).max(vt.controls).optional(),timers:K.array(gx).max(vt.timers).optional(),effects:K.array(K.discriminatedUnion("type",[yx,Ax])).max(vt.effects).optional(),clock:K.boolean().optional()});function xx(e,t){if(!Br(e,t,[])||!Rn(e))return;for(let[r,i]of[["state",vt.state],["derived",vt.derived]]){let a=e[r];if(!Br(a,t,[r]))return;if(Rn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",vt.bindings],["controls",vt.controls],["timers",vt.timers],["effects",vt.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!Br(i,t,["effects",r]))return}if(Rn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Br(i,t,["state",r]))return;if(Rn(i)&&Array.isArray(i.values)&&i.values.length>vt.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(Rn(e.derived))for(let[r,i]of Object.entries(e.derived))vi(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!Br(o,t,[r,a])||!Rn(o))){if(r==="bindings")vi(o.expression,t,[r,a,"expression"],n);else if(Br(o.set,t,[r,a,"set"])&&Rn(o.set)){if(Object.keys(o.set).length>vt.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))vi(c,t,[r,a,"set",s],n)}if(n.nodes>vt.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())Rn(i)&&i.type==="number_counter"?vi(i.value,t,["effects",r,"value"],n):Rn(i)&&i.enabled!==void 0&&vi(i.enabled,t,["effects",r,"enabled"],n)}function Rm(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var jm=K.unknown().superRefine(xx).pipe(bx).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(h,d)=>{for(let g of Rm(h))i.has(g)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${g}`})};for(let[h,d]of Object.entries(e.derived??{}))Object.hasOwn(n,h)&&t.addIssue({code:"custom",path:["derived",h],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",h]);let o=new Set,s=new Set,c=h=>{if(o.has(h))return!1;if(s.has(h))return!0;o.add(h);for(let d of Rm(r[h]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(h),s.add(h),!0};for(let h of Object.keys(r))if(!c(h)){t.addIssue({code:"custom",path:["derived",h],message:"Cyclic UI derived references"});break}for(let[h,d]of(e.bindings??[]).entries())a(d.expression,["bindings",h,"expression"]);let u=new Set;for(let[h,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",h,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",h,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",h,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",h,"enabled"]);let l=(h,d)=>{for(let[g,R]of Object.entries(h))Object.hasOwn(n,g)||t.addIssue({code:"custom",path:[...d,g],message:"UI assignments can only update declared state"}),a(R,[...d,g])},p=new Set,m=new Set;for(let[h,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",h,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let g of d.inactiveTargets??[])(g===d.target||m.has(g))&&t.addIssue({code:"custom",path:["controls",h,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),m.add(g);if(d.type==="carousel")for(let g of["previousTarget","nextTarget"]){let R=d[g];R!==void 0&&((R===d.target||p.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",h,g],message:"Carousel navigation needs a distinct, exclusive button target"}),p.add(R))}if(d.type!=="action"){let g=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!g||d.type==="input"&&g.type==="enum"&&g.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",h,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(g?.type!=="number"||!Number.isInteger(g.min)||g.min<0||!Number.isInteger(g.max)||g.step!==1||d.initialIndex!==void 0&&!Gc(g,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",h],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&g?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",h,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",h,"set"])}for(let[h,d]of(e.timers??[]).entries())l(d.set,["timers",h,"set"])});import{z as ct}from"zod";var Sx=ct.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Va=ct.discriminatedUnion("type",[ct.object({type:ct.literal("fixed"),productVersionId:ct.string().min(1).max(200)}).strict(),ct.object({type:ct.literal("picker"),pickerId:Sx,allowedProductVersionIds:ct.array(ct.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Ix=ct.strictObject({min:ct.number().finite().min(1).max(1800),max:ct.number().finite().min(1).max(1800),viewport:ct.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Tm={desktopWidth:Ix.optional(),mobile:ct.enum(["sheet","fullscreen"]).optional(),backdrop:ct.enum(["none","scrim","dim","strong-dim","blur"]).optional()},kn=ct.discriminatedUnion("type",[ct.strictObject({type:ct.literal("modal"),size:ct.enum(["sm","md","lg"]),...Tm}),ct.strictObject({type:ct.literal("sheet"),size:ct.enum(["sm","md","lg"]),...Tm}),ct.strictObject({type:ct.literal("fullscreen")}),ct.strictObject({type:ct.literal("inline")})]);var wx=4,Tn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},Po=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ve=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ox=I.enum(["none","xs","sm","md","lg","xl"]),Px=I.enum(["none","sm","md","lg","full"]),Kc=I.string().regex(/^#[0-9a-fA-F]{6}$/),Qc=I.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Hc=I.union([Qc,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Nm=I.object({primary:Kc,background:Kc,text:Kc,radius:Px,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:Qc,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),Co=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ue=(e,t)=>I.number().int().min(e).max(t),Dm=I.union([I.enum(["fit","fill"]),Ue(1,1200)]),Cx=I.object({top:Ue(0,200),right:Ue(0,200),bottom:Ue(0,200),left:Ue(0,200)}).strict(),_x=I.object({top:Ue(-100,200),right:Ue(-100,200),bottom:Ue(-100,200),left:Ue(-100,200)}).strict(),Fm=I.object({x:Ue(0,100),y:Ue(0,100)}).strict(),Ex=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:Co}).strict(),I.object({type:I.literal("linear"),angle:Ue(0,360),stops:I.array(I.object({color:Co,at:Ue(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:Hc,fit:I.enum(["cover","contain"]),position:Fm.optional()}).strict()]),Rx=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Ue(0,200),I.object({topLeft:Ue(0,200),topRight:Ue(0,200),bottomRight:Ue(0,200),bottomLeft:Ue(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),kx=I.object({width:Ue(0,12),color:Co,style:I.enum(["solid","dashed"])}).strict(),jx=I.object({x:Ue(-40,40),y:Ue(-40,40),blur:Ue(0,80),spread:Ue(-20,40),color:Co}).strict(),Tx=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Ue(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:Co,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),Lr=I.object({width:Dm,height:Dm,padding:Cx,margin:_x,gap:Ue(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Ex,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Rx,border:kx,shadow:jx,text:Tx}).strict().partial(),an={id:Po,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:Lr.optional(),fallback:Ve.optional()},Nx=I.object({...an,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:Ve,variant:I.enum(["title","heading","body","caption"])}).strict(),Dx=I.object({...an,type:I.literal("image"),src:Hc,localizedSrc:I.record(Cn,Hc).optional(),alt:Ve,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Fm.optional()}).strict(),Fx=I.object({...an,type:I.literal("button"),label:Ve,variant:I.enum(["primary","secondary","link"]),action:Ve,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:qa.optional()}).strict(),Mx=I.object({...an,type:I.literal("divider")}).strict(),qx=I.object({...an,type:I.literal("customer_data"),title:Ve,data:Cm}).strict(),Ux=I.object({...an,type:I.literal("spacer"),size:Ox}).strict(),Bx=I.object({...an,type:I.literal("custom_html"),html:I.record(Cn,I.string().max(Tn.customHtml)),css:I.string().max(Tn.customCss),ui:jm.optional()}).strict(),Vx=I.object({...an,type:I.literal("price"),fallback:Ve,parts:I.object({current:Lr.optional(),original:Lr.optional(),period:Lr.optional()}).strict().optional()}).strict(),Lx=I.object({...an,type:I.literal("coupon_code"),label:Ve,fallback:Ve}).strict(),zx=I.object({...an,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:Ve,fallback:Ve}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),$x=I.object({...an,type:I.literal("plan_picker"),label:Ve,fallback:Ve,planIds:I.array(I.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.string().min(1).max(200).optional(),grouping:Ua.safeExtend({monthLabel:Ve,yearLabel:Ve,unavailableLabel:Ve}).optional(),states:I.object({selected:Lr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ba(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Gx=I.object({...an,type:I.literal("quantity_picker"),bind:qa.optional(),label:Ve,fallback:Ve,internalFeatureId:I.uuid(),minimumQuantity:Ue(0,1e4),maximumQuantity:Ue(0,1e4),defaultQuantity:Ue(0,1e4),step:Ue(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),Kx=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:Ve,keyboard:I.enum(["text","email","tel","url"]),maxLength:Ue(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:Ve,min:Ue(0,50),max:Ue(1,50)}).strict(),I.object({type:I.literal("select"),label:Ve,defaultIndex:Ue(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:Po.optional(),selectedStyle:Lr.optional()}).strict(),I.object({type:I.literal("tabs"),label:Ve,defaultIndex:Ue(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:Ve,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:Ve}).strict()]),jn={...an,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Ue(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:Kx.optional(),states:I.object({selected:Lr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:Ve.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:qa.optional()},Mm=I.lazy(()=>I.object({...an,type:jn.type,direction:jn.direction,align:jn.align,justify:jn.justify,children:I.array(Hx).max(Tn.children),productSlot:jn.productSlot,interaction:jn.interaction,states:jn.states,purpose:jn.purpose,purchaseAction:jn.purchaseAction,buttonVariant:jn.buttonVariant,bind:jn.bind}).strict()),Hx=I.lazy(()=>I.union([Mm,Nx,Dx,Fx,Mx,Ux,Bx,Vx,Lx,zx,$x,Gx,qx])),Qx=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),Oo={id:Ve,event:Ve,properties:I.record(Ve,Qx).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Jx=I.discriminatedUnion("type",[I.object({...Oo,type:I.literal("navigate"),close:I.literal(!1),pageId:Po}).strict(),I.object({...Oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...Oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...Oo,type:I.literal("open_url"),close:I.boolean(),url:Qc}).strict(),I.object({...Oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),Zx=I.object({defaultLocale:Cn,locales:I.record(Cn,I.record(Ve,I.string().max(Tn.stringLength)))}).strict(),Wx=I.enum(["popup","paywall","onboarding","page","banner"]);var Yx=I.object({kind:I.literal("screen"),schemaVersion:I.literal(wx),name:I.string().trim().min(1).max(80),surface:Wx,initialPageId:Po.optional(),presentation:kn,theme:Nm,pages:I.array(I.object({id:Po,name:I.string().trim().min(1).max(60),root:Mm,theme:Nm.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Tn.pages),strings:Zx,actions:I.array(Jx).max(Tn.actions)}).strict();function Zt(e,t){for(let n of e.pages)tr(n.root,t)}var mn=Yx.superRefine((e,t)=>{let n=Tn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(p=>p.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Tn.locales&&r(`\u6700\u591A ${Tn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Zt(e,(l,p)=>{if(c++,p>Tn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Tn.depth} \u5C42`)});function tr(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)tr(i,t,n+1,e)}function La(e){let t=[],n=new Set;return Zt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Xx(e,t,n){if(t.field==="html"){let r;return Zt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=_o(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function mr(e){let t=La(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!Xx(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function eS(e,t){let n=null;return tr(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function _o(e,t){for(let n of e.pages){let r=eS(n.root,t);if(r)return r}return null}import{z as $t}from"zod";var wt=$t.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Jc=$t.strictObject({type:$t.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:$t.boolean(),enum:$t.array($t.string().max(255)).min(1).max(100).optional()}),wi=Jc.extend({type:$t.enum([...Jc.shape.type.options,"array"]),items:Jc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),Oi=wi.safeExtend({source:$t.discriminatedUnion("type",[$t.strictObject({type:$t.literal("input")}),$t.strictObject({type:$t.literal("node")}),$t.strictObject({type:$t.enum(["parameter","attribute"]),key:wt})])}),q_=$t.record(wt,Oi),Zc=$t.record(wt,wt).refine(e=>Object.keys(e).length<=20);function xn(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>xn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&$t.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Wc(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Wc(e.items,t.items)}function za(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!xn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Pi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function qm(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!xn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as zr}from"zod";var Nn=zr.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Vn=zr.discriminatedUnion("source",[zr.strictObject({source:zr.literal("literal"),value:ve}),zr.strictObject({source:zr.literal("variable"),key:zr.string().min(1).max(255),path:Nn.optional()})]);function Um(e,t){if(!t)return e;for(let n of Nn.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Yc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=za(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(Um(n[e.key],e.path)))}function Xc(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!Nn.safeParse(r).success?null:{key:n,path:r}}function eu(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Zt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(vm))]}function $a(e){return eu(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function fn(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),p=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):p)+Number(u),h=m<=0?2-m+p:m>=p?m:p+1;n+=h+(c.startsWith("-")?1:0)-s.length}}return n}var fr=Ce.enum(["page","popup","banner"]),tS=3e5,Bm=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),nS=Ce.strictObject({inputs:Ce.record(Ve,Bm.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(Ve,Bm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),rS=Ce.strictObject({kind:fr,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:mn,contract:nS}),Ga=rS.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),fn(e)>tS&&n("Content document exceeds its byte budget",[])});function iS(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var oS=Ga.superRefine((e,t)=>{for(let n of $a(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!iS(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}mr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Vm=Ce.strictObject({id:Ce.uuid(),kind:fr,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),e1=Vm.extend({draft:Ga}),t1=Ce.strictObject({rows:Ce.array(Vm).max(200),nextCursor:Ce.uuid().nullable()}),tu=Ce.strictObject({id:Ce.uuid(),kind:fr,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:oS,createdAt:Ce.iso.datetime({offset:!0})}),n1=tu.omit({document:!0}),r1=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:fr,id:Ce.uuid(),document:Ga}),Ce.strictObject({action:Ce.literal("save"),kind:fr,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:Ga}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:fr,id:Ce.uuid(),revision:Ce.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as Lm}from"zod";var Ci={funnelId:Lm.uuid().optional(),funnelVersionId:Lm.uuid().optional()};import{z as Ka}from"zod";var Ha=Ka.strictObject({runId:Ka.uuid(),bindingId:Ka.uuid(),receiptId:Ka.uuid()});import{z as ut}from"zod";import{z as Le}from"zod";import{z as rt}from"zod";var l1=rt.discriminatedUnion("action",[rt.strictObject({action:rt.literal("create"),couponId:rt.uuid(),productBindingId:rt.uuid(),storeOfferId:rt.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:rt.enum(["introductory","promotional"])}),rt.strictObject({action:rt.literal("set_enabled"),id:rt.uuid(),revision:rt.number().int().nonnegative(),enabled:rt.boolean()})]),d1=rt.array(rt.strictObject({id:rt.uuid(),couponId:rt.uuid(),productBindingId:rt.uuid(),storeOfferId:rt.string().min(1).max(255).nullable(),storeOfferType:rt.enum(["introductory","promotional"]),enabled:rt.boolean(),revision:rt.number().int().nonnegative()})).max(500),_i=rt.strictObject({offerKind:rt.enum(["none","introductory","promotional"]),offerId:rt.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:rt.number().int().min(0).max(1e8),trialDays:rt.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),p1=rt.record(rt.uuid(),_i).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var nu=Le.object({type:Le.literal("native_purchase"),receiptId:Le.uuid(),orderId:Le.uuid(),productVersionId:Le.uuid(),provider:Le.enum(["apple","google"]),productId:Le.string().min(1).max(255),productKind:Ud,replacement:Le.strictObject({sourceOrderId:Le.uuid(),sourceProductId:Le.string().min(1).max(255),policy:Le.enum(["apple_store","google_full_price"]),sourceAccountTokens:Le.array(Le.uuid()).max(50)}).nullable(),appAccountToken:Le.uuid().optional(),obfuscatedAccountId:Le.string().min(1).max(64).optional(),obfuscatedProfileId:Le.uuid().optional(),basePlanId:Le.string().min(1).max(255).optional(),offerId:Le.string().min(1).max(255).optional(),offerKind:Le.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Le.number().int().nonnegative().max(1e8),discountMinor:Le.number().int().nonnegative().max(1e8),trialDays:Le.number().int().min(1).max(730).nullable(),seatBundle:Le.array(Le.strictObject({key:Le.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Le.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Le.strictObject({offerId:Le.string().min(1).max(255),keyId:Le.string().min(1).max(255),nonce:Le.uuid(),signature:Le.string().min(1).max(1024),timestamp:Le.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as f}from"zod";import{z as _e}from"zod/v4";import{z as aS}from"zod/v4";var sS=aS.registry(),{BillingInterval:zm}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:cS}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e),{withSpecDefault:uS}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(sS),{COMMON:$m}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:lS}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:dS}=(e=>({COMMON_SET:new Set(e)}))($m),{hasNoDuplicateCurrencies:Gm}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Km}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:pS}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:mS}={Infinite:"inf"},{TierBehavior:fS}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Hm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:hS}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:gS}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:yS}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:AS}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:Qm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e),{VIOLATION_MESSAGES:bS}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:Jm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:xS}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e,Jm),{InvoiceUsageEntrySchema:SS}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e),{AttachDiscountSchema:Zm}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e),{CustomLineItemSchema:IS}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e),{UnixMsTimestampSchema:vS}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:wS}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e),{ReissueInvoiceParamsSchema:Wm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e),{InvoiceModeParamsSchema:$r}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(_e),{InvoiceTemplateSchema:OS}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e),{BasePriceSchema:PS}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e,zm,cS),{CURRENCY_CODES:CS}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))($m,lS,dS),{ApiPriceProcessorsSchema:Ym}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,pS),{AllocatedBillingFieldSchema:_S}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e,hS),{CreditDimensionNameSchema:ES}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,gS,yS),{ApiCreditMatchSchema:Xm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(AS),{findCreditTierViolations:RS}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(bS),{ApiCreditMultiplierSchema:kS}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e,Xm),{ProviderMarkupsSchema:jS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,Jm),{InvoiceFeatureQuantitySchema:ef}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e,Hm,SS),{CreateInvoicePreviewSchema:ru}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e,wS),{SUPPORTED_SET:TS}=(e=>({SUPPORTED_SET:new Set(e)}))(CS),{ApiCreditDimensionBaseSchema:NS}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e,Xm),{refineGraduatedTiers:tf}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(RS),{ApiFeatureMarkupsOverrideSchema:DS}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e,jS,xS),{isValidCurrencyCode:FS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(TS),{ApiCreditDimensionSchema:MS}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e,NS,Qm,tf),{CurrencyCodeSchema:nf}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e,FS),{AdditionalCurrencyTierSchema:qS}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e,nf),{ApiCreditSchemaItemBaseSchema:rf}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e,ES,MS,kS),{ApiFlatCreditSchemaItemSchema:US}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(rf,_e),{AdditionalCurrencyPriceSchema:BS}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e,nf),{AdditionalCurrencyTierArraySchema:VS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,qS,Gm,Km),{ApiGraduatedCreditSchemaItemSchema:LS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(rf,_e,Qm,tf),{AdditionalCurrencyPriceArraySchema:of}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,BS,Gm,Km),{ApiUsageTierWithCurrenciesSchema:zS}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e,mS,VS),{ApiCreditSchemaItemSchema:$S}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,LS,US),{BasePriceParamsSchema:GS}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(PS,uS,_e,of),{PlanItemPriceParamsSchema:KS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e,of,zS,fS,zm,Hm,_S),{ApiFeatureOverrideSchema:HS}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e,$S,DS),{InvoiceBasePriceParamsSchema:af}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(GS,Ym),{InvoiceItemPriceParamsSchema:QS}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(KS,Ym),{InvoiceLicenseQuantitySchema:JS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e,af,ef),{InvoiceCustomizeItemSchema:ZS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e,QS,HS),{InvoiceCustomizeSchema:WS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e,af,ZS),{InvoicePlanParamsSchema:YS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e,WS,ef,JS,Zm),{CreateInvoiceParamsSchema:Ei}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e,YS,IS,Zm,vS);var uf=f.strictObject({requestId:f.uuid(),predecessorOperationId:f.uuid().optional(),invoiceMode:$r.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:_i.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(ya,f.number().int().min(0).max(1e4)).optional(),featureQuantities:f.record(f.uuid(),f.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:f.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Kr=f.strictObject({operationId:f.uuid()}),Bt=f.number().int().min(0).max(1e8),XS=f.strictObject({lineId:f.uuid(),productVersionId:f.uuid(),productName:f.string().min(1).max(80),interval:f.enum(["free","week","month","year","one_time"]),intervalCount:f.number().int().min(1).max(156).optional(),baseAmountMinor:Bt,seats:f.array(f.strictObject({key:ya,quantity:f.number().int().min(0).max(1e4),includedQuantity:f.number().int().min(0).max(1e4),maximumQuantity:f.number().int().min(0).max(1e4),unitAmountMinor:Bt})).max(20),prepaid:f.array(Yp).max(100).optional(),catalogAmountMinor:Bt,trial:Xi.nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Sa({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),lf=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),e0=f.strictObject({id:lf,name:f.string().min(1).max(40),percent_off:f.number().gt(0).max(100).optional(),amount_off:f.number().int().positive().optional(),currency:f.string().regex(/^[a-z]{3}$/).optional(),duration:f.enum(["once","repeating","forever"]),duration_in_months:f.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),t0=f.strictObject({subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.array(f.strictObject({id:f.string(),price_id:f.string(),quantity:f.number().int().nonnegative(),discounts:f.array(f.strictObject({id:f.string(),coupon:f.string(),start:f.number(),end:f.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.number().int().nonnegative(),amountMinor:f.number().int().positive(),periodStartMs:f.number(),periodEndMs:f.number()}),df=f.strictObject({invoiceMode:$r.optional(),append:t0.optional(),provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.enum(["payment","subscription"]),lineItems:f.array(f.strictObject({price:f.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.number().int().min(1).max(1e4),priceId:f.uuid(),productName:f.string().min(1).max(80),amountMinor:f.number().int().min(0).max(1e8),currency:f.string().regex(/^[a-z]{3}$/),interval:f.enum(["week","month","year","one_off"]),intervalCount:f.number().int().min(1).max(52),slot:f.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.strictObject({mode:f.enum(["graduated","volume"]),tiers:f.array(f.strictObject({upTo:f.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.number().int().min(0).max(1e8),flatAmountMinor:f.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.array(f.strictObject({coupon:lf,terms:e0})).max(1),trialPeriodDays:f.number().int().min(1).max(730).nullable(),metadata:f.strictObject({grooveCheckoutId:f.uuid(),grooveCustomerId:f.uuid()}),expiresAt:f.iso.datetime({offset:!0})}),Ri=f.strictObject({operationId:f.uuid(),merchantTerms:pi.optional(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:dr,duration:dn,amountMinor:Bt,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:Bt})).min(1).max(20),expiresAt:f.iso.datetime({offset:!0})}).nullable(),charge:f.strictObject({effectiveAt:f.iso.datetime({offset:!0}),periodEndsAt:f.iso.datetime({offset:!0}),debitMinor:Bt,discountMinor:Bt,taxMinor:Bt,totalMinor:Bt}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google","merchant"]),nativeOffer:_i.optional(),currency:Ie,lines:f.array(XS).min(1).max(20),catalogAmountMinor:Bt,automaticTax:f.boolean(),execution:f.union([df,oa]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ki=f.strictObject({operationId:f.uuid(),orderId:f.uuid(),append:f.boolean().optional(),invoiceMode:f.boolean().optional(),status:f.enum(["pending","complete","cancelled","failed"]),executor:f.enum(["indiana","merchant"]),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:f.union([df,oa]).nullable(),currency:Ie,catalogAmountMinor:Bt,taxMinor:Bt,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:nu.nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),quote:Ri.optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),authority:ga.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Ja=f.strictObject({enabled:f.literal(!0),featureIds:f.array(f.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),pf=f.strictObject({requestId:f.uuid(),invoiceMode:$r.optional(),membershipId:f.uuid(),carryOverBalances:Ja.optional(),carryOverUsages:Ja.optional(),membershipIds:f.array(f.uuid()).min(1).max(20).optional(),prorationBehavior:f.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.enum(["immediate","renewal","store"]),change:f.discriminatedUnion("type",[f.strictObject({type:f.literal("plan"),productVersionId:f.uuid()}),f.strictObject({type:f.literal("seats"),licenseKey:ya,quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("quantity"),internal_feature_id:f.uuid(),quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("cancel")}),f.strictObject({type:f.literal("uncancel")}),f.strictObject({type:f.literal("billing_cycle"),billingCycleAnchor:f.union([f.literal("now"),f.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Qa=f.string().regex(/^price_[A-Za-z0-9]+$/),sf=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),cf=f.strictObject({price:Qa.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),mf=f.strictObject({provider:f.literal("stripe"),invoiceMode:$r.optional(),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.enum(["update","cancel","schedule","release"]),update:f.strictObject({items:f.array(cf).max(20),remove:f.array(Qa).max(20),restoreItems:f.array(f.strictObject({price:Qa,quantity:f.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.number().int().positive().optional(),paymentBehavior:f.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.boolean().optional(),clearCancelAt:f.literal(!0).optional(),billingCycleAnchorNow:f.literal(!0).optional(),metadata:sf}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:Qa,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(cf).min(1).max(20),switchAt:f.number().int().positive(),interval:f.enum(["week","month","year"]),intervalCount:f.number().int().min(1).max(52),resetBillingCycleAnchor:f.literal(!0).optional(),metadata:sf}).nullable(),release:f.strictObject({schedule:f.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Za=f.strictObject({merchantTerms:pi.optional(),carryOverBalances:Ja.optional(),carryOverUsages:Ja.optional(),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),expiresAt:f.iso.datetime({offset:!0}),currency:Ie,creditMinor:Bt,debitMinor:Bt,discountMinor:Bt,taxMinor:Bt,totalMinor:Bt,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:f.union([mf,nr])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"subscription_change",e.currency)),n0=f.strictObject({operationId:f.uuid(),invoiceMode:f.boolean().optional(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.enum(["indiana","merchant"]),execution:f.union([mf,nr]).nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),quote:Za.optional(),authority:ga.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),r0=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.literal("store"),effectiveAt:f.null(),expiresAt:f.iso.datetime({offset:!0}),currency:Ie,creditMinor:f.null(),debitMinor:f.null(),discountMinor:f.null(),taxMinor:f.null(),totalMinor:f.null(),retainedProductVersionIds:f.array(f.uuid()).max(19),store:f.strictObject({provider:f.enum(["apple","google"]),productId:f.string().min(1).max(255),catalogAmountMinor:Bt,policy:f.enum(["apple_store","google_full_price"])})}),i0=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.literal("store"),effectiveAt:f.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.null(),nativePurchase:nu.nullable()}),ff=f.union([Za,r0]),iu=f.union([n0,i0]),ou=dc,Gr=da,hf=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),...Nr.shape}).refine(to,"A partial refund states amountMinor; a full refund refunds the remaining amount"),gf=f.strictObject({provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:ou,currency:f.string().regex(/^[a-z]{3}$/),metadata:f.strictObject({indianaRefundId:f.uuid()}),idempotencyKey:f.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),au=f.strictObject({operationId:f.uuid(),merchantTerms:pi.optional(),invoiceId:f.uuid(),providerInvoiceId:f.string().min(1).max(200),currency:Ie,paidMinor:Gr,refundedMinor:Gr,pendingMinor:Gr,amountMinor:ou,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),revokes:f.strictObject({customerProductIds:f.array(f.uuid()).max(100),subscriptionIds:f.array(f.string().min(1).max(200)).max(20)}),execution:f.union([gf,aa]),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Wa=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().min(1).max(200),status:f.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.enum(["indiana","merchant"]),currency:Ie,amountMinor:ou,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().min(1).max(200).nullable(),quote:au.optional(),execution:f.union([gf,aa]).nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),authority:ga.optional(),failureReason:f.string().min(1).max(200).nullable(),createdAt:f.iso.datetime({offset:!0}),completedAt:f.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),D1=f.strictObject({invoiceId:f.uuid(),currency:Ie,paidMinor:Gr,refundedMinor:Gr,pendingMinor:Gr,refundableMinor:Gr,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(Wa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),F1=f.strictObject({requestId:f.uuid(),...Nr.shape}).refine(to,"A partial refund states amountMinor; a full refund refunds the remaining amount");var yf=ut.strictObject({requestId:ut.uuid(),targets:ut.array(ut.strictObject({membershipId:ut.uuid(),action:ut.enum(["cancel","uncancel"]),timing:ut.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Ya=ut.strictObject({batchId:ut.uuid()}),o0=ut.strictObject({operationId:ut.uuid(),membershipIds:ut.array(ut.uuid()).min(1).max(20),provider:ut.enum(["stripe","apple","google"]),action:ut.enum(["cancel","uncancel"]),timing:ut.enum(["immediate","renewal"]),status:ut.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Za.nullable(),managementUrl:ut.url().nullable(),failureCode:ut.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Eo=ut.strictObject({batchId:ut.uuid(),ready:ut.boolean(),status:ut.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ut.iso.datetime({offset:!0}),acceptedAt:ut.iso.datetime({offset:!0}).nullable(),groups:ut.array(o0).min(1).max(100)});import{z as Te}from"zod";var a0=Te.string().trim().min(1).max(240),su={requestId:Te.uuid(),reason:a0},Xa=Te.discriminatedUnion("action",[Te.strictObject({...su,action:Te.literal("start"),productVersionId:Te.uuid(),entityId:Te.uuid().optional(),days:Te.number().int().min(1).max(730).optional()}),Te.strictObject({...su,action:Te.literal("extend"),membershipId:Te.uuid(),days:Te.number().int().min(1).max(730)}),Te.strictObject({...su,action:Te.literal("end"),membershipId:Te.uuid()})]),Af=Te.strictObject({operationId:Te.uuid()}),bf=Te.iso.datetime({offset:!0}),s0=Te.strictObject({provider:Te.literal("stripe"),executor:Te.enum(["indiana","merchant"]),accountId:Te.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Te.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Te.union([Te.literal("now"),bf]),prorationBehavior:Te.literal("none")}),cu=Te.strictObject({operationId:Te.uuid(),action:Te.enum(["start","extend","end"]),status:Te.enum(["pending","effective"]),managedBy:Te.enum(["indiana","stripe"]),membershipIds:Te.array(Te.uuid()).min(1).max(20),endsAt:bf.nullable(),execution:s0.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),L1=Te.strictObject({groupId:Te.uuid(),productVersionId:Te.uuid(),enabled:Te.boolean()});import{z as et}from"zod";var xf=et.strictObject({requestId:et.uuid(),currency:Ie,makeDefault:et.boolean()}),Sf=et.strictObject({setupId:et.uuid()}),c0=et.strictObject({provider:et.literal("stripe"),executor:et.literal("merchant"),accountId:et.string().regex(/^acct_[A-Za-z0-9]+$/),mode:et.literal("setup"),currency:et.string().regex(/^[a-z]{3}$/),customer:et.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:et.uuid(),metadata:et.strictObject({grooveProjectId:et.uuid(),grooveEnvironmentId:et.uuid(),grooveCustomerId:et.uuid(),groovePaymentSetupId:et.uuid()}),setDefaultPaymentMethod:et.boolean(),expiresAt:et.iso.datetime({offset:!0})}),uu=et.strictObject({id:et.uuid(),provider:et.literal("stripe"),status:et.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:et.boolean(),url:et.url().nullable(),createdAt:et.iso.datetime({offset:!0}),expiresAt:et.iso.datetime({offset:!0}),completedAt:et.iso.datetime({offset:!0}).nullable(),execution:c0.nullable()});import{z as Vt}from"zod";var If=Vt.union([Vt.string(),Vt.number(),Vt.boolean(),Vt.null()]),vf=Vt.strictObject({customerId:Vt.uuid()}),wf=Vt.strictObject({customerId:Vt.uuid(),provider:Vt.literal("stripe"),checkedAt:Vt.iso.datetime({offset:!0}),status:Vt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Vt.number().int().nonnegative(),differences:Vt.array(Vt.strictObject({subscriptionId:Vt.string().startsWith("sub_"),itemId:Vt.string().nullable(),field:Vt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:If,actual:If})).max(1e4)});import{z as we}from"zod";var es=we.iso.datetime({offset:!0}),ts=we.strictObject({createdAt:es,id:we.uuid()}),ns=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:ts.optional(),limit:we.number().int().min(1).max(100).optional()}),lu={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:es},u0=we.strictObject({...lu,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),l0=we.strictObject({...lu,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),d0=we.strictObject({...lu,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:es,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:es.nullable()}),Of=ns.extend({status:we.enum(["blocked","resolved"]).optional()}),Pf=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Cf=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),_f=we.strictObject({items:we.array(u0).max(100),nextCursor:ts.nullable()}),Ef=we.strictObject({items:we.array(l0).max(100),nextCursor:ts.nullable()}),Rf=we.strictObject({items:we.array(d0).max(100),nextCursor:ts.nullable()});import{z as ot}from"zod";var kf=ot.union([ot.strictObject({intent:ot.literal("read"),requestId:ot.uuid(),purchaseIntentId:ot.uuid()}),ot.strictObject({requestId:ot.uuid(),provider:ot.literal("apple"),purchaseIntentId:ot.uuid(),productId:ot.string().min(1).max(255).optional(),signedTransaction:ot.string().min(1).max(131072)}),ot.strictObject({requestId:ot.uuid(),provider:ot.literal("google"),purchaseIntentId:ot.uuid(),productId:ot.string().min(1).max(255).optional(),purchaseToken:ot.string().min(1).max(16384)})]),jf=ot.strictObject({requestId:ot.uuid(),orderId:ot.uuid(),purchaseIntentId:ot.uuid(),status:ot.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:ot.boolean(),completion:ot.strictObject({transactionIds:ot.array(ot.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:ot.boolean()}).nullable()});import{z as L}from"zod";var pu=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),p0=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),m0=3,Ro=20,f0=m0*Ro,du=L.strictObject({type:L.literal("product"),productId:pu}),Tf={type:L.literal("group"),key:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.string().trim().min(1).max(80)},h0=L.discriminatedUnion("type",[du,L.strictObject({...Tf,items:L.array(du).max(Ro)})]),g0=L.discriminatedUnion("type",[du,L.strictObject({...Tf,items:L.array(h0).max(Ro)})]),y0=L.array(g0).max(Ro).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>Ro||i>f0)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function mu(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:mu(t))}var ji=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:y0,metadata:p0}),A0=L.strictObject({product:L.record(L.string(),L.json()),prices:L.array(L.record(L.string(),L.json())),entitlements:L.array(L.record(L.string(),L.json())),freeTrials:L.array(L.record(L.string(),L.json())),licenses:L.array(L.record(L.string(),L.json()))}),Nf=ji.extend({id:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),state:L.enum(["active","archived"]),isCurrent:L.boolean(),revision:L.number().int().nonnegative(),publishedVersionId:L.uuid().nullable(),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Df=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:ji,productEvidence:L.record(pu,A0),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=mu(e.document);(!n.length||S0(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),b0=L.strictObject({rows:L.array(Nf).max(200),versions:L.array(Df).max(500)}),nE=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:ji}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:ji}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),rE=L.strictObject({record:Nf,version:Df.nullable()}),Ff=L.discriminatedUnion("type",[L.strictObject({type:L.literal("current")}),L.strictObject({type:L.literal("id"),id:L.uuid()}),L.strictObject({type:L.literal("lookup_key"),lookupKey:L.string().min(1).max(200)}),L.strictObject({type:L.literal("version"),versionId:L.uuid()})]),x0=L.strictObject({internalId:pu,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),iE=b0.extend({products:L.array(x0).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function S0(e){let t=[];mu(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as rs}from"zod";var Mf=rs.strictObject({id:rs.uuid(),offeringId:rs.uuid(),version:rs.number().int().positive(),document:ji});import{z as Et}from"zod";import{z as Ae}from"zod";import{z as Ti}from"zod";var is=Ti.strictObject({items:Ti.array(Ti.strictObject({productVersionId:Ti.string().min(1).max(200),label:Ti.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Ti.string().min(1).max(200).nullable(),grouping:Ua.optional()});function qf(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var fu=Ae.discriminatedUnion("type",[Ae.strictObject({type:Ae.literal("event"),event:Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),Ae.strictObject({type:Ae.literal("open_url"),url:Ae.url().refine(e=>new URL(e).protocol==="https:")})]),I0=mn,v0=Ae.discriminatedUnion("type",[Ae.object({type:Ae.literal("checkout"),product:Va}).strict(),Ae.object({type:Ae.literal("close")}).strict(),Ae.object({type:Ae.literal("action"),action:fu}).strict()]),Ni=Ae.object({schemaVersion:Ae.literal(3),kind:Ae.literal("paywall"),name:Ae.string().trim().min(1).max(80),presentation:kn,requirement:Pn.optional(),products:is,offeringVersionId:Ae.uuid().nullable(),offeringId:Ae.uuid(),screen:I0,buttons:Ae.record(Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),v0)}).strict(),bE=Ni.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of O0(e))t.addIssue({code:"custom",message:r});for(let r of w0(e))t.addIssue({code:"custom",message:r});mr(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function w0(e){let t=e.products.items.map(a=>a.productVersionId),n=wm(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!Ba(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Zt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Zt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function O0(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),tr(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let p=e.buttons[u];s.id!==n.id&&p&&p.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Uf=Ae.object({id:Ae.uuid(),projectId:Ae.uuid(),environmentId:Ae.uuid(),revision:Ae.number().int().nonnegative(),state:Ae.enum(["active","archived"]),publishedVersionId:Ae.uuid().nullable(),updatedAt:Ae.iso.datetime({offset:!0}),draft:Ni}).strict(),xE=Ae.object({rows:Ae.array(Uf).max(200),nextCursor:Ae.uuid().nullable()}).strict(),SE=Uf.omit({draft:!0}).extend({name:Ae.string(),productCount:Ae.number().int().nonnegative()}).strict(),IE=Ae.discriminatedUnion("action",[Ae.object({action:Ae.literal("save"),id:Ae.uuid().nullable(),revision:Ae.number().int().nonnegative(),document:Ni}).strict(),Ae.object({action:Ae.enum(["publish","archive"]),id:Ae.uuid(),revision:Ae.number().int().nonnegative()}).strict()]),vE=Ae.object({paywalls:Ae.array(Ae.object({id:Ae.uuid(),paywallId:Ae.uuid(),version:Ae.number().int().positive(),name:Ae.string().min(1).max(80),presentation:kn,buttons:Ni.shape.buttons}).strict()).max(500),limited:Ae.boolean()}).strict();import{z as Re}from"zod";import{z as Wt}from"zod";var Di=Wt.string().regex(/^[a-f0-9]{64}$/),P0=Ma.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Bf=Wt.strictObject({couponDigests:Wt.record(Wt.uuid(),Di),variables:Wt.record(Cn,Wt.record(Wt.uuid(),Wt.partialRecord(Wt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Wt.string()))),locales:Wt.record(Cn,Ii.extend({nodes:Wt.record(Wt.string(),Wt.strictObject({base:P0})),plans:Wt.object({}).strict(),pickers:Wt.object({}).strict()}).omit({paywall:!0}))});import{z as ze}from"zod";import{z as os}from"zod";var hu=os.strictObject({eventsEnabled:os.boolean(),experimentViewsEnabled:os.boolean(),featureUsageEnabled:os.boolean()}),RE=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Vf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var gu=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),C0=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(gu).max(100)}),_0=$.strictObject({id:$.string().min(1).max(255),condition:nn,gate:$.boolean().optional()}),E0=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),Lf={condition:nn.optional(),parentConditions:$.array(_0).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(C0).max(100).optional(),ranges:$.array(gu).max(20).optional(),meta:$.array(E0).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},Fi=$.strictObject({...Lf,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),yu=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),R0=$.strictObject({...Lf,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:gu.optional(),tracks:$.array($.strictObject({experiment:Fi,result:yu})).max(100).optional()}),k0=$.strictObject({defaultValue:ve.optional(),rules:$.array(R0).max(500).optional()}),ko=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:nn})])),Sn=$.strictObject({scope:De,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),k0),savedGroups:ko,experiments:$.record($.uuid(),Fi)});var jo=Sn.extend({analyticsConfig:hu,remoteFeatures:ze.array(ze.string().min(1).max(255)).max(500)}),Au=jo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),zf=ze.strictObject({attributes:Pt,features:ze.array(ze.string().min(1).max(255)).max(500).optional(),customerId:ze.uuid().optional()}),j0=ze.strictObject({value:ve,source:ze.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ze.boolean(),off:ze.boolean(),ruleId:ze.string(),experimentResult:yu.optional()}),as=ze.strictObject({generation:Sn.shape.generation,evaluatedAt:Sn.shape.evaluatedAt,expiresAt:Sn.shape.expiresAt,features:ze.record(ze.string(),j0),merchandiseContext:ze.strictObject({merchandiseId:ze.uuid(),merchandise:Pt}).optional()}),$f=ze.strictObject({customerId:ze.uuid().optional(),events:ze.array(ze.strictObject({eventUuid:ze.uuid(),timestamp:ze.iso.datetime({offset:!0}),name:ze.string().min(1).max(255),merchandise:Cp.optional(),properties:ze.record(ze.string(),ve).default({}),deviceId:ze.string().min(1).max(255).optional(),sessionId:ze.string().min(1).max(255).optional()})).min(1).max(100)}),Gf=ze.strictObject({inserted:ze.number().int().nonnegative(),duplicates:ze.number().int().nonnegative(),rejected:ze.number().int().nonnegative(),skipped:ze.number().int().nonnegative(),analyticsConfig:hu});import{z}from"zod";import{z as T0}from"zod";var Kf=T0.enum(["funnel-run/1","funnel-process/1"]),Hf="funnel-process/1";function bu(e,t=[]){let n=[];Zt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(La(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function Qf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Qf(t)??[])}}function N0(e){let t=e.pages.map(i=>{let a=Qf(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(La({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Jf(e,t=[]){let n=mn.parse(structuredClone(N0(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=bu(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as ht}from"zod";var ss=ht.strictObject({schemaVersion:ht.literal(1),renderKey:ht.string().min(1).max(256),routeTemplate:ht.string().startsWith("/").max(2048),selectors:ht.array(ht.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ht.array(ht.number().int().min(0)).min(1),absent:ht.array(ht.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Zf=ht.strictObject({renderKey:ht.string().min(1).max(256),routeKey:ht.string().min(1).max(256),stateKey:ht.string().min(1).max(256),documentKey:ht.string().min(1).max(256),documentHash:ht.string().regex(/^[a-f0-9]{64}$/),compositionKey:ht.string().min(1).max(256),entryMode:ht.enum(["hard","soft"]),match:ht.strictObject({present:ht.array(ht.number().int().min(0)),absent:ht.array(ht.number().int().min(0))})});import{z as Hr}from"zod";var D0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],xu="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",F0=Hr.string().regex(new RegExp(`^${xu}/${xu}/${xu}/manifest\\.json$`)),Wf=Hr.strictObject({kind:Hr.literal("gcs-resumable"),url:Hr.url(),bucket:Hr.enum(D0),objectKey:F0,byteLength:Hr.number().int().positive(),expiresAt:Hr.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var bt=M.string().min(1).max(256),hn=M.string().regex(/^[a-f0-9]{64}$/),cs=M.strictObject({versionId:M.uuid(),manifestDigest:hn,sourceGraphDigest:hn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:hn,elementKey:bt.optional(),nodeId:bt.optional(),contentHash:hn.optional(),renderKey:bt.optional()}),Yf=M.strictObject({pageKey:bt,documentKey:bt,expectedDocumentHash:hn,renderKey:bt.optional(),nodeId:bt,elementKey:bt,expectedContentHash:hn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),Xf=M.strictObject({versionId:M.uuid(),manifestDigest:hn,sourceGraphDigest:hn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:hn,renderKey:bt.optional(),patches:M.array(Yf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),M0=/^[a-z][a-z0-9-]{0,39}$/,To=M.string().regex(M0),Iu=M.enum(["web","ios","android"]),XE=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:To,platform:Iu,label:M.string().trim().min(1).max(100),sha256:hn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:bt,changesetId:M.uuid().nullable(),expectedRevision:hn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(Yf).max(200)})]),vu=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:To,platform:Iu,label:M.string(),sha256:hn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),q0=M.strictObject({key:To,platform:Iu,currentId:M.uuid().nullable()}),eR=M.strictObject({rows:M.array(vu).max(100),nextCursor:M.uuid().nullable(),clients:M.array(q0).max(20)}),Su=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),tR=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Su,runtime:Su,previews:Su})}),nR=M.strictObject({version:vu,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),rR=M.strictObject({version:vu,upload:Wf.nullable()}),iR=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:bt,path:M.string(),documentKey:bt,documentHash:hn,initialStateKey:bt,initialRenderKey:bt})),renders:M.array(Zf)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),oR=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:bt,key:bt,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),aR=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Mi}from"zod";var eh=Mi.strictObject({id:Mi.uuid(),name:Mi.string().trim().min(1).max(80),client:To,source:cs,event:Mi.enum(["screen_enter","button_click"]),cooldownSeconds:Mi.number().int().min(0).max(2592e3),behavior:Mi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Je}from"zod";var wu=ve,U0=["parameters","answers","results","variables"];function Ou(e){return U0.some(t=>e===t||e.startsWith(t+"."))}function Pu(e){let t={};for(let[r,i]of Object.entries(za(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Ou(r))),variables:t}}import{z as xt}from"zod";var us=xt.discriminatedUnion("kind",[xt.object({kind:xt.literal("ledger"),cursor:Fa}).strict(),xt.object({kind:xt.literal("billing"),cursor:xt.uuid()}).strict()]),B0=xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),hr=xt.record(xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xt.union([xt.string().max(500),xt.boolean(),xt.array(xt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),V0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Cu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Cu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||V0.test(n)||Cu(r,t+1)))}var L0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,gr=xt.record(B0,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Cu(e)&&!L0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var th=xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ls=xt.array(xt.object({variable:th,componentId:th,required:xt.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),AR=xt.object({bindings:ls,answers:hr,values:xt.record(xt.string(),ve).optional()}).strict();import{z as z0}from"zod";var ds=z0.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var _u=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nh=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),rh=gr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Eu=Je.record(_u,Je.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),$0=Vn,ih=Je.strictObject({type:Je.literal("external_task"),endpointId:Je.uuid(),taskKey:_u,inputs:Je.record(_u,$0).refine(e=>Object.keys(e).length<=20),outputs:Eu}),oh=Je.strictObject({maxAttempts:Je.number().int().min(1).max(5),retryDelaySeconds:Je.number().int().min(1).max(30),backoff:Je.enum(["fixed","exponential"]),requestTimeoutSeconds:Je.number().int().min(1).max(10),timeoutSeconds:Je.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var _R=Je.strictObject({outcome:Je.enum(["success","failure"]),data:rh});var ER=Je.discriminatedUnion("operation",[Je.strictObject({operation:Je.literal("signal"),runId:Je.uuid(),nodeId:nh,eventName:ds,eventId:Je.uuid(),data:rh}),Je.strictObject({operation:Je.literal("read_results"),runId:Je.uuid()})]),RR=Je.strictObject({scope:De,runId:Je.uuid(),eventId:Je.uuid(),accepted:Je.boolean()}),G0=Je.record(nh,wu),kR=Je.strictObject({scope:De,runId:Je.uuid(),results:G0});var Dn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},ah="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as tt}from"zod";var MR=tt.enum(["local","remote"]),Ru=tt.strictObject({port:tt.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:tt.array(tt.strictObject({expected:uo.nullable(),next:uo})).max(100),exposures:tt.array(ve).max(100),features:tt.array(ve).max(100)}),sh=tt.strictObject({type:tt.literal("evaluate"),receiptId:tt.uuid(),environmentId:tt.uuid(),policyRevision:tt.number().int().nonnegative(),attributes:Pt,sticky:tt.record(tt.string(),uo)}),ch=sh.extend({runId:tt.uuid(),versionId:tt.uuid(),nodeId:tt.string().min(1).max(64),visit:tt.number().int().nonnegative(),revision:tt.number().int().nonnegative()}),ku=sh.omit({type:!0,receiptId:!0}).extend({type:tt.literal("evaluate_segment")}),uh=tt.strictObject({nodeId:tt.string().min(1).max(64),result:Ru}),lh=ku.extend({runId:tt.uuid(),versionId:tt.uuid(),nodeId:tt.string().min(1).max(64),visit:tt.number().int().nonnegative(),revision:tt.number().int().nonnegative(),parameters:gr,answers:hr,variables:tt.record(tt.string(),ve)});import{z as ue}from"zod";var ju=ue.array(ue.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),ps=ue.intersection(Pt,ue.looseObject({tags:ju.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ms=ue.string().trim().max(80),fs=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),hs=ue.union([ue.email().max(254),ue.literal("")]),gs=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dh=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),ph=ue.object({externalUserId:dh.optional(),name:ms.default(""),email:hs.default(""),phone:fs.optional(),attributes:ps.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Qr=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:dh})]),qi=ue.strictObject({name:ms.optional(),email:hs.optional(),phone:fs.optional(),attributes:ps.optional(),fingerprint:gs.optional()}),ys=e=>!e.customerData||e.customer?.type==="externalUserId",As="customerData requires an externalUserId customer",Ui=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:ms,email:hs,phone:fs.optional(),attributes:ps,createdAt:ue.iso.datetime()}).strict(),mh=ue.object({customer:Ui,changed:ue.boolean(),replayed:ue.boolean()}).strict(),K0=ue.discriminatedUnion("type",[ue.object({type:ue.literal("id"),value:ue.uuid()}).strict(),ue.object({type:ue.literal("externalUserId"),value:ue.string().trim().min(1).max(255)}).strict()]),H0=ue.object({name:ms.optional(),email:hs.optional(),phone:fs.optional(),attributes:ps.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.array(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.strictObject({add:ju,remove:ju}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Tu=ue.object({lookup:K0}).strict(),fh=Tu.extend({requestId:ue.uuid(),patch:H0}).strict(),hh=ue.object({search:ue.string().trim().max(200).default(""),tag:ue.string().trim().max(40).default(""),planId:ue.string().max(200).default(""),versionId:ue.string().max(200).default(""),holdingStatus:ue.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),createdUntil:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),offset:ue.coerce.number().int().min(0).max(1e5).default(0),limit:ue.coerce.number().int().min(1).max(100).default(50)}).strict(),gh=ue.object({customers:Ui.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var No=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:wt,path:Nn.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),Q0=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),J0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:Qr,customerData:qi.optional(),attributes:Pt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},JR=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...J0}).refine(ys,As),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:Ru}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(uh).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),ZR=Z.strictObject({scope:De,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:Q0.nullable(),evaluation:Z.discriminatedUnion("type",[ch,lh]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),WR=Z.strictObject({scope:De,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Lt}from"zod";var yh=Lt.strictObject({type:Lt.literal("bundle"),paywall:Vn.optional(),offering:Vn.optional(),coupons:Vn,data:Vn}),Z0=e=>Lt.strictObject({type:Lt.literal(e),id:Lt.uuid()}),rk=Lt.strictObject({type:Lt.literal("bundle"),paywallVersionId:Lt.uuid().optional(),offeringVersionId:Lt.uuid().optional(),couponIds:Lt.array(Lt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var ik=Lt.strictObject({type:Lt.literal("bundle"),offering:Z0("offering_version").nullable(),paywall:Lt.strictObject({versionId:Lt.uuid(),paywallId:Lt.uuid(),offeringVersionId:Lt.uuid()}).nullable(),coupons:Lt.array(lo).max(20),data:ve});import{z as Fn}from"zod";import{z as In}from"zod";var Ah=In.union([In.string(),In.number().finite(),In.boolean(),In.null()]),W0=In.union([Ah,In.array(Ah).min(1).max(20)]),Y0=In.record(Nn,W0).refine(e=>Object.keys(e).length<=10),bh=In.strictObject({path:Nn,type:In.enum(["string","number","boolean","strings"]),nullable:In.boolean().optional(),aggregation:In.enum(["count","exists"]).optional(),where:Y0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var X0=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],xh=Fn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),eI=Vn,Sh=Fn.discriminatedUnion("type",[ih,Fn.strictObject({type:Fn.literal("claim_offer"),coupon:Vn}),Fn.strictObject({type:Fn.literal("event"),event:xh}),Fn.strictObject({type:Fn.literal("api"),operation:Fn.enum(X0),inputs:Fn.record(Nn,eI).refine(e=>Object.keys(e).length<=40),outputs:Fn.record(xh,bh).refine(e=>Object.keys(e).length<=20)})]);var dt=ds,tI=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),gn={id:dt,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},nI={success:dt,cancel:dt,unavailable:dt,failure:dt},Nu=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Du=Q.enum(["same_window","new_window"]),rI=Q.discriminatedUnion("type",[Q.strictObject({...gn,type:Q.literal("entry"),next:dt,triggers:Q.array(eh).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...gn,type:Q.literal("screen"),screenId:dt,presentation:kn,outputs:Q.record(dt,dt),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:wt}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...gn,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...No.options,yh,Q.strictObject({type:Q.literal("selection"),screenId:dt,offeringKey:wt})])}),Q.strictObject({...gn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:nn,target:dt})).min(1).max(50),default:dt}),Q.strictObject({...gn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(tI,dt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:dt}),Q.strictObject({...gn,type:Q.literal("action"),...nI,execution:oh,action:Sh,writes:Zc.optional()}),Q.strictObject({...gn,type:Q.literal("external_page"),appManifest:cs.optional(),url:Nu,openIn:Du,opened:dt,failed:dt}),Q.strictObject({...gn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:No.optional()}),Q.strictObject({...gn,type:Q.literal("wait"),writes:Zc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:dt}),Q.strictObject({type:Q.literal("event"),eventName:dt,outputs:Eu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:dt,timeout:dt})])})]),Fu=Q.strictObject({version:Q.literal(5),entry:dt,nodes:Q.array(rI).min(1).max(Dn.flowNodes)}),Mu=Fu.superRefine((e,t)=>{iI(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function bs(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function iI(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,p,m)=>{n.push(l),t?.({message:l,reason:p,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>Dn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Dn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let p of bs(l))p===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(p)||i(`Missing target ${p}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let p of bs(r.get(l)))u(p);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var qu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Ih(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of lr(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as q}from"zod";var Bi=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),xs=e=>q.record(q.string(),ve).refine(t=>fn(t)<=e,"Funnel evidence exceeds its byte budget"),Dk=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Bu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Vu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),Do=q.strictObject({schemaVersion:q.literal(1),kind:Bu,selector:Vu.nullable(),context:xs(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>fn(e)<=131072,"Node input exceeds its byte budget"),vh=q.strictObject({schemaVersion:q.literal(1),kind:Bu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:xs(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:xs(131072)}).refine(e=>fn(e)<=131072,"Node result exceeds its byte budget"),Fk=q.strictObject({schemaVersion:q.literal(1),operations:q.record(Bi,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:Bi,id:q.uuid()}).nullable()}))}).refine(e=>fn(e)<=65536,"Execution state exceeds its byte budget"),Jr={receiptId:q.uuid()},Uu=q.iso.datetime({offset:!0}),Mk=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:Bu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Jr,source:q.literal("client"),occurredAt:Uu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:Bi,eventName:Bi,data:xs(8192),source:q.literal("server"),occurredAt:Uu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Jr,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Jr,operation:Bi,reference:q.strictObject({type:Bi,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Jr,source:q.enum(["client","server"]),occurredAt:Uu,reference:q.string().min(1).max(128).optional()})})]);var vn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oI=z.discriminatedUnion("type",[z.strictObject({id:vn,type:z.literal("owned"),publicData:Bf.optional(),document:mn.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),z.strictObject({id:vn,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),Lu={executionContract:Kf.optional(),kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(oI).max(Dn.pages),references:z.record(vn,Vu).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:vn,screenId:vn,componentId:vn,required:z.boolean()})).max(Dn.questions),variables:z.record(wt,Oi).refine(e=>Object.keys(e).length<=Dn.logicNodes),outputSchema:wi,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(qu.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(qu.maxTransitions)})},rj=z.strictObject({...Lu,graph:Fu});function aI(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function Is(e){return Array.isArray(e)?e.some(Is):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===ah:Is(n))}function sI(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=Jf(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!_o(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),aI(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&Is(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Is(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function wh(e,t){for(let{message:n,reason:r,path:i}of sI(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Oh(e,t){let n=(h,d,g=[])=>t.addIssue({code:"custom",message:h,path:g,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(h=>[h.id,h])),a=(h,d)=>r.some(g=>g.type===h&&("id"in g?g.id:g.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(h=>h.type==="screen");(o.length!==i.size||o.some(h=>!i.has(h.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(h=>c.some(d=>h!==d&&d.startsWith(h+".")))&&n("Variable paths must not overlap","variable");function u(h,d){Object.hasOwn(e.variables,h)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let g=s.get(h)??new Set;g.add(d.id),s.set(h,g)}for(let[h,d]of e.graph.nodes.entries()){let g=["graph","nodes",h],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",g);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,C]of Object.entries(A)){u(C,d);let j=e.variables[C],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",g)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let C of d.couponIds)a("reward",C)||n("Coupons require Reward references","coupon",g)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let C=v.document.pages[0];if(!C){n("Owned screen requires a page","screen",g);continue}mr(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",g);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),tr(C.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",g),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",g),d.type==="end"&&d.output?.type==="literal"&&!xn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",g),d.type==="output"&&d.value.type==="literal"&&!xn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",g);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!Wc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let C of eu(v.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!Xc(C.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(d.type==="condition")for(let v of d.cases){for(let C of Yn(v.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let C of lr(v.condition))C.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,C]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!xn({type:C,nullable:!1},X)||!a(C,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==C))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[h,d]of e.graph.nodes.entries()){let g=d.type==="screen"?i.get(d.screenId):void 0,R=[...Ih(d,c),...g?.type==="owned"?$a(g.document).map(y=>Xc(y,c)?.key??y):[]];for(let y of new Set(R)){let C=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:bs(_)).some(C):!1};var m=C;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",h]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||C(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",h])}}(new Set(e.inputs.map(h=>h.variable)).size!==e.inputs.length||new Set(e.inputs.map(h=>`${h.screenId}:${h.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[h,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",h]);let g=i.get(d.screenId),R=g?.type==="owned"?_o(g.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",h]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",h]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",h])}}for(let[h,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",h]),d.source.type==="input"&&!e.inputs.some(g=>g.variable===h)&&n("Input variable requires a component binding","inputBinding",["variables",h]);let l=0,p=0;for(let h of e.screens)if(h.type==="owned"){for(let d of h.document.pages)tr(d.root,()=>{l++});p+=h.document.actions.length}(l>Dn.components||p>Dn.actions||fn(e)>Dn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var cI=z.strictObject({...Lu,graph:Mu}).superRefine(Oh),Vi=z.strictObject({...Lu,graph:Mu,displayName:z.string().trim().min(1).max(80)}).superRefine(Oh),ij=Vi.superRefine(wh),oj=cI.superRefine(wh),Ss=z.string().regex(Ft),Fo={requestId:z.uuid(),nodeId:vn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ss.optional()},uI=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:vn,answers:hr,selection:z.record(vn,z.union([z.string().max(200),z.boolean(),z.number().int().min(0).max(1e4)])).optional()}),z.strictObject({type:z.literal("paywall_quote"),featureQuantities:z.record(z.uuid(),z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:vn,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:_i.optional(),predecessor:z.strictObject({operationId:z.uuid().nullable(),generation:z.number().int().positive()}).optional()}),z.strictObject({type:z.literal("paywall_confirm"),operationId:z.uuid()}),z.strictObject({type:z.literal("paywall_cancel"),operationId:z.uuid()}),z.strictObject({type:z.literal("client_action"),receiptId:z.uuid(),outcome:z.enum(["success","cancel","failure","opened","failed"])})]),lI=z.object({nodeId:vn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(vn,z.object({resourceKey:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.number().int().min(1).max(1e5),after:us.nullable(),filter:z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ct=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:Qr.optional(),customerData:qi.optional(),locale:z.string().min(1).max(35),parameters:gr}).refine(ys,As),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:lI.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Ss.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Ss.optional()}),z.strictObject({operation:z.literal("submit"),...Fo,input:uI}),z.strictObject({operation:z.literal("back"),...Fo}),z.strictObject({operation:z.literal("shown"),...Fo}),z.strictObject({operation:z.literal("close"),...Fo}),z.strictObject({operation:z.literal("commit_segment"),...Fo,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Ss.optional()})]);function vs(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let g of Yn(d))l(g)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let g=t.savedGroups[d];g&&(i.add(d),c.set(d,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function p(d){for(let g of["hashAttribute","fallbackAttribute"])if(d[g]!==void 0&&Ou(d[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(d.condition);for(let g of d.parentConditions??[])m(g.id),u(g.condition)}function m(d,g=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){p(y);for(let A of y.tracks??[])p(A.experiment)}}))}function h(d){let g=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,g),a.push(()=>p(g)))}for(let d of e.graph.nodes){d.type==="feature"&&m(d.featureKey,!0),d.type==="split"&&h(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&m(d.configuration.featureKey,!0);let g=d.type==="output"?d.value:d.type==="end"?d.output:null;g?.type==="feature"&&m(g.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Ph(e,t){let n=[],r={};Zt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Zt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Ch(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Zt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as Mo}from"zod";var _h=Mo.object({defaultLocale:Cn,locales:Mo.record(Cn,Mo.object({name:Mo.string().max(80),description:Mo.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var dI=["customer_data","coupon_code"],Eh=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),pI=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ws=(e,t)=>new Set(e.map(t)).size===e.length,mI=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),fI=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),hI=ae.strictObject({stripe:ae.strictObject({prices:ae.array(mI).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Eh).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Eh,basePlanId:pI.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ws(e.stripe.prices,n=>n.currency)||e.apple&&!ws(e.apple.productIds,n=>n)||e.google&&!ws(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),gI=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(fI).max(50).refine(e=>ws(e,t=>t.featureId),"Duplicate benefit"),channels:hI,prepaid:ae.array(wo).max(100).optional()}),yI=ae.strictObject({digest:Di,content:ae.strictObject({discount:dr,duration:dn,appliesTo:Nc,displayCopy:_h.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),AI=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:Va}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:fu})]),Os=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:kn,screen:mn,products:is,catalog:ae.record(ae.uuid(),gI),buttons:ae.record(Ve,AI),coupons:ae.record(ae.uuid(),yI)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Ph(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),bu(r,dI).forEach(n),mr(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Zt(r,g=>{let R="bind"in g?g.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(y=>i.add(y)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(R=>R.featureId)));for(let g of o)l.has(g)||n("Feature text must read a displayed benefit");let p=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==p.length||p.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let h=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;h=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}h||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Rh=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var sn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},zu=Re.string().regex(/^[a-f0-9]{64}$/),$u=Re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Ku=De.extend({environmentId:Re.uuid()}),kh=Re.strictObject({features:Re.array(Re.string()).max(500),experiments:Re.record(Re.uuid(),Re.array(Re.string()).max(20)),savedGroups:Re.array(Re.string()).max(1e3)}),Hu=Re.strictObject({kind:Re.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.number().int().positive(),url:Re.string().min(1).max(2048),sha256:zu,byteLength:Re.number().int().positive().max(sn.maxArtifactBytes),generation:zu.optional()}),bI=Re.strictObject({state:Re.enum(["active","paused","archived"]),controlRevision:$u,evaluationMode:Re.enum(["local","remote"]),evaluationRevision:$u,currentVersionId:Re.uuid(),versions:Re.record(Re.uuid(),Re.strictObject({artifact:Re.string(),dependencies:kh,definitionDigest:Di.optional(),couponDigests:Re.record(Re.uuid(),Di).optional()}))}),Qu=Re.strictObject({kind:Re.literal("sdk_configuration"),schemaVersion:Re.literal(1),scope:Ku,revision:$u,generation:zu,policy:Re.strictObject({refreshIntervalSeconds:Re.number().positive().max(15),maxControlAgeSeconds:Re.number().positive().max(60)}),gb:Re.strictObject({features:Re.string().nullable(),pageExperiments:Re.string().nullable()}),artifacts:Re.record(Re.string(),Hu),funnels:Re.record(Re.uuid(),bI),paywalls:Re.record(Re.uuid(),Rh).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function _t(e){if(Array.isArray(e))return`[${e.map(_t).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${_t(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Ju(e){return rr(or(typeof e=="string"?new TextEncoder().encode(e):e))}function jh(e){return Ju(_t(e))}var Gu=class extends Error{constructor(n,r){super(n);Be(this,"dependency",r)}};function Th(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,p)=>e.graph.nodes.find(m=>l==="experiment"?m.type==="split"&&m.experimentId===p:l==="feature"&&n(m)===p)?.name,i=(l,p,m=r(p.type,p.resource))=>new Gu(l,{...p,...m?{step:m}:{}});for(let l of Object.values(e.references)){let p=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(p)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...p})}let a=vs(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let p=n(l);if(!p)continue;let m=a.features[p],h=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:p};if(!m||!h)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([m.defaultValue,...(m.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!xn(h,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,p)=>{for(let m of Yn(l)){if(s.has(m))continue;let h=t.savedGroups[m];if(!h)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:m},p);s.add(m),!Array.isArray(h)&&h.type==="condition"&&c(h.condition,p)}},u=(l,p)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},p)};for(let l of e.graph.nodes)if(l.type==="condition")for(let p of l.cases)c(p.condition,l.name);for(let[l,p]of Object.entries(a.features)){let m=r("feature",l);for(let h of p.rules??[]){c(h.condition,m);for(let d of[...h.parentConditions??[],...(h.tracks??[]).flatMap(g=>g.experiment.parentConditions??[])])u(d.id,m),c(d.condition,m);for(let d of h.tracks??[])c(d.experiment.condition,m)}}for(let[l,p]of Object.entries(a.experiments)){let m=r("experiment",l);c(p.condition,m);for(let h of p.parentConditions??[])u(h.id,m),c(h.condition,m)}for(let l of e.graph.nodes)if(l.type==="split"){let p=a.experiments[l.experimentId],m={type:"experiment",resource:l.experimentId};if(!p)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...m},l.name);for(let h of p.variations)if(typeof h!="string"||!Object.hasOwn(l.routes,h))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...m},l.name)}return kh.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,p])=>[l,p.variations.map(String)])),savedGroups:[...s].sort()})}function Nh(e){return Vi.parse(e)}var Dh=Et.strictObject({processContext:Ha.optional(),...Ci,selector:Et.discriminatedUnion("type",[Et.strictObject({type:Et.literal("paywall"),paywallId:Et.uuid()}),Et.strictObject({type:Et.literal("version"),versionId:Et.uuid()})]),customerId:Et.uuid().optional(),commerce:fi,locale:Et.string().min(1).max(35),requirement:Pn.optional()}),qo=Et.strictObject({id:Et.uuid(),paywallId:Et.uuid(),version:Et.number().int().positive(),document:Ni.omit({requirement:!0,offeringId:!0}),offering:Et.strictObject({id:Et.uuid()}),content:Et.strictObject({environmentId:Et.uuid(),offeringVersionId:Et.uuid(),artifact:Hu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Ii,check:sr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Zr=Et.strictObject(qo.shape).omit({document:!0,offering:!0}).extend({content:qo.shape.content.unwrap()});function Fh(e,t){let n=Os.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return qo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Yt}from"zod";var Mh={requestId:Yt.uuid(),sourceId:Yt.uuid(),expectedAvailable:Jt},qh=Yt.discriminatedUnion("action",[Yt.strictObject({...Mh,action:Yt.enum(["add","subtract","set_remaining"]),amount:de}),Yt.strictObject({...Mh,action:Yt.literal("edit"),granted:de,expiresAt:Yt.iso.datetime({offset:!0}).nullable(),nextResetAt:Yt.iso.datetime({offset:!0}).nullable(),expectedRevision:Yt.number().int().nonnegative()})]),Zu=Yt.strictObject({sourceId:Yt.uuid(),available:Jt,held:Jt,spent:Jt,adjustmentGrantId:Yt.uuid().nullable()}),Uh=Zu.extend({granted:Jt,expiresAt:Yt.iso.datetime({offset:!0}).nullable(),nextResetAt:Yt.iso.datetime({offset:!0}).nullable(),revision:Yt.number().int().nonnegative()});import{z as yn}from"zod";var Bh=yn.discriminatedUnion("action",[yn.object({action:yn.literal("upsert"),externalId:yn.string().min(1).max(128),name:yn.string().trim().min(1).max(80)}).strict(),yn.object({action:yn.literal("archive"),entityId:yn.uuid()}).strict()]),Vh=yn.object({id:yn.uuid(),externalId:yn.string().min(1).max(128),name:yn.string().min(1).max(80),archived:yn.boolean()}).strict();import{z as Gt}from"zod";import{z as Yr}from"zod";var zh=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Lh=Yr.string().regex(/.+\/.+/),Wu=Yr.number().min(-100),Wr=Yr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),xI=Yr.strictObject({input:Wr,output:Wr,cache_read:Wr.optional(),cache_write:Wr.optional(),reasoning:Wr.optional(),input_audio:Wr.optional(),output_audio:Wr.optional()}),Yu=(e,t)=>Yr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),iT=Yr.strictObject({defaultMarkup:Wu,providerMarkups:Yu(Yr.string().min(1),Wu),modelMarkups:Yu(Lh,Wu),customModels:Yu(Lh,xI.partial())});import{z as xe}from"zod";var Xr=xe.iso.datetime({offset:!0}),yr=xe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),SI=xe.discriminatedUnion("kind",[xe.object({kind:xe.literal("absolute"),from:Xr,to:Xr}).strict(),xe.object({kind:xe.literal("last_days"),days:xe.union([xe.literal(1),xe.literal(7),xe.literal(30),xe.literal(90)])}).strict(),xe.object({kind:xe.literal("billing_cycles"),membershipId:xe.uuid(),count:xe.number().int().min(1).max(12),includeCurrent:xe.boolean()}).strict()]),$h=xe.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),II=xe.object({key:xe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:xe.array(xe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ei=xe.object({range:SI,timezone:$h,filterBy:xe.array(II).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:xe.enum(["hour","day","week","month"]),internal_feature_id:xe.uuid().nullable(),entityId:xe.uuid().nullable(),topN:xe.number().int().min(1).max(50).nullable(),groupBy:xe.union([xe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),xe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid()}).strict().nullable(),limit:xe.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Gh=xe.object({from:Xr,to:Xr,interval:xe.enum(["hour","day","week","month"]),timezone:$h,rows:xe.array(xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid(),consumedUnits:yr,refundedUnits:yr,reservedUnits:yr,charged:yr,refunded:yr,reserved:yr,netUnits:yr,netCharged:yr}).strict()).max(100),nextCursor:xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid()}).strict().nullable()}).strict();var Li=Gt.string().regex(/^(0|[1-9]\d{0,29})$/),Kh=Gt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Xu=Gt.strictObject({bucket:Gt.iso.datetime({offset:!0}),group:Gt.string().max(240),isOther:Gt.boolean(),internal_feature_id:Gt.uuid()}),Hh=Gt.strictObject({...ei.shape,groupBy:Gt.union([Gt.enum(["customer","entity","entitlement"]),Gt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Xu.nullable()}).superRefine((e,t)=>{let n=ei.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Qh=Gt.strictObject({from:Gt.iso.datetime({offset:!0}),to:Gt.iso.datetime({offset:!0}),interval:ei.shape.interval,timezone:ei.shape.timezone,rows:Gt.array(Gt.strictObject({...Xu.shape,eventCount:Li,units:Kh,tokenEventCount:Li,tokens:Gt.strictObject(Object.fromEntries(zh.map(e=>[e,Li]))),totalTokens:Li,providerCostEventCount:Li,providerCostUsd:Kh,invalidTelemetryEventCount:Li})).max(100),nextCursor:Xu.nullable()});import{z as St}from"zod";var Jh=St.object({requestId:St.uuid(),items:St.array(St.object({customerId:St.uuid(),command:Ao.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),Zh=St.object({batchId:St.uuid(),after:St.number().int().min(-1).max(999),limit:St.number().int().min(1).max(100)}).strict(),Wh=St.object({batchId:St.uuid(),status:St.enum(["queued","complete"]),total:St.number().int().min(1).max(1e3),processed:St.number().int().min(0).max(1e3),items:St.array(St.object({position:St.number().int().min(0).max(999),customerId:St.uuid(),idempotencyKey:St.string().min(1).max(120),status:St.enum(["queued","accepted","rejected","failed"]),receipt:bo.nullable(),errorCode:St.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:St.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var vI=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Yh=k.enum(["draft","active","paused","archived"]),Xh=k.string().min(1).max(256),eg=k.array(Xh).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),wI=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),OI=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:wI.nullable()}),PI=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(OI).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:Xh,duration:dn}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:dn,rollover:k.boolean(),productIds:eg})]),CI=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),tg=k.object({key:CI,name:k.string().trim().min(1).max(80),configuration:PI}).strict(),ng=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),el=k.object({code:ng,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),rg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:eg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),ig={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:Yh,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},_I=tg.extend(ig).strict(),EI=rg.safeExtend(ig).strict(),AT=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:vI,status:Yh}),bT=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:tg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),xT=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:rg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),og=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),ag=k.object({code:ng,requestId:k.uuid()}).strict(),sg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),RI=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:dn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),cg=k.discriminatedUnion("type",[RI,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:dn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),ug=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),lg=k.object({id:k.uuid(),programId:k.uuid(),code:el.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),ST=k.object({rows:k.array(_I).max(100),nextCursor:k.uuid().nullable()}).strict(),IT=k.object({rows:k.array(EI).max(100),nextCursor:k.uuid().nullable()}).strict(),kI=el.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),jI=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),vT=k.object({codes:k.array(kI).max(100),redemptions:k.array(jI).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),wT=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:el}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Ln={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Uo=e=>new Set(e).size===e.length,tl=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),TI=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Bo=W.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),NI=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),dg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var pg=W.strictObject({id:W.uuid(),repo:TI,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Bo).min(1).max(4).refine(Uo),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(Uo),include:W.array(dg).min(1).max(16),exclude:W.array(dg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Uo),maxAgeHours:W.number().int().min(1).max(720)}),mg=pg.extend({revision:W.number().int().positive()}),CT=W.strictObject({repository:pg,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),fg=W.strictObject({repositoryId:W.uuid(),branch:Bo}),DI=W.array(tl).max(Ln.keys).refine(Uo),hg=W.strictObject({repository:mg.omit({keyIds:!0}),branch:Bo,keys:DI,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),FI=W.strictObject({filePath:NI,startingLineNumber:W.number().int().min(1).max(1e7)}),nl=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Bo,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Ln.files),sourceBytes:W.number().int().min(0).max(Ln.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Ln.files)}),features:W.array(W.strictObject({key:tl,refs:W.array(FI).max(Ln.referencesPerKey)})).max(Ln.keys)}).superRefine((e,t)=>{Uo(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>Ln.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),rl=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),MI=rl.extend({repositoryId:W.uuid(),branch:Bo,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:nl.shape.coverage}),qI=W.strictObject({repositories:W.array(mg).max(Ln.repositories),scans:W.array(MI).max(Ln.repositories*Ln.branches)}),UI=W.strictObject({key:tl,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),_T=W.strictObject({available:W.boolean().default(!0),settings:qI,expectedTargets:W.number().int().min(0).max(80),features:W.array(UI).max(2001),truncated:W.boolean()});import{z as Ee}from"zod";var cn=Ee.string().min(1).max(200),Ps=Ee.iso.datetime({offset:!0}),Vo=Ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),il=Ee.number().int().min(0).max(1e12),Ag=Ee.number().int().min(1).max(1e12),gg={...Ht,type:Ee.literal("coupon.redeemed"),grantId:Ee.uuid()},yg={...Ht,type:Ee.literal("usage.observed"),merchantTransactionId:cn,resource:cn,unit:cn,quantity:Ag},BI=Ee.strictObject({...Ht,type:Ee.literal("fulfillment.updated"),operationId:Ee.uuid(),merchantFulfillmentId:cn,status:Ee.enum(["pending","applied","failed"])}),VI=Ee.strictObject({...Ht,type:Ee.literal("benefit.claimed"),merchantBenefitId:cn,resource:cn,unit:cn,quantity:Ag,expiresAt:Ps.nullable(),revision:Vo}),LI=Ee.strictObject({...Ht,type:Ee.literal("benefit.closed"),merchantBenefitId:cn,status:Ee.enum(["failed","expired","canceled"]),revision:Vo}),zI=Ee.strictObject({...Ht,type:Ee.literal("benefit.updated"),merchantBenefitId:cn,status:Ee.enum(["active","expired","revoked"]),remainingQuantity:il.nullable(),expiresAt:Ps.nullable(),revision:Vo}),$I=Ee.strictObject({...Ht,type:Ee.literal("authorization.updated"),merchantAuthorizationId:cn,kind:Ee.literal("auto_topup"),status:Ee.enum(["pending","effective","revoked","failed"]),termsReference:cn.nullable(),revision:Vo}),GI=Ee.strictObject({...Ht,type:Ee.literal("balance.observed"),resource:cn,unit:cn,availableQuantity:il,reservedQuantity:il,periodStartsAt:Ps.nullable(),periodEndsAt:Ps.nullable(),revision:Vo}),bg=Ee.union([Ee.discriminatedUnion("type",[...ld,BI,VI,LI,zI,$I,GI]),Ee.strictObject({...gg,productVersionId:Ee.uuid(),subscriptionId:Ee.string().trim().min(1).max(255)}),Ee.strictObject({...gg,merchandiseId:Ee.uuid()}),Ee.strictObject({...yg,operation:Ee.literal("consume")}),Ee.strictObject({...yg,operation:Ee.literal("reverse"),reversalOf:cn})]),xg=Ee.strictObject({id:Ee.uuid(),eventId:Ee.string().min(1).max(200),source:Ee.literal("merchant"),providerVerified:Ee.literal(!1),outcome:Ee.string().min(1).max(100)});import{z as oe}from"zod";var Sg=Wm,KI=Sg.extend({invoice_id:Sg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ol=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),HI=ol.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),Ig=oe.strictObject({items:oe.array(HI).max(50),nextCursor:oe.uuid().nullable()}),DT=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:ol}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:ol}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),vg=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:Ei}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:KI})]),al=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),wg=al.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),zi=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:al.nullable(),errorCode:oe.string().nullable()}),Og=oe.strictObject({items:oe.array(al).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(zi).max(50),operationsLimited:oe.boolean()});var QI=w.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Pg={scope:De,permissions:w.array(QI),expiresAt:w.iso.datetime().nullable()},_N=w.discriminatedUnion("kind",[w.object({...Pg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Pg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),V=w.object({requestId:w.uuid(),scope:De}).strict(),JI=ph.safeExtend({fingerprint:gs.optional()}).strict(),ZI=V.extend({customer:Ui,created:w.boolean()});function Cg(){return V.extend({offer:lo.nullable(),reason:Ep.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:bm,response:V.extend({message:w.object({messageId:w.uuid(),channel:vo,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:V.extend({message:w.object({id:w.uuid(),channel:vo,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:Sm,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:Im,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Jl,response:V.extend({installation:kr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Zl,response:V.extend({installation:kr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:na,response:V.extend({installation:kr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:vo}),response:V.extend({preference:Js})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:xm,response:V.extend({preference:Js})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:V.extend({templates:Ig})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:Ei}),response:V.extend({preview:ru})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:Ei}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:zi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:vg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:zi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:V.extend({operation:zi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:V.extend({invoices:Og})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:V.extend({invoice:wg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:fg,response:V.extend({config:hg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:nl,response:V.extend({receipt:rl})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:V.extend({payload:jo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:zf,response:V.merge(as)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:$f,response:V.merge(Gf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:V.extend({balance:Uh})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:qh}),response:V.extend({balance:Zu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.uuid(),config:Sc,model_markups:xa})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:Da}),response:V.extend({usage:xo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:lm}),response:V.extend({usage:xo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:im}),response:V.extend({grant:qc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:om,response:V.extend({grants:am})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(kf.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(Ft).optional()}))),response:V.extend({operation:jf})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:xf.extend({customerId:w.uuid().optional()}),response:V.extend({setup:uu})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Sf.extend({customerId:w.uuid().optional()}),response:V.extend({setup:uu})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:yf.safeExtend({customerId:w.uuid()}),response:V.extend({batch:Eo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[Xa.options[0].extend({customerId:w.uuid()}),Xa.options[1].extend({customerId:w.uuid()}),Xa.options[2].extend({customerId:w.uuid()})]),response:V.extend({trial:cu})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Af.extend({customerId:w.uuid()}),response:V.extend({trial:cu})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ns,response:V.extend({subscriptions:_f})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ns,response:V.extend({purchases:Ef})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Of,response:V.extend({conflicts:Rf})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Pf,response:V.extend({resolution:Cf})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:vf,response:V.extend({verification:wf})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:uf.safeExtend({...Ci,customerId:w.uuid().optional()}),response:V.extend({quote:Ri})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:bg,response:V.extend({record:xg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional(),merchantConfirmation:io.optional()}),response:V.extend({operation:ki})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:ki})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:pf.safeExtend({customerId:w.uuid().optional()}),response:V.extend({quote:ff})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional(),merchantConfirmation:io.optional()}),response:V.extend({operation:iu})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:iu})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:hf.safeExtend({customerId:w.uuid()}),response:V.extend({quote:au})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Kr.extend({customerId:w.uuid(),merchantConfirmation:io.optional()}),response:V.extend({operation:Wa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Kr.extend({customerId:w.uuid()}),response:V.extend({operation:Wa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:zp,response:V.extend({controls:Fc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Fp,response:V.extend({prepared:qp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Up,response:V.extend({authorization:ka})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Qp,response:V.extend({coupons:Jp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Bp,response:V.extend({authorization:ka})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Kp,response:V.extend({invoices:Hp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Gp.extend({customerId:w.uuid()}),response:V.extend({operation:zi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:$p,response:V.extend({invoice:fo})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:Lp}).strict(),response:V.extend({controls:Fc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:Bh}).strict(),response:V.extend({entity:Vh})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:Hh}),response:V.extend({analytics:Qh})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:ei}).strict(),response:V.extend({analytics:Gh})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jh,response:V.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Zh,response:V.extend({batch:Wh})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Bd.extend({customerId:w.string().min(1).optional()}),response:V.extend({check:sr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:fr,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:V.extend({content:tu})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Dh,response:V.extend({paywall:Zr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Ha.optional(),...Ci,selector:Ff,customerId:w.string().min(1).optional(),commerce:fi,requirement:Pn.optional()}),response:V.extend({offering:Mf,candidates:w.array(Ac).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:sr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:V.extend({holdings:dm})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:mm}).strict(),response:V.extend({ledger:fm})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:sm.extend({customerId:w.uuid().optional()}),response:V.extend({detail:cm})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Uc.safeExtend({customerId:w.uuid().optional()}),response:V.extend({statement:um})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Ao.options[0]}).strict(),response:V.extend({quote:tm})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:de.optional(),properties:Ot.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:de.optional(),properties:Ot.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:V.extend({receipts:w.array(bo).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Ao.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:bo})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:ag,response:V.extend({redemption:og})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:ug,response:V.extend({referralCode:lg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:sg,response:V.extend({checkout:cg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:gm,response:V.extend({seats:Lc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:ym,response:V.extend({seats:Lc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:JI,response:ZI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Tu,response:V.extend({customer:Ui})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:hh,response:V.extend(gh.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fh,response:V.extend(mh.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:V.extend(ar.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:V.extend(ar.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:V.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:gs.optional()}),response:V.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(ar.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:V.extend({customer:Ui,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:Cg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:V.extend({offers:w.array(lo)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:kd,response:V.extend({operation:fc})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:jd,response:V.extend({operation:fc})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...Ci,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Cg()}},EN={recordMerchantEvent:O.recordMerchantEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,grantModelBenefit:O.grantModelBenefit,readModelBenefit:O.readModelBenefit,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as sl}from"zod";var Lo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function cl(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>on(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new Lo("Required GB Feature is unavailable");i=Wn(e.featureKey,t),o=i.value,Object.assign(r,Pi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Lo("Required GB Experiment is unavailable");if(a=Ea(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new Lo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Wn(e.configuration.featureKey,t).value;o={type:"offering_version",id:sl.uuid().parse(u)},Object.assign(r,Pi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,Pi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function _g(e,t,n){sl.uuid().parse(e),sl.number().int().nonnegative().parse(t);let r=rr(or(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as H}from"zod";var Ar=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),WI=H.enum(["running","waiting","completed","closed","ineligible","failed"]),ul=H.discriminatedUnion("type",[ku,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:Ar.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:Nu,openIn:Du}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:Ar})]),Cs=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),YI={id:Ar,presentation:kn,outputs:H.array(Ar).max(250),inputs:ls,values:H.record(H.string(),ve).optional(),offeringKey:wt.optional(),capabilities:Ii,customerData:Em,dataCursors:H.record(Ar,us.nullable())},XI=H.strictObject({...YI,content:H.strictObject({type:H.literal("document"),document:mn})}),zo=H.strictObject({id:H.uuid(),source:Cs,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:Ar,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:WI,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:hr,parameters:gr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:XI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([qo,Zr]),quote:Ri.nullable(),operation:ki.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:ul.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),_s=H.strictObject({scope:De,run:zo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ri.nullable(),operation:ki.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:Ar,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:Ar,visit:H.number().int().nonnegative(),document:mn,answers:hr,inputs:ls,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Eg=_s.extend({run:zo.extend({paywall:zo.shape.paywall.unwrap().extend({resolution:Zr}).nullable()})});var Rg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as be}from"zod";import{z as Rt}from"zod";var ev=Rt.strictObject({selector:Rt.string().min(1).max(2048),action:Rt.enum(["set","append","remove"]),attribute:Rt.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:Rt.string().max(5e4).optional(),parentSelector:Rt.string().max(2048).optional(),insertBeforeSelector:Rt.string().max(2048).optional()}),tv=Rt.strictObject({variation:Rt.string().min(1).max(128),description:Rt.string().max(2e3).default(""),css:Rt.string().max(1e5).default(""),js:Rt.string().max(1e5).default(""),domMutations:Rt.array(ev).max(200).default([]),iam:Xf.optional(),renderGuard:ss.optional()}),ll=tv.omit({variation:!0,description:!0,iam:!0}),nv=Fi.omit({variations:!0,active:!0}).extend({changeId:Rt.string().regex(/^[a-f0-9]{64}$/),variations:Rt.tuple([ll,ll]).rest(ll).refine(e=>e.length<=20)}),kg=Rt.strictObject({trackExposures:Rt.boolean(),environmentId:Rt.uuid(),generation:Rt.string().regex(/^[a-f0-9]{64}$/),experiments:Rt.array(nv).max(100),savedGroups:ko});var $o=be.string().regex(/^[a-f0-9]{64}$/),uD=be.strictObject({iam:$o,executionContracts:be.union([be.tuple([be.literal("funnel-run/1")]),be.tuple([be.literal("funnel-process/1")])]).default(["funnel-run/1"])}),rv=be.strictObject({release:$o,render:ss,button:be.strictObject({selector:be.string().min(1).max(512),elementKey:be.string().min(1).max(256),tag:be.enum(["button","a","input"])}).nullable()}),lD=be.strictObject({scope:De.extend({environmentId:be.uuid()}),release:$o,validatedAt:be.iso.datetime({offset:!0}),validUntil:be.iso.datetime({offset:!0}),entries:be.array(be.strictObject({id:be.uuid(),funnelId:be.uuid(),versionId:be.uuid(),event:be.enum(["screen_enter","button_click"]),target:rv})).max(4e3)}),jg=be.strictObject({operation:be.literal("entry_start"),funnelId:be.uuid(),versionId:be.uuid(),entryId:be.uuid(),release:$o,requestId:be.uuid(),locale:be.string().min(1).max(35).default("en")}),Tg=be.strictObject({scope:De,suppressed:be.literal(!0),reason:be.enum(["frequency","in_progress"]),retryAt:be.iso.datetime({offset:!0}).nullable()}),dD=be.strictObject({experimentId:be.uuid(),splitNodeId:be.string().min(1).max(128)}),iv=be.strictObject({experimentId:be.uuid(),experimentKey:be.string().min(1).max(128),variationKey:be.string().min(1).max(128),inExperiment:be.boolean(),generation:be.string().min(1).max(256)}),Go=be.strictObject({operation:be.literal("page_experiments"),release:$o,usedReceiptIds:be.array(be.uuid()).max(20).default([]),customerToken:be.string().regex(Ft).optional()}),Ng=be.strictObject({scope:De,runId:be.uuid(),assignments:be.array(iv.extend({receiptId:be.uuid()})).max(100),payload:kg});var Mn=se.literal(Hf),ov=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),dl=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Dg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:dl}),se.strictObject({type:se.literal("customer"),customer:Qr,customerData:qi.optional()})]),pl=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),av=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:pl.omit({runId:!0,requestId:!0}).nullable()}),sv=se.union([ul,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),cv=zo.omit({authenticated:!0}).extend({identity:av,instruction:sv.nullable()}),uv=se.discriminatedUnion("operation",[Ct.options[2].omit({customerToken:!0}),Ct.options[3].omit({customerToken:!0}),Ct.options[4].omit({customerToken:!0}),Ct.options[5].omit({customerToken:!0}),Ct.options[6].omit({customerToken:!0}),Ct.options[7].omit({customerToken:!0})]),Es={contract:Mn,customerToken:se.string().regex(Ft)},Fg={contract:Mn,requestId:se.uuid(),runToken:ov,externalUserId:Qr.options[1].shape.value},Mg=se.discriminatedUnion("operation",[se.strictObject({contract:Mn,operation:se.literal("describe")}),se.strictObject({contract:Mn,operation:se.literal("start"),source:Dg,funnelId:Ct.options[0].shape.funnelId,requestId:se.uuid(),locale:Ct.options[0].shape.locale,parameters:Ct.options[0].shape.parameters}),jg.omit({operation:!0}).extend({contract:Mn,operation:se.literal("entry_start"),source:Dg}),se.strictObject({...Fg,operation:se.literal("bind_customer"),guestToken:dl,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Fg,operation:se.literal("binding_status"),guestToken:dl.optional()}),Ct.options[1].omit({operation:!0,customerToken:!0}).extend({...Es,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),Ct.options[8].omit({operation:!0,customerToken:!0}).extend({...Es,operation:se.literal("review")}),Go.omit({customerToken:!0}).extend(Es),se.strictObject({...Es,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:uv})]),ml=_s.omit({run:!0}).extend({contract:Mn,run:cv,settlement:_s.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),SD=Tg.extend({contract:Mn}),ID=se.discriminatedUnion("operation",[Mg.options[1].omit({contract:!0,source:!0,requestId:!0}),Mg.options[2].omit({contract:!0,source:!0,requestId:!0})]),vD=ml.extend({binding:pl,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),wD=se.discriminatedUnion("state",[se.strictObject({contract:Mn,scope:De,state:se.literal("not_accepted")}),se.strictObject({contract:Mn,scope:De,state:se.literal("conflict")}),se.strictObject({contract:Mn,scope:De,state:se.literal("bound"),binding:pl})]),OD=se.strictObject({contract:Mn,scope:De,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as Me}from"zod";var $i=Me.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ug=Me.strictObject({entry:$i,nodes:Me.array(Me.strictObject({id:$i,type:Me.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Me.record(Me.string(),$i),writes:Me.record(wt,wt),resources:Me.strictObject({screenId:$i.optional(),paywallVersionId:Me.uuid().optional(),couponId:Me.uuid().optional(),couponIds:Me.array(Me.uuid()).max(20).optional(),experimentId:Me.uuid().optional(),featureKey:Me.string().optional(),offeringVersionId:Me.uuid().optional()})})).min(1).max(500)}),qg={scope:De,funnelId:Me.uuid(),versionId:Me.uuid(),evaluationRevision:Me.number().int().nonnegative(),expiresAt:Me.iso.datetime({offset:!0}).nullable(),topology:Ug},Rs=Me.discriminatedUnion("evaluationMode",[Me.strictObject({...qg,evaluationMode:Me.literal("local"),growth:Sn,conditions:Me.record($i,Me.array(Me.strictObject({condition:nn,port:Me.string()})))}),Me.strictObject({...qg,evaluationMode:Me.literal("remote")})]),lv=Rs.options[0].extend({evaluation:Me.strictObject({maxTransitions:Me.number().int().min(1).max(1e4),variables:Me.record(wt,Oi),outputSchema:wi,terminals:Me.record($i,Me.strictObject({outcome:Me.enum(["completed","closed","ineligible","failed"]),output:No.nullable()}))})});function dv(e){return Ug.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Me.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function fl(e){let t=Vi.parse(e.document),n=e.evaluationMode==="local"?Sn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:dv(t)};return Rs.parse(e.evaluationMode==="remote"?r:{...r,growth:vs(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function Bg(e){let t=fl(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Vi.parse(e.document);return lv.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as at}from"zod";var Vg=at.string().regex(/^[a-f0-9]{64}$/),pv=Fi.omit({variations:!0,active:!0}).extend({changeId:Vg,variations:at.array(at.strictObject({urlRedirect:at.string().max(2048)})).min(2).max(20)}),Lg=at.strictObject({environmentId:at.uuid(),trackExposures:at.boolean(),generation:Vg,experiments:at.array(pv).max(100),savedGroups:ko}),mv=at.strictObject({eventUuid:at.uuid(),timestamp:at.iso.datetime({offset:!0}).optional(),deviceId:at.string().min(1).max(128),sessionId:at.string().min(1).max(128).optional(),url:at.url().max(2048),pageTitle:at.string().max(512).optional(),experimentKey:at.string().min(1).max(255),variationKey:at.string().min(1).max(64)}),qD=at.strictObject({events:at.array(mv).min(1).max(20)}),UD=at.strictObject({inserted:at.number().int().nonnegative(),duplicates:at.number().int().nonnegative(),skipped:at.number().int().nonnegative(),rejected:at.array(at.strictObject({index:at.number().int().nonnegative(),reason:at.string()}))});import{z as pt}from"zod";var gl=32,fv=522240;function yl(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var hv=pt.strictObject({nodeId:pt.string().min(1).max(64),visit:pt.number().int().nonnegative(),revision:pt.number().int().nonnegative()}),hl=pt.record(pt.string(),ve),gv=pt.strictObject({id:pt.uuid(),nodeId:pt.string().min(1).max(64),visit:pt.number().int().nonnegative(),input:pt.strictObject({schemaVersion:Do.shape.schemaVersion,kind:Do.shape.kind,selector:Do.shape.selector,contract:Do.shape.contract}),context:hl,removed:pt.array(pt.string()).max(100),attributes:hl,removedAttributes:pt.array(pt.string()).max(100),result:vh,offeringVersionId:pt.uuid().nullable(),events:pt.strictObject({entered:pt.string().regex(/^[1-9][0-9]{0,18}$/),decision:pt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),GD=pt.strictObject({schemaVersion:pt.literal(1),mode:pt.enum(["local","remote"]),versionId:pt.uuid(),generation:pt.number().int().positive(),base:hv,context:hl,steps:pt.array(gv).min(1).max(gl)}).refine(e=>fn(e)<=fv,"Segment exceeds its byte budget");var yv=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Ko(e){return Array.isArray(e)?e.some(Ko):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Ko(n):!yv.test(t))}function zg(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>Ko(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||Ko(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||Ko(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Al=class extends Error{constructor(n,r){super(r);Be(this,"code",n);this.name="FunnelLocalCalculationError"}},$g=(e,t)=>new Al(e,t),Av=e=>({experiments:e.experiments,features:e.features});function bv(e,t=$g){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Ai(e.growth.savedGroups),i=Av(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Wn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=cl({id:c.id,name:c.id,type:"condition",cases:m.map(h=>({condition:h.condition,target:c.outputs[h.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=cl({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=h.value,u=h.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let p=c.outputs[u]??(u==="value"?c.id:void 0);if(!p)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:p,...l===void 0?{}:{value:l}}}}}function xv(e,t){let n=Rs.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=bv(n,t);return(o,s)=>(i(),Sv(a,o,s))}function Sv(e,t,n){let r=Pt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function Iv(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(p=>p.next.attributeName===s.attributeName&&p.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function Gg(e,t,n,r=$g){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,p=!1,m,h=R=>zg(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(m??(m=xv(e,r)),Iv(m,R,{attributes:Pu({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<gl;R++){let y=a.get(u);if(!y||!yl(y)||h(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let C=y.type==="end"?y.output:y.value;if(A=C?.type==="feature"?d(y.id):{...A,port:"value",value:C?.type==="literal"?C.value:C?.type==="variable"?Yc({source:"variable",key:C.key,...C.path?{path:C.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},C&&(A.value===void 0||!xn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(fn({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let C=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(C===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=Pi(y,{value:C});qm(t.variables,y,j),Object.assign(o,j)}for(let C of A.sticky)s[`${C.next.attributeName}||${C.next.attributeValue}`]=structuredClone(C.next);if(y.type==="end"||y.type==="output"){p=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let g=a.get(u);return{steps:c,...!p&&g&&(!yl(g)||h(g))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Be(this,"code",n);Be(this,"status",i);Be(this,"requestId",a);Be(this,"commandRequestId");Be(this,"retryable");Be(this,"recovery");Be(this,"retryAfterSeconds");Be(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=ra(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var Ho=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},vv=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function zn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Kg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||De.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function p(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let C=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await vv(x);if(!/^[a-f0-9]{64}$/.test(C))throw new b("INVALID_STATE","Push credential digest is invalid");return C}function m(x){let v=kr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function h(x,v){let C=u(),j={installationId:C.installationId,publicKey:C.publicKey,issuedAt:new Date().toISOString(),...v},_=await C.sign(ed(x,C.scope,j));return{...j,signature:_}}let d=(x,v,C)=>t.requestWithCredential?t.requestWithCredential(x,v,C):t.request(x,v);async function g(){let x=u(),v=i,C=r?await(t.session?.access()??r):null,j=zn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,At=Wl.parse(await h("detach",{sequence:Se,platform:x.platform}));try{let Ye=await t.request("push/installations/detach",{...x.scope,...At},"POST",{installationDetach:!0});if(!Ye||typeof Ye!="object"||!("installation"in Ye))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Ne=m(Ye.installation);if(Ne.bound||Ne.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ye){if(Ye instanceof b&&Ye.status===404)_=Ye;else if(!(Ye instanceof b)||Ye.status!==412)throw Ye}_||zn(x,Ye=>({...Ye,detachSeq:Ye.detachSeq===Se?null:Ye.detachSeq}))}if(l(v),!C){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await h("bind",{sequence:o,platform:x.platform,credentialDigest:await p(C)}));l(v);let ye=X.response.parse(await d(X.path,le,C));l(v);let ke=m(ye.installation);if(!ke.bound||ke.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&zn(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),ke}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let C=O.readPushInstallation,j=C.request.parse(await h("read",{credentialDigest:await p(v)}));l(x);let _=C.response.parse(await d(C.path,j,v));return l(x),m(_.installation)}function y(x=g){let v=s.catch(()=>{}).then(x);return s=v,v.catch(C=>{try{e?.onError?.(C instanceof Error?C:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,C){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await g(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let ye=zn(j,Ne=>C?Ne:{...Ne,addressSeq:Ho(Ne.addressSeq)}),Se=await h(C?"recovery_confirm":"recovery_request",{...x,sequence:ye.addressSeq,credentialDigest:await p(le),...C?{challenge:C}:{}}),At=C?Xl.parse(Se):Yl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Ye=await d(`push/installations/recovery/${C?"confirm":"request"}`,At,le);if(l(_),X!==a||zn(j,Ne=>Ne).addressSeq!==ye.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Ne=O.updatePushAddress.response.parse(Ye),it=m(Ne.installation);if(!it.bound||it.identitySeq!==o||it.addressSeq!==ye.addressSeq||it.connectionId!==x.connectionId||it.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return it}if(!Ye||typeof Ye!="object"||!("recovery"in Ye))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Qs.parse(Ye.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Qs.parse(await A(v,x))},async confirm(v,C){return kr.parse(await A(C,x,v))}}},identify(x){if(!e)return;o=zn(e,C=>({...C,identitySeq:Ho(C.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{zn(e,x=>{let v=Ho(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,C=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=zn(x,X=>{if(X.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Ho(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await g()})},tokenObserver(){u();let x=++a,v=i;return async C=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=zn(j,Se=>({...Se,addressSeq:Ho(Se.addressSeq)})),le=O.updatePushAddress,ye=le.request.parse(await h("address",{...C,sequence:X.addressSeq,credentialDigest:await p(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,ye,_);return l(v),x!==a||zn(j,Se=>Se).addressSeq!==X.addressSeq?null:m(le.response.parse(ke).installation)}}}}import{ZodError as wv}from"zod";function Hg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof wv?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=Hg(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):Hg(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function Qg(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var Jg={name:"@tinkerlandai/longplay-sdk",version:"0.10.19",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function We(e){return typeof e=="string"?e:String(e)}var Pv=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Cv(e){return e.replace(Pv,"$1\uFFFD")}function Il(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function iy(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function Zg(e){let t;if(Array.isArray(e)){let n=e.map(We);if(n.length===2)return n}else if((t=iy(e))!=null){let n=Il(t.next()),r=Il(t.next());if(!n.done&&!r.done)return[We(n.value),We(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Wg="0123456789ABCDEF",_v=/(?:%[0-9A-Fa-f]{2})+/g;function $n(e){return`%${Wg[e>>4&15]}${Wg[15&e]}`}function oy(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?$n(e):String.fromCharCode(e):e<=2047?$n(192|e>>6)+$n(128|63&e):e<=65535?$n(224|e>>12)+$n(128|e>>6&63)+$n(128|63&e):$n(240|e>>18)+$n(128|e>>12&63)+$n(128|e>>6&63)+$n(128|63&e)}function vl(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function wl(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(_v,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function Zo(e){return e<=31||e>126}function Ev(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return Zo(e)}}function kl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return Zo(e)}}function Rv(e){return kl(e)||e===39}function Ol(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return kl(e)}}function Ds(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Ol(e)}}function Yg(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return Ds(n)}})(e)}}function ay(e,t){return oy(e=e||0,t)}function Gn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=oy(o,t,n)}return i}function jl(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([wl(i.slice(0,a),!0),wl(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Pl(e){let t="";for(let n=0;n<e.length;n++){let r=Gn(e[n][0],Yg,!0),i=Gn(e[n][1],Yg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var kv=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],jv=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Tv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Nv=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Dv(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[Fv,Mv,qv,Xg]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function Uv(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function sy(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Qo(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function Bv(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&sy(Nv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Qo(Xg,t[i]);)i--;let a=n+1;for(;a<t.length&&Qo(Xg,t[a]);)a++;if(!(i>=0&&a<t.length&&Qo(Mv,t[i])&&Qo(qv,t[a])))return!1}return!0}var Vv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Lv=/\p{Script=Latin}/u;function zv(e){return!Vv.test(e)||!Lv.test(e)}var br=36,js=1,Cl=26,$v=38,Gv=700,Kv=72,Hv=128,Qv=2147483647;function ey(e){return String.fromCharCode(e+22+75*+(e<26))}function Jv(e,t,n){let r=0;for(e=n?Math.floor(e/Gv):e>>1,e+=Math.floor(e/t);e>(br-js)*Cl>>1;r+=br)e=Math.floor(e/(br-js));return Math.floor(r+(br-js+1)*e/(e+$v))}function Zv(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=Hv,o=0,s=Kv;for(;r<t.length;){let c=Qv;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let p=o;for(let m=br;;m+=br){let h=m<=s?js:m>=s+Cl?Cl:m-s;if(p<h)break;n+=ey(h+(p-h)%(br-h)),p=Math.floor((p-h)/(br-h))}n+=ey(p),s=Jv(o,r+1,r===i),o=0,r++}}o++,a++}return n}function bl(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=vl(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function ty(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function cy(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function uy(e){return e.length===2&&cy(e.codePointAt(0),e.codePointAt(1))}function ny(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function gt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function ly(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function _l(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,l=0,p=0;for(;p<4&&(u=vl(c[s]))>=0;)l=(l<<4)+u,s++,p++;if(c[s]===46){if(p===0||o>6)return null;s-=p;let m=0;for(;c[s]!==void 0;){let h=0;if(m>0)if(c[s]===46&&m<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(h=10*h+vl(c[s]),h>255)return null;s++}i[o]=256*i[o]+h,m++,m%2==0&&o++}if(m!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return ny(r)?null:Gn(r,Zo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let p=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!sy(kv,p)||Qo(Fv,p))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let p of u){let m=p.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(p))continue;let h=Uv(p,m);if(h){l+=h;continue}let d=jv.indexOf(m);l+=d<0?p:Tv[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(Dv(u)||l&&(/^\p{Mark}/u.test(u)||!Bv(u)||!zv(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${Zv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:wl(e));return n===null||ny(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(bl(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let l=bl(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=bl(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function El(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,p=0;for(let m=0;m<s.length;++m)s[m]!==0?(p>l&&(c=u,l=p),u=-1,p=0):(u===-1&&(u=m),++p);return p>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function dy(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function py(e){return e.username!==""||e.password!==""}function xl(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",$e=null,B,Ts=!1,Ns=!1,ti=!1,yt;function An(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),E=0,U=e,Oe="",$e=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ts=!1,Ns=!1,ti=!1,yt=r||0;let i=Wv;switch(r){case 3:case 4:i=Fs;break;case 5:i=Nl;break;case 6:i=ni;break;case 7:i=xr;break;case 8:i=Kn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?qn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function qn(e){return e!=null&&e>65535?2:1}function my(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Wv=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Oe=U.slice(E,n).toLowerCase(),E=n,Yv(n<U.length?e:void 0)}else return yt?1:(--E,ee(t,e)?fy(G(U,E)):0)},Yv=e=>{let t=E;if(e===58){if(yt){if(gt(B.scheme)!==gt(Oe))return 0;if((py(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,yt?(B.port===ly(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?Dl(G(U,E)):0:gt(B.scheme)&&$e!==null&&$e.scheme===B.scheme?ee(t,e)?Xv(G(U,E)):0:gt(B.scheme)?ee(t,e)?tw(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?ew(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?gy(G(U,E)):0))}else return yt?1:(Oe="",E=-1,ee(t,e)?fy(G(U,E)):0)},fy=e=>{let t=E;return $e===null||$e.opaquePath&&e!==35?1:$e.opaquePath&&e===35?(B.scheme=$e.scheme,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,B.fragment="",ee(t,e)?Kn(G(U,E)):0):$e.scheme==="file"?(E--,ee(t,e)?Dl(G(U,E)):0):(E--,ee(t,e)?Tl(G(U,E)):0)},Xv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?qs(G(U,E)):0):(E--,ee(t,e)?Tl(G(U,E)):0)},ew=e=>{let t=E;return e===47?ee(t,e)?Gi(G(U,E)):0:(E--,ee(t,e)?Un(G(U,E)):0)},Tl=e=>{let t=E;return B.scheme=$e.scheme,e===47||gt(B.scheme)&&e===92?ee(t,e)?ry(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,B.path=$e.path.slice(),B.query=$e.query,e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Un(G(U,E)):0):ee(t,e)?Tl(G(U,E)):0)},ry=e=>{let t=E;return gt(B.scheme)&&(e===47||e===92)?ee(t,e)?qs(G(U,E)):0:e===47?ee(t,e)?Gi(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,E--,ee(t,e)?Un(G(U,E)):0)},tw=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?qs(G(U,E)):0},qs=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Gi(G(U,E)):0):ee(t,e)?qs(G(U,E)):0},Gi=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!gt(B.scheme))){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&gt(B.scheme))break;n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Gi(G(U,E)):0}if(e===64){Ts&&(Oe=`%40${Oe}`),Ts=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!Ns){Ns=!0;continue}let i=ay(r,Ds);Ns?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Gi(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&gt(B.scheme)?Ts&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?Fs(G(U,E)):0):(Oe+=my(e),ee(t,e)?Gi(G(U,E)):0)},Fs=e=>{let t=E;if(yt&&B.scheme==="file")return E--,ee(t,e)?Fl(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!gt(B.scheme))){let n=E+qn(e);for(e===91?ti=!0:e===93&&(ti=!1);n<U.length;){let r=G(U,n);if(r==null||!ti&&r===58||r===35||r===47||r===63||r===92&&gt(B.scheme))break;r===91?ti=!0:r===93&&(ti=!1),n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Fs(G(U,E)):0}else if(e===58&&!ti){if(Oe===""||yt===4)return 1;let n=_l(Oe,!gt(B.scheme));return n===null?1:(B.host=El(n),Oe="",ee(t,e)?Nl(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&gt(B.scheme)){if(E--,gt(B.scheme)&&Oe==="")return 1;if(yt&&Oe===""&&(py(B)||B.port!==null))return 1;let n=_l(Oe,!gt(B.scheme));return n===null?1:(B.host=El(n),Oe="",yt?0:ee(t,e)?ni(G(U,E)):0)}else return Oe+=my(e),ee(t,e)?Fs(G(U,E)):0},Nl=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Nl(G(U,E)):0}else if(yt||e==null||e===35||e===47||e===63||e===92&&gt(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===ly(B.scheme)?null:n,Oe="",yt)return 0}return yt?1:(E--,ee(t,e)?ni(G(U,E)):0)}else return 1};function hy(e,t){let n=e.length-t;if(n<2)return!1;if(cy(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var Dl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?nw(G(U,E)):0:$e?.scheme==="file"?(B.host=$e.host,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(B.query=null,hy(U,E)?B.path=[]:dy(B),E--,ee(t,e)?Un(G(U,E)):0):ee(t,e)?Dl(G(U,E)):0):(E--,ee(t,e)?Un(G(U,E)):0)},nw=e=>{let t=E;return e===47||e===92?ee(t,e)?Fl(G(U,E)):0:($e!==null&&$e.scheme==="file"&&(!hy(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})($e.path[0])&&B.path.push($e.path[0]),B.host=$e.host),E--,ee(t,e)?Un(G(U,E)):0)},Fl=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Fl(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!yt&&uy(Oe))return ee(t,e)?Un(G(U,E)):0;if(Oe==="")return B.host="",yt?0:ee(t,e)?ni(G(U,E)):0;{let n=_l(Oe,!gt(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=El(n),Oe="",yt?0:ee(t,e)?ni(G(U,E)):0)}}return 1},ni=e=>{let t=E;return gt(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Un(G(U,E)):0):!yt&&e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):!yt&&e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Un(G(U,E)):0):(yt&&B.host===null&&B.path.push(""),ee(t,e)?ni(G(U,E)):0)},Un=e=>{let t=E;if(e!=null&&e!==47&&(!gt(B.scheme)||e!==92)&&(yt||e!==63&&e!==35)){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||gt(B.scheme)&&r===92||!yt&&(r===63||r===35))break;n+=qn(r)}Oe+=Gn(U.slice(E,n),Ol),E=n,e=G(U,n)}if(e==null||e===47||gt(B.scheme)&&e===92||!yt&&(e===63||e===35)){let n=gt(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Oe)?(dy(B),e!==47&&!n&&B.path.push("")):ty(Oe)&&e!==47&&!n?B.path.push(""):ty(Oe)||(B.scheme==="file"&&B.path.length===0&&uy(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):ee(t,e)?Un(G(U,E)):0}else return Oe+=ay(e,Ol),ee(t,e)?Un(G(U,E)):0},gy=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?xr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Kn(G(U,E)):0;if(e!=null){let n=E+qn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=qn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Gn(r.slice(0,-1),Zo)+"%20":B.path[0]+=Gn(r,Zo),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?xr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Kn(G(U,E)):0}return ee(t,e)?gy(G(U,E)):0},xr=e=>{let t=E,n=E;if(e!=null){if(yt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=gt(B.scheme)?Rv:kl;B.query+=Gn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!yt?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):ee(t,e)?xr(G(U,E)):0},Kn=e=>{let t=E;return e!=null&&(B.fragment+=Gn(U.slice(E),Ev),E=U.length),ee(t,e)?Kn(G(U,E)):0};function Rl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function yy(e){switch(e.scheme){case"blob":{let t=An(Rl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":yy(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Ze=Symbol("URLImpl"),wn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=We(t),n!=null&&(n=We(n));let r=null;if(n!=null&&(r=An(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=An(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=We(t),n!==void 0&&(n=We(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=We(t),n!==void 0&&(n=We(n));let r=null;return n!=null&&(r=An(n,null,null,0),r==null)?!1:An(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=Rl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ze].url)}set href(t){let n=An(t=We(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze].url=n,this[Ze].query&&Sl(this[Ze].query,n.query)}get origin(){return yy(this[Ze].url)}get protocol(){return`${this[Ze].url.scheme}:`}set protocol(t){An(`${t=We(t)}:`,this[Ze].url,null,2)}get username(){return this[Ze].url.username}set username(t){t=We(t),xl(this[Ze].url)||(function(r,i){r.username=Gn(i,Ds)})(this[Ze].url,t)}get password(){return this[Ze].url.password}set password(t){t=We(t),xl(this[Ze].url)||(function(r,i){r.password=Gn(i,Ds)})(this[Ze].url,t)}get host(){let{url:t}=this[Ze];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=We(t),this[Ze].url.opaquePath||An(t,this[Ze].url,null,3)}get hostname(){let{url:t}=this[Ze];return t.host!=null?t.host:""}set hostname(t){t=We(t),this[Ze].url.opaquePath||An(t,this[Ze].url,null,4)}get port(){let{url:t}=this[Ze];return t.port!=null?`${t.port}`:""}set port(t){t=We(t);let{url:n}=this[Ze];xl(n)||(t?An(t,n,null,5):n.port=null)}get pathname(){return Rl(this[Ze].url)}set pathname(t){t=We(t);let{url:n}=this[Ze];n.opaquePath||(n.path=[],An(t,n,null,6))}get search(){let{url:t}=this[Ze];return t.query?`?${t.query}`:""}set search(t){t=We(t);let{url:n,query:r}=this[Ze];if(!t)n.query=null,r&&Sl(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",An(i,n,null,7),r&&Sl(r,n.query)}}get searchParams(){let t=this[Ze],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Ms;return o[lt].url=i,o[lt].serialized=a==null,a&&(o[lt].list=jl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ze];return t.fragment?`#${t.fragment}`:""}set hash(t){t=We(t);let{url:n}=this[Ze];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",An(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(wn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var lt=Symbol("URLSearchParamsImpl"),rw=Symbol.dispose||Symbol.for("dispose");function Sl(e,t){t?e[lt].list=jl(t):e[lt].list.length=0,e[lt].serialized=t==null}function ks(e){if(e.url){let t=Pl(e.list);(function(r,i){r[Ze].url.query=i})(e.url,t||null),e.serialized=!0}}var iw=typeof Iterator<"u"?Iterator:Object,Jo=class extends iw{constructor(t,n){super(),this[lt]={ptr:t,map:n,index:0}}next(){let t=this[lt];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[rw](){}},Ms=class{constructor(t){let n=this[lt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Zg(t[i]));else if((r=iy(t))!=null){let i;for(;!(i=Il(r.next())).done;)n.list.push(Zg(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=Cv(o),c=We(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=We(t);i=i[0]==="?"?i.substring(1):i,n.list=jl(i)}}get size(){return this[lt].list.length}append(t,n){t=We(t),n=We(n),this[lt].list.push([t,n]);let r=this[lt];r.url&&r.serialized?(function(a,o){let s=a[Ze].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Pl([[t,n]])):ks(r)}delete(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[lt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ks(this[lt])}get(t){t=We(t);let{list:n}=this[lt];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=We(t);let n=[],{list:r}=this[lt];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[lt];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=We(t),n=We(n);let{list:r}=this[lt],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&ks(this[lt])}sort(){this[lt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ks(this[lt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[lt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Jo(this[lt],t=>t)}keys(){return new Jo(this[lt],t=>t[0])}values(){return new Jo(this[lt],t=>t[1])}toString(){return Pl(this[lt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ms.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Sr="https://api.longplayai.com";function Ay(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let p of[...a.keys()])try{p()}catch{}};function s(p){let m=++r;i=void 0,t=void 0;for(let h of[...a.values()])try{h?.()}catch{}m===r&&(t=p,o())}let c=()=>s();function u(p,m=!1){let h=ar.safeParse(p);if(!h.success||m&&Date.parse(h.data.expiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<Date.parse(h.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return h.data}async function l(){if(i)return i;let p=typeof t=="object"?t:void 0,m=r;if(!p||Date.parse(p.refreshExpiresAt)<=Date.now())throw p&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let h=(async()=>{try{let d=await e(p.refreshToken);if(m!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(d,!0);if(g.customerId!==p.customerId||g.sessionId!==p.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,{...g}}catch(d){throw m!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=h;try{return await h}finally{i===h&&(i=void 0)}}return{identify(p){let m=typeof p=="string"?p:u(p),h=typeof m=="string"?m:m.accessToken;if(!h.trim()||/\s/.test(h)||h.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(m)},reset:c,subscribeIdentity(p,m){return a.set(p,m),()=>{a.delete(p)}},access(){let p=typeof t=="object"?t:void 0;if(p&&Date.parse(p.expiresAt)<=Date.now()+3e4){let h=r;return l().then(()=>{let d=n();if(h!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let m=n();if(!m)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var by=Symbol("IndianaNoContent");function Ir(e,t,n=wn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?De.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??Sr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,p=null,m=new Set,h=e.session??Ay(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:C,...j}=x;return j});function d(){l+=1,p=null;for(let A of m)A.abort();m.clear()}let g=h.subscribeIdentity(d);function R(){u||h.reset()}async function y(A,x={},v="POST",C={},j){let _=C.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||m.add(le);let ye=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),ke,Se=new Promise((Ne,it)=>{ke=()=>it(ye()),le.signal.addEventListener("abort",ke,{once:!0})}),At=setTimeout(()=>le.abort(),C.timeoutMs??c),Ye=async()=>{let Ne=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...C.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Xs]:ec.current,[od]:Jg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...C.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw ye();let it;try{it=Ne.status===204?by:await Ne.json()}catch{throw le.signal.aborted?ye():new b(Ne.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Ne.status,Ne.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw ye();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Ne.ok){let ft=Ys.safeParse(it),Xt=ft.success&&(!Jn.safeParse(ft.data.error.code).success||rd(ft.data.error.code,Ne.status)),Cr=Xt?ft.data.error.code:"HTTP_ERROR",_r=ra(Cr,Ne.status,{retryAfter:Ne.headers.get("Retry-After"),recovery:Xt?ft.data.error.recovery:void 0,reason:Xt?ft.data.error.reason:void 0});throw new b(Cr,Xt?ft.data.error.message:"Longplay request failed",Ne.status,Ne.headers.get("X-Request-Id")??(ft.success?ft.data.requestId:void 0),{..._r,...ft.success&&ft.data.error.retryable===!1?{retryable:!1}:{},..._r.retryAfterSeconds===void 0&&ft.success&&ft.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ft.data.error.retryAfterSeconds}:{}})}if(Ne.headers.get(Xs)!==ec.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&it!==by){let ft=it&&typeof it=="object"&&"scope"in it?it:it&&typeof it=="object"&&"configuration"in it?it.configuration:null;if(!ft||typeof ft!="object"||!("scope"in ft))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Xt=De.safeParse(ft.scope);if(!Xt.success||Xt.data.projectId!==a.projectId||Xt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let ii=Ne.headers.get("X-Indiana-Telemetry-Subject");if(ii){if(!/^[a-f0-9]{64}$/.test(ii))throw new b("INVALID_RESPONSE","Invalid telemetry identity");p!==ii&&(p=ii,t?.(p))}return it};try{return await Promise.race([Ye(),Se])}catch(Ne){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Ne instanceof b?Ne:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(At),le.signal.removeEventListener("abort",ke),m.delete(le)}}return{session:h,requestWithCredential(A,x,v,C={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",C,v)},subjectKey:()=>p,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=De.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}h.identify(A)},reset:R,dispose(){u||(u=!0,g(),d())},request(A,x={},v="POST",C={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(C.installationDetach)return y(A,x,v,C);let j=l;try{let _=h.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,C,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function xy(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!Ft.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Ml(e,t,n,r){if(!Ld(e,t)||n!==void 0&&t.observation&&t.observation.subject.customerId!==n||r!==void 0&&t.observation!==void 0&&(t.observation.subject.scope.projectId!==r.projectId||t.observation.subject.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","The access requirement or Customer changed");return t}function vr(e,t,n){if(e.requirement){if(!t)throw new b("INVALID_RESPONSE","The requested access check is missing");Ml(e.requirement,t,e.customerId,n)}}function Ge(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var ow={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Sy(e){return{async checkEntitlement(t){Ge(t);let n=O.checkEntitlement,r=n.request.parse(t),i=await ge(e,n,r);return Ml(r.requirement,i.check,void 0,i.scope),i},async readHoldings(t={}){return ge(e,ow,t)}}}function Iy(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Ge(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Ge(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function vy(e){return{async setupPayment(t){Ge(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Ge(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Ge(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Ge(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Ge(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Ge(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Ge(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ge(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ge(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Ge(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function wy(e){return{async previewUpdate(t){Ge(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Ge(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Ge(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Ge(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Ge(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Ge(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Ge(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Oy(e){return{async redeemReward(t){return Ge(t),(await ge(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ge(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ge(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Py(e){return{...Sy(e),...Iy(e),...vy(e),...wy(e),...Oy(e)}}function Cy(e){return{async resolveContent(t){Ge(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Ge(t);let n=O.resolvePaywall,r=n.request.parse(t),i=await ge(e,n,r);return vr(r,i.paywall.check,i.scope),i},async resolveOffering(t){Ge(t);let n=O.resolveOffering,r=n.request.parse(t),i=await ge(e,n,r);return vr(r,i.check,i.scope),i}}}var ql=e=>new TextEncoder().encode(JSON.stringify(e)).length,_y=16384;function Ey(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,p().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,g={},R={}){if(c(),r&&Date.now()<r.until&&!Vf(r.config,d))return;h();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:g,...R}]}).events[0];if(ql({events:[y]})>_y)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function p(d=!1){if(c(),o)return o;let g=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let x=[],v=ql({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ql(_)+(x.length?1:0);if(x.length&&v+X>_y)break;x.push(_),v+=X}let C=O.trackEvents,j=await ge(e,C,{events:x},void 0,{keepalive:d});if(g!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let m;function h(){if(m||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&p(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),m=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:p,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){m?.(),m=void 0}}}function Ul(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:Pt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},p=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function m(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>m(v.id,A))))}let h=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?p():structuredClone(o.features[y]??p()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||m(y)?p():structuredClone(Wn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],C=(async()=>{let j=as.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=Pt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:C};try{await C}finally{s?.loading===C&&(s=null)}}function g(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?jo.parse(x):null,C=v??Sn.parse(x);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===C.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:ye,expiresAt:ke,...Se}=C;if(_t(le)!==_t(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=C.evaluatedAt,t.expiresAt=C.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&g(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(C.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in C&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(C),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=Ai(t.savedGroups),l.trackedFeatureUsage={},u(),g(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=Pt.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),g()},evalFeature:h,isOn(y){return h(y).on},isOff(y){return h(y).off},getFeatureValue(y,A){let x=h(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function Ry(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function aw(e){let t=Ry(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function ky(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,p=!1,m=async()=>{if(p||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ye=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,ye,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(ke.scope.projectId!==r.projectId||ke.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ke.payload.analyticsConfig),ke},h=await m(),d=!0,g,R=ye=>{try{u.onError?.(ye)}catch{}},y=(ye,ke,Se)=>{try{let At=Ry(Se);n.track(ye,ke,At?{merchandise:At}:{})}catch(At){R(At)}},A=Ul({assertUsable:i?.assertFeatures,scope:h.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,h.payload):(await m()).payload,evaluateRemote:async ye=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...ye,attributes:aw(ye.attributes)});if(Se.scope.projectId!==h.scope.projectId||Se.scope.environment!==h.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(ye,ke,Se)=>y("Experiment Viewed",{experimentId:ye.key,variationId:ke.key},Se),onFeatureUsage:(ye,ke,Se)=>y("Feature Evaluated",{feature:ye,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(g),!i&&(p||l!==a||!A.expiresAt||(g=setTimeout(()=>{C().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function C(){try{return await x()}finally{v()}}let j=()=>{p||C().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!p&&i.fresh&&C().catch(R)});function le(){p||(p=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(ye){throw le(),ye}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:C,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as sw}from"zod";function jy(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=sw.object({funnelId:Cs.shape.id,funnelVersionId:Cs.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering,c=s.request.parse(a(o)),u=await ge(e,s,c);return vr(c,u.check,u.scope),u},async resolvePaywall(o){let s=O.resolvePaywall,c=s.request.parse(a(o)),u=await ge(e,s,c);return vr(c,u.paywall.check,u.scope),u},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Ty(e){let t=Ir(e),n=t.request,r;try{r=Kg(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=xy(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ey(n,i.isIdentified),o=ky(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Qg(n,r),...Py(n),...Cy(n),forFunnel(s){return i.assertActive(),jy(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ki(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ki(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ki(a,Reflect.get(t,i)))}function Us(e,t){let n=Eg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Hi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Bs(e){let t=Ft.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Hi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Ct.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=Ir({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=Us(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ki(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function Bl(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((p,m)=>{s=()=>m(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let p=await Promise.race([r.read(),c]);if(p.done){o=!0;break}if(a+=p.value.length,a>t)throw n.error("limit");i.push(p.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let p of i)u.set(p,l),l+=p.length;return u}async function Ny(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Bl(e,t,n))}function Vs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Ju(n)===t.sha256}async function Ls(e,t){let n=Zr.parse(t),{artifact:r,environmentId:i}=n.content,a=new wn(e.baseUrl??Sr).origin,o=new wn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((p,m)=>{c=setTimeout(()=>{let h=new b("TIMEOUT","Public Paywall read timed out");s.abort(h),m(h)},sn.initializationMs)}),l=(async()=>{let p=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(p.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>r.byteLength)throw p.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let m=await Bl(p,r.byteLength,{signal:s.signal,error:h=>new b("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Vs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Fh(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Dy=(e,t)=>new b(e,t);var cw=3,uw=2e3;function lw(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function dw(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===cw||!lw(n))throw n;await new Promise(r=>setTimeout(r,t*uw))}}async function Vl(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=pw(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await dw(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function pw(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=fl({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:Sn.parse(o)}),c=mw(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function mw(e,t,n){return Gg(e,t,n,Dy)}import{z as bn}from"zod";var Fy=Ct.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),My=bn.strictObject({schemaVersion:bn.literal(1),scope:De,runId:bn.uuid(),funnelId:bn.uuid(),versionId:bn.uuid(),processBindingIds:bn.record(bn.uuid(),bn.uuid().nullable()).optional(),command:Fy.optional(),closeCommand:Fy.refine(e=>e.operation==="close").optional(),purchase:bn.strictObject({receiptId:bn.uuid(),operationId:bn.uuid(),generation:bn.number().int().nonnegative()}).optional(),closed:bn.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),rn=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),zs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function qy(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:My.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let p=await a();if(p.entry&&n!==null&&r(p.entry)!==n)throw rn();let m=u(p.entry,p.revision);if(zs(p.entry,m)){t=p.revision;return}let h=await e.write(p.revision,m);if(h!==null){if(!Number.isSafeInteger(h)||h<=p.revision)throw rn();t=h;return}}throw rn()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let p={...u.processBindingIds};delete p[l],u={...u,processBindingIds:p}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw rn();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=My.parse(u),p=l.command;return!p||n!==null&&r(l)!==n?Promise.reject(rn()):(n??(n=r(l)),o(()=>s((m,h)=>{if(m&&!zs(r(m),r(l)))throw rn();if(m&&l.processBindingIds){for(let[d,g]of Object.entries(l.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,d)&&m.processBindingIds[d]!==g)throw rn();m={...m,processBindingIds:{...m.processBindingIds,...l.processBindingIds}}}if(!m){if(h!==t&&p.operation!=="close")throw rn();return l}if(!m.command)return{...m,command:p,...p.operation==="close"?{closed:!0}:{}};if(p.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===p.requestId||m.closeCommand&&!zs(m.closeCommand,p))throw rn();return{...m,closeCommand:p,closed:!0}}if(!zs(m.command,p))throw rn();return m})))},observePurchase(u,l,p,m){return o(()=>s((h,d)=>{if(!h&&d!==t||h&&r(h)!==r({...u,schemaVersion:1}))throw rn();if(h?.purchase&&h.purchase.generation>l.generation)return c(h,m);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw rn();return p?!h?.purchase||h.purchase.operationId!==l.operationId?c(h,m):c(h.command?{...h,purchase:void 0}:null,m):c({schemaVersion:1,...u,...h,purchase:l},m)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function Uy(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Sr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function By(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(p){if(n&&(n.projectId!==p.projectId||n.environment!==p.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...p})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(p,m="Run identity changed during the request"){if(p!==i||s)throw new b("IDENTITY_CHANGED",m)},assertRun(p){if(r&&(p.id!==r.id||p.source.type!==r.source.type||p.source.id!==r.source.id||p.source.versionId!==r.source.versionId||p.locale!==r.locale||!Ki(p.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&p.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(p,m,h,d,g){if(!(p.operation==="review"&&r&&r!==h&&m.run.revision<=r.revision)&&!(r&&m.run.revision===r.revision&&d!==void 0&&d<u)&&(p.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&r&&m.run.nodeId===r.nodeId&&m.run.visit===r.visit&&m.run.revision===r.revision&&(m.run.screen=r.screen,(r.paywall?.quote?.operationId===m.review?.activeOperationId||!r.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=r.paywall)),!(r?.paywall&&m.run.paywall&&r.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||m.run.revision>=r.revision)r=m.run;else if(!g)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(p){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!Ft.test(p))throw new b("INVALID_TOKEN","Customer credential required");o(),c=p},subscribe(p){return l.add(p),()=>l.delete(p)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function wr(e){let{customerToken:t,...n}=e;return n}var fw=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Vy({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,p=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();p.catch(()=>{});async function m(y){e&&await p;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:wr(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!fw(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function h(y){let A=Ct.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return g(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(wr(a))!==JSON.stringify(wr(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(wr(i))!==JSON.stringify(wr(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=m(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function g(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:p,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let C=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=C&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==C&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?C:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,ye=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=ye?.operationId??le?.quote?.operationId??ke?.operationId,At=le?.receiptId??ke?.receiptId,Ye=X?.selectionGeneration??u?.generation??0;if(e&&Se&&At&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Ye>=u.generation)){let Ne={receiptId:At,operationId:Se,generation:Ye},it=ye?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},Ne,it,j),t.assertCurrent(x),(!u||Ne.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(it?u?.operationId===Ne.operationId&&(u=void 0):u=Ne)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:h,settle:g,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function Or(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Hi.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=Ir({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=By(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Uy(e):void 0),o=a&&qy(a),s=Vy({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),C=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,ye=()=>{},ke=new Promise((Se,At)=>{ye=()=>At(X.reason),X.addEventListener("abort",ye,{once:!0}),le=setTimeout(()=>At(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",ye)}}n.assertCurrent(x);let j={...A,...C?{customerToken:C}:{}},_=A.operation==="page_experiments"?Go.parse(j):Ct.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!C?{[Rg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,C=()=>n.assertCurrent(v);o&&await s.ready,C();let j=n.view,_=Us(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(C(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(C(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let p=s.submit,m=null,h=new WeakMap;function d(A){let x=h.get(A);if(x)return x;let v=R(A);return h.set(A,v),v}let g=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(m)return m;g=!0;let v=n.generation,C=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await Vl(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let ye=!0;Vl(e.configuration,_).then(({prediction:ke})=>{ye&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=ke)}).catch(()=>{});try{x=await p({operation:"commit_segment",requestId:_g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{ye=!1,i=null}}}return x})();m=C;try{return await C}finally{m===C&&(m=null)}}let y={get configuration(){return g?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(wr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(wr(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return Ls(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let C=n.view?.id;if(!C)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Ng.parse(await c(Go.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==C||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(p(s.pending)):d(p({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(p(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?p(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(p(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function Ly(e){if(!Ft.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=Bs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Or({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function zy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function $y(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function Gy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function Ky(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function Hy(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function Qy(e,t){if(!Ft.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=Ir(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,p=null,m=null,h=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function g(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector});vr(n,v.paywall.check,v.scope);let C=await Ls(e,v.paywall);if(d(),t.paywallVersionId?C.id!==t.paywallVersionId:C.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!zy(C,i)||C.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=C,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(m){if(p===x)return m;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(p&&p!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");p=x,h++}let C=p,j=h,_=x==="read"&&m===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let ye=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x},...x==="confirm"&&v.merchantTerms?{merchantConfirmation:_d(v.merchantTerms)}:{}});return $y(ye.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(ye.operation):(s=Ky(s,ye.operation),(x!=="read"||_&&m===null)&&h===j&&p===C&&(p=null),structuredClone(s))})();if(x!=="read"){m=le;let ye=()=>{m===le&&(m=null)};le.then(ye,ye)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return Hy({quote:o,operation:s,requestId:l,pending:u!==null||p!==null,destroyed:a})},get pendingCancellation(){return!a&&p==="cancel"},refresh:g,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let C=qf(v.product,x.selection,i.capabilities);if(!C)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Ch(i.document.screen,C,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:C,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||p||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let ye=O.previewAttach,ke=await ge(r.request,ye,_);return d(),Gy(ke.quote,{productVersionId:C,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=ke.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await g(),y}catch(x){throw y.destroy(),x}}function Jy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let h=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,h)).catch(()=>{})}),l=e.nativeEvents?.(h=>{!n||!e.nativeModule||typeof h?.requestId!="string"||(async()=>{let d=await n;if(h.instanceId!==d)return;if(h.kind==="credential"){let y=r,A=null;try{if(!o&&h.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,h.requestId,A)}return}let g=!1,R=r;try{if(o||h.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(h.action),g=!o&&r===R}finally{await e.nativeModule.acknowledge(d,h.requestId,g)}})().catch(()=>{})});async function p(h,d={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let C=(async()=>{if(await g.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await g.reset(A,R),c();i=R})();a={epoch:R,task:C}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await g.invoke(A,h,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function m(h,d){let g=await p(h,d);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(h){return m("showFunnel",{runToken:h})},showPaywall(h){return m("showPaywall",h)},showContent(h){return m("showContent",h)},purchaseSubscription(h,d){return p("purchaseSubscription",{operationId:h,accepted:d})},switchSubscription(h,d){return p("switchSubscription",{operationId:h,accepted:d})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(h){return p("manageSubscriptions",h?{productId:h}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var hw=O.trackUsage.request.shape.command,gw=O.trackUsage.response;function yw(e){let t=De.parse(e.scope),n=Ty({...e,scope:t}),r={...e,scope:t,session:n.session},i=Jy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return Ly({...r,customerToken:s()})},resumeFunnel(c){return s(),Or({...r,runToken:c})},paywall(c){return Qy(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=hw.parse(c),l=a,p;try{p=await e.usageReporter(u)}catch(h){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):h}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let m=gw.parse(p);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}import{z as Sw}from"zod";import{z as Wo}from"zod";var Aw=Wo.record(Wo.string().regex(/^[a-f0-9]{64}$/),Wo.strictObject({at:Wo.number(),text:Wo.string()})),ri=2*1048576,bw=100;function xw(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Zy(e,t){let n=t===void 0?xw():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(p){if(!n)return null;let m;try{let h=await Promise.race([Promise.resolve().then(()=>n.getItem(p)),new Promise(d=>{m=setTimeout(()=>d(null),bw)})]);return typeof h=="string"&&h.length<=ri&&new TextEncoder().encode(h).byteLength<=ri?h:null}catch{return null}finally{clearTimeout(m)}}function l(){if(c)return c;let p=(async()=>{try{let m=await u(`${e}:artifacts`);if(m)return Aw.parse(JSON.parse(m))}catch{}return{}})();return c=p,p.finally(()=>{c===p&&(c=void 0)}),p}return{async readManifest(){return u(e)},writeManifest(p){!n||p.length>ri||new TextEncoder().encode(p).byteLength>ri||(s=p,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let m=s;try{await n.setItem(e,m)}catch{}s===m&&(s=void 0)}}finally{o=!1}})))},async readArtifact(p){let m=(await l())[p],h=Date.now();return m&&h>=m.at&&h-m.at<=sn.retentionMs?m.text:void 0},writeArtifact(p,m){if(!n||m.length>ri)return;let h=r.get(p);if(h?.text===m||!h&&r.size>=128)return;let d=new TextEncoder().encode(m).byteLength;i-(h?.byteLength??0)+d>ri||(r.set(p,{text:m,byteLength:d}),i+=d-(h?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let g=new Map(r);try{let R={...await l()},y=Date.now();for(let[C,j]of g)R[C]={at:y,text:j.text};let A={},x=2,v=0;for(let[C,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>sn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[C]:j})).byteLength;x+_>ri||v>=128||(A[C]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of g)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),Pr=()=>performance.now(),Wy=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Iw(e){let t=Ku.parse(e.scope),n=new wn(e.origin??Sr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new wn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${_t(t)}`,s=Zy(o,e.storage),c,u=0,l=0,p=!1,m=!1,h=0,d=0,g,R,y,A,x=0,v=new Set,C=new Set,j=new Map,_=new Map,X=0,le=!1;function ye(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!m&&!p&&!!c&&Pr()<u&&Date.now()<l;function At(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ye(Y,J,pe){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+pe>sn.maxCacheBytes);){let me=j.entries().next().value;X-=me[1].byteLength,j.delete(me[0])}j.set(Y,{text:J,byteLength:pe}),X+=pe}}function Ne(Y,J,pe){return Ny(Y,J,{signal:pe,error:me=>Pe("INVALID_RESPONSE",me==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function it(Y){let J=new wn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function Yo(Y,J,pe=!1){let me=await i(it(Y),{method:"GET",credentials:"omit",redirect:"error",cache:pe?"default":"no-cache",signal:J,headers:{}});if(me.status===429){let nt=me.headers.get("retry-after")??"";x=/^\d+$/.test(nt)?Number(nt)*1e3:Math.max(0,Date.parse(nt)-Date.now())||15e3}if(!me.ok&&me.status!==304)throw Pe(`CONFIGURATION_HTTP_${me.status}`,"Configuration synchronization failed");return me}function ii(Y,J,pe){let me=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),nt=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),st=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),un=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![me,nt,st,un].every(Number.isFinite)||nt<=me||nt-me>sn.maxControlAgeMs||me>st+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let zt=Math.min(nt-me,pe.maxControlAgeSeconds*1e3,sn.maxControlAgeMs)-Math.max(un,st-me,0)-(Pr()-J);if(zt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Pr()+zt}function ft(){if(clearTimeout(y),clearTimeout(A),m||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?ft():ye()},Math.max(1,u-Pr())),Wy(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Xt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),Wy(y)}async function Xt(){if(m)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=h,J=new AbortController;R=J;let pe=(async()=>{if(!le){le=!0;try{let ea=await s.readManifest();if(ea&&!c){let Qn=Qu.parse(JSON.parse(ea));_t(Qn.scope)===_t(t)&&(c=Qn)}}catch{}}J.signal.throwIfAborted();let Ke=c,un=Pr(),Kt=await Yo(a,J.signal);Kt.status===304&&(!Ke||!Kt.headers.has("x-indiana-config-validated-at")||!Kt.headers.has("x-indiana-config-valid-until")||!Kt.headers.has("age"))&&(Kt=await Yo(a,J.signal));let zt=Kt.status===304?Ke:Qu.parse(JSON.parse(await Ne(Kt,sn.maxManifestBytes,J.signal))),{generation:oi,...ai}=zt,Hn=Kt.headers.get("etag");if(_t(zt.scope)!==_t(t)||jh(ai)!==oi||Hn!==`"${oi}"`&&Hn!==`W/"${oi}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(zt.revision<Ke.revision||zt.revision===Ke.revision&&zt.generation!==Ke.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ea,Qn]of Object.entries(Ke?.funnels??{})){let Rr=zt.funnels[ea];if(Rr&&(Rr.controlRevision<Qn.controlRevision||Rr.evaluationRevision<Qn.evaluationRevision||Rr.controlRevision===Qn.controlRevision&&Rr.state!==Qn.state||Rr.evaluationRevision===Qn.evaluationRevision&&Rr.evaluationMode!==Qn.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let Er=ii(Kt,un,zt.policy);if(J.signal.throwIfAborted(),Y!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=zt,u=Er,l=Date.now()+Math.max(0,Er-Pr()),p=!1,d=0,x=0,s.writeManifest(_t(zt)),ye(),structuredClone(zt)})(),me=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs),nt=new Promise((Ke,un)=>J.signal.addEventListener("abort",()=>un(J.signal.reason),{once:!0})),st=Promise.race([pe,nt]).catch(Ke=>{throw d++,(Ke instanceof Sw.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,p=!0,ye()),Ke}).finally(()=>{clearTimeout(me),g===st&&(g=void 0),ft()});return g=st,st}async function Cr(Y){let J=Y.sha256,pe=ai=>Vs(ai,Y);it(Y.url);let me=j.get(J);if(me){if(me.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,me),me.text}let nt=_.get(J);if(nt){if(nt.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return nt.promise}let st=new AbortController;C.add(st);let Ke=h,un=(async()=>{try{let Er=await s.readArtifact(J);if(Er&&pe(Er)){if(st.signal.throwIfAborted(),m||Ke!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Ye(J,Er,Y.byteLength),Er}}catch{}st.signal.throwIfAborted();let ai=await Yo(Y.url,st.signal,!0),Hn=await Ne(ai,Y.byteLength,st.signal);if(!pe(Hn))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||Ke!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Ye(J,Hn,Y.byteLength),s.writeArtifact(J,Hn),Hn})(),Kt=setTimeout(()=>st.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),sn.initializationMs),zt=new Promise((ai,Hn)=>st.signal.addEventListener("abort",()=>Hn(st.signal.reason),{once:!0})),oi=Promise.race([un,zt]).finally(()=>{clearTimeout(Kt),C.delete(st),_.delete(J)});return _.set(J,{promise:oi,byteLength:Y.byteLength}),oi}async function _r(){return Se()||await Xt(),At(),c}async function Qi(Y){let J,pe=new Promise((me,nt)=>{J=setTimeout(()=>nt(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs)});try{return await Promise.race([Y(),pe])}finally{clearTimeout(J)}}function Ji(Y,J){if(At(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function zl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let pe=Y.artifacts[J];if(pe.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let me=Au.parse(JSON.parse(await Cr(pe)));if(_t(me.scope)!==_t({projectId:t.projectId,environment:t.environment})||me.generation!==pe.generation||me.remoteFeatures.some(nt=>Object.hasOwn(me.features,nt)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ji(Y),{...me,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Pr())).toISOString()}}async function $l(Y,J){let pe=await _r(),me=pe.funnels[Y];J&&(!me||me.evaluationMode==="local"&&!me.versions[J])&&(g&&await g,pe=await Xt()),Ji(pe,Y);let nt=pe.funnels[Y];if(nt.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let st=J??nt.currentVersionId,Ke=nt.versions[st];if(!Ke)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(pe.artifacts[Ke.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[un,Kt]=await Promise.all([Cr(pe.artifacts[Ke.artifact]).then(zt=>Nh(JSON.parse(zt))),nt.evaluationMode==="local"?zl(pe):void 0]);if(Kt&&_t(Th(un,Kt))!==_t(Ke.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ji(pe,Y),{document:un,growth:Kt,versionId:st,control:structuredClone(nt),manifest:structuredClone(pe)}}async function Gl(Y,J){try{return await $l(Y,J)}catch(pe){if(!(pe instanceof b)||!(pe.code==="CONFIGURATION_CHANGED"||pe.code==="CONFIGURATION_HTTP_404"&&Se()))throw pe;let me=c?.generation;if(g&&await g,await Xt(),pe.code!=="CONFIGURATION_CHANGED"&&c?.generation===me)throw pe;return $l(Y,J)}}function $s(){p=!0,ye(),Xt().catch(ke)}let Xo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&$s()};function Yy(Y){if(m)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",$s),window.addEventListener("focus",Xo),document.addEventListener("visibilitychange",Xo)),ft()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Kl())}}function Kl(){typeof window<"u"&&(window.removeEventListener("online",$s),window.removeEventListener("focus",Xo),document.removeEventListener("visibilitychange",Xo))}return{scope:Object.freeze({...t}),refresh:Xt,subscribe:Yy,assertFresh:At,assertFeatures(Y){At();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-Pr()):0},async features(){return Qi(async()=>zl(await _r()))},pageExperiments:()=>Qi(async()=>{let Y=await _r(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let pe=Y.artifacts[J];if(pe.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let me=Lg.parse(JSON.parse(await Cr(pe)));if(me.environmentId!==t.environmentId||me.generation!==pe.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Ji(Y),me}),funnel:(Y,J)=>Qi(()=>Gl(Y,J)),paywall:(Y,J)=>Qi(async()=>{let pe=await _r(),me=pe.paywalls?.[Y];if(!me||!J&&me.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let nt=J??me.currentVersionId,st=me.versions[nt],Ke=st&&pe.artifacts[st.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let un=Os.parse(JSON.parse(await Cr(Ke)));return Ji(pe),{document:un,versionId:nt,version:st.version,control:structuredClone(me),manifest:structuredClone(pe)}}),async localFunnel(Y,J){let pe=await Qi(()=>Gl(Y,J));if(!pe.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:me,remoteFeatures:nt,...st}=pe.growth;return Bg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:pe.versionId,evaluationMode:"local",evaluationRevision:pe.control.evaluationRevision,document:pe.document,payload:st})},assertFunnel(Y,J,pe){At();let me=c.funnels[Y];if(!me||me.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(me.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&me.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(pe!==void 0&&!me.versions[pe])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Kl(),ye(),v.clear();for(let Y of C)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function vw(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&_t(n)!==_t(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Hi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=Bs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Or({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function Ll(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function ww(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(m){let h,d=new Promise((g,R)=>{h=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),d])}finally{clearTimeout(h)}}function c(m){throw m instanceof b&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),m}function u(m,h){if(h!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=ml.parse(m);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)Ll(j,d.run);d.run.instruction?.type==="authentication_required"&&Ll(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:g,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,C=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:g.binding!==null,instruction:R?.type==="authentication_required"?null:R},...C?{settlement:C}:{}}}let l=m=>(a.has(m)||a.set(m,t?.run.identity.binding?.id??null),a.get(m));async function p(m){let h=r,d=t?.run.identity.binding?.id??null,g=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(m.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(g)}let R;if(m.operation==="get"){let{operation:y,customerToken:A,...x}=m;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(g)}else if(m.operation==="review")R=await s(()=>e.adapter.review(m.receiptId)).catch(g);else{if(m.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=m;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(g)}}return u(R,h)}return{get view(){return t?.run??null},get controller(){return n},async open(m){let h=r,d=await s(()=>e.adapter.open(m)).catch(c);if(u(d,h),!n){n=Or({...e,runToken:d.runToken,process:{request:p,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let g=n,R=g.submit;g.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await g.settle?.(y.requestId),await g.get();let x=g.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let g of n.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(g.requestId);return{run:t.run,controller:n}},async syncIdentity(){let m=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),m),await n?.get();for(let h of n?.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(h.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(m){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:m}},subscribe(m){return i.add(m),()=>{i.delete(m)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,Iw as createConfigurationSync,Ul as createFeatureClient,ww as createFunnelProcess,vw as createLocalFunnelClient,yw as createLongplayReactNative};