@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.cjs
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.z.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"})}),Et=N.z.record(N.z.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"})}),Tb=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=Et.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.z.strictObject({id:N.z.uuid(),attributeKey:N.z.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("$")&&!Tb.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)}),Nb=N.z.discriminatedUnion("type",[N.z.strictObject({type:N.z.literal("condition"),condition:nn}),N.z.strictObject({type:N.z.literal("list"),attributeKey:N.z.string().min(1).max(128),values:N.z.array(N.z.union([N.z.string(),N.z.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 Xn(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 Db=N.z.record(N.z.uuid(),Nb).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"&&Xn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Dc=N.z.tuple([N.z.number().min(0).max(1),N.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Ep=N.z.strictObject({attribute:N.z.string().optional(),seed:N.z.string().min(1),hashVersion:N.z.literal(2),ranges:N.z.array(Dc).min(1).max(100)}),Fb=N.z.strictObject({id:N.z.string().min(1).max(128),condition:nn,gate:N.z.boolean().optional()}),Nc={id:N.z.string().max(128).optional(),condition:nn.optional(),parentConditions:N.z.array(Fb).max(50).optional(),filters:N.z.array(Ep).max(20).optional()},Mb=N.z.union([N.z.strictObject({...Nc}),N.z.strictObject({...Nc,force:ve,coverage:N.z.number().min(0).max(1).optional(),range:Dc.optional(),seed:N.z.string().min(1).optional(),hashAttribute:N.z.string().optional(),hashVersion:N.z.literal(2).optional()}),N.z.strictObject({...Nc,type:N.z.literal("experiment-ref"),experimentId:N.z.uuid(),values:N.z.record(N.z.string().min(1),ve),meta:N.z.record(N.z.string().min(1),N.z.strictObject({passthrough:N.z.boolean()})).optional()})]),qb=N.z.strictObject({defaultValue:ve,rules:N.z.array(Mb).max(100)}),FP=N.z.record(N.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),qb).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)}),Ub=N.z.strictObject({name:N.z.string().max(80),reason:N.z.string().max(500),dateStarted:N.z.iso.datetime({offset:!0}),dateEnded:N.z.iso.datetime({offset:!0}).nullable(),coverage:N.z.number().min(0).max(1),variationWeights:N.z.array(N.z.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.z.array(N.z.strictObject({match:N.z.enum(["any","all","none"]),ids:N.z.array(N.z.uuid()).min(1)})).max(50),namespace:N.z.strictObject({id:N.z.uuid(),ranges:N.z.array(Dc).min(1)}).nullable(),seed:N.z.string().min(1).max(128)}),Bb=N.z.strictObject({key:N.z.string().min(1).max(128),name:N.z.string().min(1).max(80),hypothesis:N.z.string().max(2e3),status:N.z.enum(["draft","running","stopped"]),hashAttribute:N.z.string().min(1).max(128),fallbackAttribute:N.z.string().max(128).nullable(),hashVersion:N.z.literal(2),disableStickyBucketing:N.z.boolean(),bucketVersion:N.z.number().int().min(0).max(1e3),minBucketVersion:N.z.number().int().min(0).max(1e3),variations:N.z.array(N.z.strictObject({id:N.z.string().min(1),key:N.z.string().min(1),name:N.z.string().max(80),description:N.z.string().max(500)})).min(2).max(20),phases:N.z.array(Ub).min(1).max(100),releasedVariationId:N.z.string().nullable(),excludeFromPayload:N.z.boolean(),statusSchedule:N.z.strictObject({startAt:N.z.iso.datetime({offset:!0}).nullable(),stopAt:N.z.iso.datetime({offset:!0}).nullable(),stopAfter:N.z.strictObject({value:N.z.number().int().positive().max(36500),unit:N.z.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 Vb=Bb.safeExtend({filters:N.z.array(Ep).optional()}),Lb=N.z.strictObject({experiments:N.z.record(N.z.uuid(),Vb),savedGroups:Db}),mo=N.z.strictObject({attributeName:N.z.string(),attributeValue:N.z.string(),assignments:N.z.record(N.z.string(),N.z.string())}),MP=N.z.strictObject({snapshot:Lb,attributes:Et,results:Et,stickyBucketAssignmentDocs:N.z.record(N.z.string(),mo)}),qP=N.z.strictObject({variantKey:N.z.string().nullable(),bucketVersion:N.z.number().int().min(0),source:N.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.z.number().min(0).max(1).optional(),stickyBucketUsed:N.z.boolean().optional(),hashUsed:N.z.boolean().optional()});function pr(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 zb=Nt.z.enum(["active","inactive"]),$b=Nt.z.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},Et),Gb=Nt.z.strictObject({id:Nt.z.string().trim().min(1).max(255),name:Nt.z.string().trim().min(1).max(255),status:zb,metadata:$b}),zP=Gb.extend({internal_id:Nt.z.uuid(),project_id:Nt.z.uuid(),environment_id:Nt.z.uuid(),created_at:Nt.z.iso.datetime({offset:!0}),updated_at:Nt.z.iso.datetime({offset:!0})}),kp=Nt.z.union([Nt.z.strictObject({id:Nt.z.string().trim().min(1).max(255)}),Nt.z.strictObject({internalId:Nt.z.uuid()})]),$P=Nt.z.enum(["customer","merchandise","context"]),GP=Nt.z.enum(["system","stored","request"]),KP=Nt.z.enum(["customer","merchandise","mixed"]),Rp=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Fc(e,t={},n=new Set){if(pr(e).some(Rp))return!0;for(let r of Xn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Rp(i.attributeKey)||i?.type==="condition"&&Fc(i.condition,t,n))return!0}return!1}var jp=require("zod"),Kb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,En=jp.z.string().max(16).regex(Kb,"\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 YP=ee.z.enum(["draft","active","paused","archived"]),mr=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("percent"),percentOff:ee.z.number().min(1).max(100).multipleOf(.01)}).strict(),ee.z.object({type:ee.z.literal("amount"),amountOffCents:ee.z.number().int().min(1).max(1e8),currency:Ie}).strict()]),mn=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("once")}).strict(),ee.z.object({type:ee.z.literal("repeating"),months:ee.z.number().int().min(1).max(36)}).strict(),ee.z.object({type:ee.z.literal("forever")}).strict()]),Tp=[ee.z.object({type:ee.z.literal("all")}).strict(),ee.z.object({type:ee.z.literal("plans"),planIds:ee.z.array(ee.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Hb=ee.z.discriminatedUnion("type",[...Tp,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.discriminatedUnion("type",[ee.z.strictObject({type:ee.z.literal("all")}),ee.z.strictObject({type:ee.z.literal("selected"),merchandiseIds:ee.z.array(ee.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),ee.z.strictObject({type:ee.z.literal("condition"),condition:nn})])})]),Mc=ee.z.discriminatedUnion("type",[...Tp,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.strictObject({type:ee.z.enum(["all","selected","condition"])})})]),Qb=ee.z.strictObject({firstPurchaseOnly:ee.z.boolean(),condition:nn}),XP=ee.z.object({name:ee.z.string().trim().min(1).max(80),description:ee.z.string().max(500),discount:mr,duration:mn,appliesTo:Hb,eligibility:Qb,selfClaimEnabled:ee.z.boolean().default(!1),startsAt:ee.z.iso.datetime().nullable(),endsAt:ee.z.iso.datetime().nullable(),totalLimit:ee.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ee.z.number().int().min(1).max(10),grantWindowHours:ee.z.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=>!Fc(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"]}),eC=ee.z.object({code:ee.z.string().trim().transform(e=>e.toUpperCase()).pipe(ee.z.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:ee.z.number().int().min(1).max(1e6).nullable(),expiresAt:ee.z.iso.datetime().nullable(),firstPurchaseOnly:ee.z.boolean(),minimumAmountCents:ee.z.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 fo=ee.z.object({id:ee.z.uuid(),couponId:ee.z.uuid(),status:ee.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ee.z.iso.datetime(),expiresAt:ee.z.iso.datetime(),coupon:ee.z.object({name:ee.z.string(),discount:mr,duration:mn,appliesTo:Mc}).strict()}).strict(),Np=ee.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Up=S.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),qc=S.z.string().regex(/^(0|[1-9]\d{0,14})$/),vi=S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Jb=S.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),ho=Jb,er=de.refine(e=>/[1-9]/.test(e)),Zt=S.z.iso.datetime({offset:!0}),Da=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"))},Zb=S.z.array(S.z.object({upTo:er.nullable(),unitAmountMinor:Up,flatAmountMinor:S.z.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&&Da(t.upTo)>Da(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Wb=S.z.discriminatedUnion("kind",[S.z.object({kind:S.z.literal("flat"),units:er,unitAmountMinor:Up}).strict(),S.z.object({kind:S.z.enum(["graduated","volume"]),units:er,tiers:Zb}).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"),Yb=S.z.strictObject({interval:S.z.enum(["month","year"]),count:S.z.number().int().min(1).max(12),anchor:S.z.enum(["membership","calendar"])}),go=S.z.object({currency:Ie,pricing:Wb,billingCycle:Yb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Dp={requestId:S.z.uuid(),productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},Bp=S.z.strictObject({interval:S.z.enum(["hour","day","week","month"]),intervalCount:S.z.number().int().min(1).max(12),limit:S.z.number().int().min(1).max(1e6)}),Vp=S.z.discriminatedUnion("kind",[S.z.object({...Dp,kind:S.z.literal("auto_topup"),threshold:ha,quantity:er.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Bp.optional()}).strict(),S.z.object({...Dp,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:ho,maxOutstandingMinor:ho}).strict()]),Fp={productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},Lp=S.z.discriminatedUnion("kind",[S.z.object({...Fp,kind:S.z.literal("auto_topup"),threshold:ha,quantity:er.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Bp.optional(),purchaseAmountMinor:ho,purchaseUnits:er}).strict(),S.z.object({...Fp,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:ho,maxOutstandingMinor:ho,cashPrice:go}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Fa=S.z.object({id:S.z.uuid(),terms:Lp,status:S.z.enum(["prepared","active","revoked","blocked"]),createdAt:Zt,acceptedAt:Zt.nullable(),effectiveAt:Zt.nullable(),revokedAt:Zt.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"),zp=S.z.object({authorizationId:S.z.uuid(),terms:Lp,setupUrl:S.z.url().nullable()}).strict(),$p=S.z.object({authorizationId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),Gp=S.z.object({authorizationId:S.z.uuid(),requestId:S.z.uuid()}).strict(),Kp=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:_t.optional(),limit:de.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.z.array(er).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&&Da(t)>Da(i)}),"Notification thresholds must increase"),Xb=Kp.safeExtend({requestId:S.z.uuid()}),Mp={control:S.z.literal("overage"),requestId:S.z.uuid(),internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable()},ex=S.z.discriminatedUnion("action",[S.z.strictObject({...Mp,action:S.z.literal("set"),allowed:S.z.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.z.boolean()}),S.z.strictObject({...Mp,action:S.z.literal("remove")})]),Hp=S.z.union([Xb,ex]),tx=S.z.strictObject({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),allowed:S.z.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.z.boolean(),interval:S.z.enum(["day","week","month","year"]),startsAt:Zt,endsAt:Zt,used:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),nx=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:_t.optional(),startsAt:Zt,endsAt:Zt,used:tn,reserved:tn,limit:de.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),notifiedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),includedAllowance:S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.z.array(er).max(8).optional(),notifiedAbsoluteThresholds:S.z.array(er).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"),rx=S.z.object({authorizationId:S.z.uuid(),status:S.z.enum(["idle","pending","blocked"]),taskId:S.z.uuid().nullable(),invoiceId:S.z.uuid().nullable(),hostedInvoiceUrl:S.z.url().nullable(),purchaseCount:S.z.number().int().nonnegative(),purchaseWindowEndsAt:Zt.nullable(),attemptCount:S.z.number().int().nonnegative(),failedAttemptCount:S.z.number().int().nonnegative(),suspendedAt:Zt.nullable(),nextAttemptAt:Zt.nullable(),failureReason:S.z.string().min(1).max(240).nullable()}).strict(),Qp=S.z.object({internal_feature_id:S.z.uuid().optional(),entityId:S.z.uuid().optional()}).strict(),Uc=S.z.object({authorizations:S.z.array(Fa).max(100),limits:S.z.array(Kp).max(100),overages:S.z.array(tx).max(100).optional(),windows:S.z.array(nx).max(200),autoTopups:S.z.array(rx).max(100),limited:S.z.boolean()}).strict(),ix=S.z.object({id:S.z.uuid(),internal_feature_id:S.z.uuid(),productVersionId:S.z.uuid(),authorizationId:S.z.uuid(),entityId:S.z.uuid().nullable(),units:de,amountMinor:vi,cashPrice:go}).strict(),yo=S.z.object({id:S.z.uuid(),sourceKind:S.z.enum(["product","usage","manual"]),providerInvoiceId:S.z.string().min(1).max(240).nullable(),status:S.z.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Zt.nullable(),endsAt:Zt.nullable(),amountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:qc,paidAmountMinor:qc,refundedAmountMinor:qc,createdAt:Zt,hostedInvoiceUrl:S.z.url().nullable(),adjustment:S.z.object({originalInvoiceId:S.z.uuid(),amountMinor:S.z.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:Zt.nullable(),reason:S.z.string().min(1).max(500).optional()}).strict().nullable(),lines:S.z.array(ix).max(100),linesLimited:S.z.boolean()}).strict(),Jp=S.z.object({invoiceId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),Zp=S.z.strictObject({requestId:S.z.uuid(),originalInvoiceId:S.z.uuid(),amountMinor:S.z.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.z.string().trim().min(1).max(500)}),Wp=S.z.object({after:S.z.uuid().nullable(),limit:S.z.number().int().min(1).max(100)}).strict(),Yp=S.z.object({rows:S.z.array(yo).max(100),nextCursor:S.z.uuid().nullable()}).strict(),qp=S.z.strictObject({id:S.z.string(),coupon:S.z.string(),start:S.z.number().nonnegative(),end:S.z.number().nullable()}),ox=S.z.strictObject({subscriptionId:S.z.string(),customerId:S.z.string(),accountId:S.z.string(),sourceItems:S.z.array(S.z.strictObject({id:S.z.string(),price_id:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(qp).optional()})).max(100),items:S.z.array(S.z.strictObject({id:S.z.string(),price:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(S.z.strictObject({coupon:S.z.string().optional(),terms:S.z.strictObject({id:S.z.string(),name:S.z.string().optional(),percent_off:S.z.number().optional(),amount_off:S.z.number().optional(),currency:S.z.string().optional(),duration:S.z.enum(["once","forever","repeating"]),duration_in_months:S.z.number().optional()}).optional(),discount:S.z.string().optional(),receipt:qp.optional()})).max(20)})).max(100)}),Xp=S.z.strictObject({membershipId:S.z.uuid(),requestId:S.z.uuid(),grantIds:S.z.array(S.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),em=S.z.strictObject({membershipId:S.z.uuid(),operationId:S.z.uuid(),status:S.z.enum(["pending","effective"]),execution:ox.nullable(),grants:S.z.array(S.z.strictObject({id:S.z.uuid(),couponId:S.z.uuid(),name:S.z.string(),discount:mr,duration:mn,startedAt:Zt.nullable()})).max(20)});var wi=require("zod");var tm=wi.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),nm=wi.z.number().int().min(1).max(1e3),Ma=wi.z.object({cap:de.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:wi.z.number().positive().max(1e4).nullable(),cycles:wi.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var tr=require("zod");var rm=tr.z.strictObject({itemKey:tr.z.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:tr.z.uuid(),includedAmount:tr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:tr.z.number().int().min(0).max(1e4),terms:Ca,pricing:uo.optional(),unitAmountMinor:tr.z.number().int().min(0).max(1e8),productId:tr.z.string().min(1).max(255).nullable(),priceId:tr.z.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{rp(e.includedAmount,e.terms.units,e.quantity),Pa({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"})}});var te=require("zod");var Gr=de.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Ao=te.z.string().min(1).max(120),qa=te.z.enum(["cap","overflow"]),fn=(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"))},bo=e=>{try{return e()}catch{return!1}},xo=te.z.discriminatedUnion("operation",[te.z.object({operation:te.z.literal("quote"),overageBehavior:qa.optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Gr,properties:_t}).strict(),te.z.object({operation:te.z.literal("consume"),overageBehavior:qa.optional(),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:de,properties:_t,idempotencyKey:Ao}).strict(),te.z.object({operation:te.z.literal("reserve"),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Gr,properties:_t,idempotencyKey:Ao,expiresInSeconds:te.z.number().int().min(1).max(86400)}).strict(),te.z.object({operation:te.z.literal("confirm"),operationId:te.z.uuid(),quantity:Gr,properties:_t.optional(),idempotencyKey:Ao}).strict(),te.z.object({operation:te.z.literal("refund"),operationId:te.z.uuid(),quantity:Gr,idempotencyKey:Ao}).strict(),te.z.object({operation:te.z.literal("release"),operationId:te.z.uuid(),idempotencyKey:Ao}).strict()]),Bc=te.z.object({internal_credit_feature_id:te.z.uuid().nullable(),internal_metered_feature_id:te.z.uuid(),dimension:te.z.string().min(1).max(64),counterKey:te.z.string().min(1).max(240),cycleStart:te.z.iso.datetime({offset:!0}),unitCost:de,units:Gr,amount:tn,tier:te.z.number().int().min(1).max(12).nullable()}).strict(),Kr=te.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function im(e,t){let n=e.reduce((r,i)=>r+fn(i.units,12),0n)-fn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var om=te.z.discriminatedUnion("funding",[te.z.strictObject({funding:te.z.literal("balance"),sourceId:te.z.uuid(),rolloverId:te.z.uuid().nullable(),units:Kr.refine(e=>/[1-9]/.test(e)),amount:tn}),te.z.strictObject({funding:te.z.literal("unbilled"),units:Kr.refine(e=>/[1-9]/.test(e))}),te.z.object({funding:te.z.literal("prepaid"),sourceId:te.z.uuid(),units:Gr,amount:tn,pricing:te.z.array(Bc).min(1).max(12)}).strict().refine(e=>bo(()=>e.pricing.reduce((t,n)=>t+fn(n.units,6),0n)===fn(e.units,6)&&e.pricing.reduce((t,n)=>t+fn(n.amount,12),0n)===fn(e.amount,12)&&e.pricing.every(t=>fn(t.unitCost,6)*fn(t.units,6)===fn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),te.z.object({funding:te.z.literal("postpaid"),invoiceLineId:te.z.uuid().nullable(),units:Gr,authorizationId:te.z.uuid()}).strict()]),Ua=te.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),am=te.z.object({allowed:te.z.boolean(),internal_feature_id:te.z.uuid(),quantity:de,requestedQuantity:de.optional(),overageBehavior:qa.optional(),reason:Ua.nullable(),allocations:te.z.array(om).max(500)}).strict().refine(e=>bo(()=>e.allowed?e.reason===null&&im(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>bo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&fn(e.requestedQuantity,6)>=fn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),So=te.z.object({id:te.z.uuid(),internal_feature_id:te.z.uuid(),kind:te.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:te.z.uuid().nullable(),quantity:de,requestedQuantity:de.optional(),overageBehavior:qa.optional(),accepted:te.z.boolean(),reason:te.z.enum([...Ua.options,"expired"]).nullable(),createdAt:te.z.iso.datetime({offset:!0}),reservationStatus:te.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:te.z.iso.datetime({offset:!0}).nullable(),allocations:te.z.array(om).max(500)}).strict().refine(e=>bo(()=>e.accepted?e.reason===null&&im(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>bo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&fn(e.requestedQuantity,6)>=fn(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");var Ne=require("zod");var Hr=Ne.z.iso.datetime({offset:!0}),sm=de.refine(e=>/[1-9]/.test(e)),cm=Ne.z.strictObject({interval:tm.exclude(["lifetime"]),count:nm}),ax=Ne.z.strictObject({action:Ne.z.literal("create"),requestId:Ne.z.uuid(),internal_feature_id:Ne.z.uuid(),entityId:Ne.z.uuid().nullable(),amount:sm.nullable(),expiresAt:Hr.nullable(),reset:cm.nullable(),rollover:Ma.nullable(),nextResetAt:Hr.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"),um=Ne.z.discriminatedUnion("action",[ax,Ne.z.strictObject({action:Ne.z.literal("update"),requestId:Ne.z.uuid(),grantId:Ne.z.uuid(),revision:Ne.z.number().int().nonnegative(),amount:sm.nullable(),expiresAt:Hr.nullable(),rollover:Ma.nullable(),nextResetAt:Hr.nullable()}),Ne.z.strictObject({action:Ne.z.enum(["add","subtract","set_remaining"]),requestId:Ne.z.uuid(),grantId:Ne.z.uuid(),revision:Ne.z.number().int().nonnegative(),amount:de}),Ne.z.strictObject({action:Ne.z.literal("revoke"),requestId:Ne.z.uuid(),grantId:Ne.z.uuid(),revision:Ne.z.number().int().nonnegative()})]),Vc=Ne.z.strictObject({id:Ne.z.uuid(),internal_feature_id:Ne.z.uuid(),entityId:Ne.z.uuid().nullable(),amount:de.nullable(),reset:cm.nullable(),rollover:Ma.nullable(),nextResetAt:Hr.nullable(),startsAt:Hr,expiresAt:Hr.nullable(),revision:Ne.z.number().int().nonnegative(),revoked:Ne.z.boolean(),available:tn,held:tn,spent:tn}),lm=Ne.z.strictObject({customerId:Ne.z.uuid(),after:Ne.z.uuid().nullable(),limit:Ne.z.number().int().min(1).max(100)}),dm=Ne.z.strictObject({rows:Ne.z.array(Vc).max(100),nextCursor:Ne.z.uuid().nullable()});var ie=require("zod");var Bn=ie.z.iso.datetime({offset:!0}),pm=ie.z.strictObject({invoiceId:ie.z.uuid(),after:ie.z.string().min(1).max(180).nullable(),limit:ie.z.number().int().min(1).max(100)}),sx=ie.z.strictObject({kind:ie.z.literal("product"),key:ie.z.string(),productVersionId:ie.z.uuid(),productName:ie.z.string(),itemKey:ie.z.string(),entityId:ie.z.uuid().nullable(),quantity:ie.z.number().positive(),subtotalMinor:ie.z.string().regex(/^-?\d+$/),discountMinor:ie.z.string().regex(/^\d+$/),taxMinor:ie.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.z.string().regex(/^-?\d+$/),startsAt:Bn.nullable(),endsAt:Bn.nullable(),providerLineId:ie.z.string().nullable(),providerItemId:ie.z.string()}),mm=ie.z.strictObject({invoice:yo,items:ie.z.array(ie.z.discriminatedUnion("kind",[sx,ie.z.strictObject({kind:ie.z.literal("invoice_credit"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),units:de,reserved:de,amountMinor:vi,grossAmountMinor:vi,creditsAppliedMinor:vi,properties:_t,cashPrice:go,providerItemId:ie.z.string().nullable(),creditProviderItemId:ie.z.string().nullable()}),ie.z.strictObject({kind:ie.z.literal("usage"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),name:ie.z.string(),units:de,reserved:de,amountMinor:vi,cashPrice:go})])).max(100),nextCursor:ie.z.string().min(1).max(180).nullable()}),cx=ie.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Lc=ie.z.strictObject({from:Bn,to:Bn,entityId:ie.z.uuid().optional(),snapshotAt:Bn.nullable(),after:ie.z.strictObject({at:Bn,id:ie.z.uuid(),position:ie.z.number().int().nonnegative()}).nullable(),limit:ie.z.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"),fm=ie.z.strictObject({customerId:ie.z.uuid(),entityId:ie.z.uuid().nullable(),from:Bn,to:Bn,snapshotAt:Bn,totals:ie.z.array(ie.z.strictObject({internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),consumed:tn,refunded:tn,net:cx})).max(1e3),rows:ie.z.array(ie.z.strictObject({operationId:ie.z.uuid(),position:ie.z.number().int().nonnegative(),kind:ie.z.enum(["consume","confirm","refund"]),originalId:ie.z.uuid().nullable(),occurredAt:Bn,internal_feature_id:ie.z.uuid(),entitlementName:ie.z.string(),sourceId:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),creditName:ie.z.string(),units:Kr,amount:tn,pricing:ie.z.array(Bc).max(12),properties:_t})).max(100),nextCursor:Lc.shape.after});var D=require("zod");var Sn=require("zod");var ux=Sn.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),lx=Sn.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Ba=Sn.z.strictObject({internal_feature_id:Sn.z.uuid(),entityId:Sn.z.uuid().nullable()}),hm=Ba.extend({quantity:de,expectedRevision:Sn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:Sn.z.string().min(1).max(120),properties:_t.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Io=Ba.extend({operationId:Sn.z.uuid().nullable(),usage:de,capacity:ux.nullable(),remaining:lx.nullable(),withinLimit:Sn.z.boolean(),revision:Sn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Sn.z.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 Wt=D.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Rn=D.z.iso.datetime({offset:!0}),dx=D.z.enum(["access","metered","credit"]),vo={internal_feature_id:D.z.uuid(),key:qr,name:D.z.string().min(1).max(120),kind:dx},gm=D.z.object({customerId:D.z.uuid(),snapshotAt:Rn,memberships:D.z.array(D.z.object({id:D.z.uuid(),productId:D.z.string().min(1).max(255),productVersionId:D.z.uuid(),billingProductVersionId:D.z.uuid(),version:D.z.number().int().positive(),key:D.z.string().min(1).max(64),name:D.z.string().min(1).max(120),groupId:D.z.string().max(255).nullable(),membershipType:D.z.enum(["main","addon"]),status:D.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.z.boolean(),accessEnabled:D.z.boolean(),renewalChange:D.z.object({productVersionId:D.z.uuid(),name:D.z.string().min(1).max(120),version:D.z.number().int().positive(),effectiveAt:Rn,benefitsAppliedAt:Rn.nullable(),timing:D.z.enum(["immediate","renewal"]),changeKind:D.z.enum(["plan","seats","quantity"]),feature:D.z.strictObject({internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(80),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).optional(),seat:D.z.object({key:D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).strict().nullable(),status:D.z.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.z.object({phase:D.z.enum(["paid","trial"]),startsAt:Rn,endsAt:Rn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.z.boolean(),balances:D.z.array(D.z.object({...vo,usageType:D.z.enum(["consumable","non_consumable"]).nullable(),accessible:D.z.boolean(),unlimited:D.z.boolean(),available:Wt,held:Wt,debt:Wt,nextExpiresAt:Rn.nullable(),usage:Io.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.z.boolean()}).strict(),ym=D.z.enum(["source","usage","transaction","invoice","debt","settlement"]),Va=D.z.object({at:Rn,id:D.z.uuid(),type:ym}).strict(),Am=D.z.object({type:ym.nullable(),resourceKey:qr.optional(),kind:D.z.enum(["purchase","refund"]).optional(),topup:D.z.boolean().optional(),from:D.z.iso.date().nullable(),to:D.z.iso.date().nullable(),after:Va.nullable(),limit:D.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Oi={id:D.z.uuid(),occurredAt:Rn},px=D.z.discriminatedUnion("type",[D.z.strictObject({...Oi,type:D.z.literal("invoice"),status:D.z.string().min(1).max(80),paid:Wt,refunded:Wt,currency:Ie,externalId:D.z.string().nullable()}),D.z.object({...Oi,...vo,type:D.z.literal("source"),reason:D.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Wt,unlimited:D.z.boolean(),status:D.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Rn,expiresAt:Rn.nullable(),orderId:D.z.uuid().nullable(),parentSourceId:D.z.uuid().nullable()}).strict(),D.z.object({...Oi,type:D.z.literal("usage"),internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(120),kind:D.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.z.uuid().nullable(),quantity:de,accepted:D.z.boolean(),reason:D.z.enum([...Ua.options,"expired"]).nullable(),properties:_t,reservationStatus:D.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Rn.nullable(),charges:D.z.array(D.z.discriminatedUnion("funding",[D.z.strictObject({funding:D.z.literal("balance"),sourceId:D.z.uuid(),rolloverId:D.z.uuid().nullable(),units:Kr,amount:Wt}),D.z.strictObject({funding:D.z.literal("unbilled"),units:Kr}),D.z.object({...vo,funding:D.z.literal("prepaid"),amount:Wt}).strict(),D.z.object({funding:D.z.literal("postpaid"),invoiceId:D.z.uuid(),invoiceLineId:D.z.uuid(),authorizationId:D.z.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.z.object({...Oi,type:D.z.literal("transaction"),purpose:D.z.enum(["product","invoice"]),productVersionId:D.z.uuid().nullable(),productName:D.z.string().min(1).max(120).nullable(),productVersion:D.z.number().int().positive().nullable(),invoiceId:D.z.uuid().nullable(),orderId:D.z.uuid(),originalId:D.z.uuid().nullable(),kind:D.z.enum(["purchase","refund"]),amountMinor:D.z.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.z.object({...Oi,...vo,type:D.z.literal("debt"),sourceId:D.z.uuid(),transactionId:D.z.uuid(),amount:Wt}).strict(),D.z.object({...Oi,...vo,type:D.z.literal("settlement"),sourceId:D.z.uuid(),debtId:D.z.uuid(),kind:D.z.enum(["payment","usage_refund","payment_return"]),amount:Wt}).strict()]),bm=D.z.object({customerId:D.z.uuid(),rows:D.z.array(px).max(50),nextCursor:Va.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");var he=require("zod"),Sm=he.z.object({customerId:he.z.uuid()}).strict(),Im=he.z.discriminatedUnion("action",[he.z.object({customerId:he.z.uuid(),requestId:he.z.uuid(),action:he.z.literal("assign"),poolId:he.z.uuid(),memberCustomerId:he.z.uuid()}).strict(),he.z.strictObject({customerId:he.z.uuid(),requestId:he.z.uuid(),action:he.z.literal("assign_entity"),poolId:he.z.uuid(),entityId:he.z.uuid()}),he.z.object({customerId:he.z.uuid(),requestId:he.z.uuid(),action:he.z.literal("release"),poolId:he.z.uuid(),slotId:he.z.uuid()}).strict()]),wo=he.z.number().int().nonnegative(),zc=he.z.iso.datetime({offset:!0}),$c=he.z.strictObject({internalId:he.z.uuid(),id:he.z.string(),name:he.z.string().nullable(),version:he.z.number().int().positive()}),xm=he.z.enum(["active","past_due"]),Gc=he.z.strictObject({customerId:he.z.uuid(),licenses:he.z.array(he.z.strictObject({id:he.z.uuid(),linkId:he.z.uuid(),parent:he.z.strictObject({customerProductId:he.z.uuid(),status:xm,product:$c}),product:$c,planLicense:he.z.strictObject({id:he.z.uuid(),prepaidOnly:he.z.boolean(),isCustom:he.z.boolean()}).nullable(),granted:wo,included:wo,paidQuantity:wo,usage:wo,remaining:wo,createdAt:zc}).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.z.array(he.z.strictObject({id:he.z.uuid(),linkId:he.z.uuid(),status:xm,product:$c,entity:he.z.strictObject({internalId:he.z.uuid(),id:he.z.string().nullable(),name:he.z.string().nullable()}).nullable(),beneficiary:he.z.strictObject({internalId:he.z.uuid(),id:he.z.string().nullable(),name:he.z.string().nullable()}).nullable(),startedAt:zc.nullable(),endedAt:zc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:he.z.boolean()});var pe=require("zod"),Oo=pe.z.enum(["email","sms","voice","push"]),EC=pe.z.enum(["resend","twilio","fcm","apns"]);var RC=pe.z.string().regex(/^\+[1-9]\d{1,14}$/),mx=pe.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var fx=pe.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),hx=pe.z.strictObject({subject:fx,html:pe.z.string().min(1).max(131072).optional(),text:pe.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),gx=pe.z.strictObject({body:pe.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),yx=pe.z.strictObject({text:pe.z.string().trim().min(1).max(4e3),language:pe.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:pe.z.number().int().min(1).max(900)}),Ax=pe.z.record(pe.z.string().min(1).max(64),pe.z.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"),bx=pe.z.strictObject({title:pe.z.string().trim().min(1).max(200),body:pe.z.string().trim().min(1).max(2e3),url:pe.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:Ax.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),vm=pe.z.discriminatedUnion("channel",[pe.z.strictObject({channel:pe.z.literal("email"),content:hx}),pe.z.strictObject({channel:pe.z.literal("sms"),content:gx}),pe.z.strictObject({channel:pe.z.literal("voice"),content:yx}),pe.z.strictObject({channel:pe.z.literal("push"),content:bx})]),wm=pe.z.strictObject({requestId:pe.z.uuid(),customerId:pe.z.uuid(),connectionId:pe.z.uuid().optional(),message:vm,expiresAt:pe.z.iso.datetime({offset:!0})}),xx=pe.z.array(pe.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Sx=pe.z.discriminatedUnion("kind",[pe.z.strictObject({kind:pe.z.literal("all")}),pe.z.strictObject({kind:pe.z.literal("customers"),customerIds:xx})]),kC=pe.z.strictObject({name:pe.z.string().trim().min(1).max(120),connectionId:pe.z.uuid().optional(),message:vm,audience:Sx,frequencyLimit:pe.z.number().int().min(1).max(100)}),Om=pe.z.strictObject({requestId:pe.z.uuid(),channel:Oo,state:pe.z.enum(["allowed","denied"]),expectedRevision:pe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Pm=pe.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Cm=pe.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),jC=pe.z.strictObject({meter:mx,estimatedUnits:pe.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:pe.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Oe=require("zod");var re=require("zod");var Qr=require("zod");var Po=Qr.z.strictObject({internalFeatureId:Qr.z.uuid(),name:Qr.z.string().min(1).max(120),includedAmount:Qr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Qr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:Qr.z.number().int().min(1).max(100),terms:Ca});var za=re.z.object({plan:re.z.string().min(1).max(200).optional(),coupon:re.z.uuid().optional(),promotionCode:re.z.uuid().optional(),picker:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),La=re.z.object({text:re.z.string().optional(),label:re.z.string().optional(),alt:re.z.string().optional(),html:re.z.string().max(32768).optional(),price:re.z.object({current:re.z.string(),original:re.z.string().nullable(),period:re.z.string()}).optional(),code:re.z.string().optional(),countdownAt:re.z.iso.datetime().optional(),planId:re.z.string().min(1).max(200).optional(),planVersionId:re.z.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.z.uuid().optional(),offerId:re.z.uuid().optional(),unavailable:re.z.boolean().optional(),unavailableReason:re.z.string().optional(),missing:re.z.array(re.z.string()).optional()}).strict(),Pi=re.z.object({paywall:ur.optional(),nodes:re.z.record(re.z.string(),re.z.object({base:La,picker:re.z.string().optional(),byPlan:re.z.record(re.z.string(),La).optional()}).strict()),plans:re.z.record(re.z.string(),re.z.object({id:re.z.string().min(1).max(200),versionId:re.z.string().min(1).max(200),available:re.z.boolean(),name:re.z.string(),price:re.z.string(),period:re.z.string(),currency:Ie.optional(),amountMinor:re.z.number().int().nonnegative().optional(),interval:re.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.z.number().int().positive().optional(),prepaid:re.z.array(Po).max(100).optional()}).strict()),pickers:re.z.record(re.z.string(),re.z.object({options:re.z.array(re.z.string().min(1).max(200)).max(20),selected:re.z.string().min(1).max(200).nullable()}).strict()),quantities:re.z.record(re.z.string(),re.z.strictObject({minimum:re.z.number().int().nonnegative(),maximum:re.z.number().int().nonnegative(),step:re.z.number().int().positive(),value:re.z.number().int().nonnegative(),label:re.z.string(),available:re.z.boolean()})).optional(),diagnostics:re.z.array(re.z.object({nodeId:re.z.string(),message:re.z.string()}).strict())}).strict();function _m(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var I=require("zod");function Ix(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Em(e){let t={};function n(r){var i;if(Ix(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}var Vn=require("zod"),Rm=Vn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),$a=Vn.z.strictObject({tiers:Vn.z.array(Vn.z.strictObject({id:Rm,name:Vn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Vn.z.array(Vn.z.strictObject({productVersionId:Vn.z.string().min(1).max(200),tierId:Rm,period:Vn.z.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 Ga(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var ce=require("zod");var vx=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],km=ce.z.enum(vx),jm=ce.z.object({source:km,layout:ce.z.enum(["full","compact"]),resourceKey:qr.optional(),pageSize:ce.z.number().int().min(1).max(50),showSources:ce.z.boolean(),allowPurchase:ce.z.boolean(),outputs:ce.z.object({billing_adjustment:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.z.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"})}),Dt=ce.z.string().max(2e3),Tm=ce.z.object({id:ce.z.string().max(100),label:Dt,detail:ce.z.array(Dt).max(12),value:Dt.optional(),status:Dt.optional(),facts:ce.z.array(ce.z.object({label:Dt,value:Dt}).strict()).max(1e3),purchaseId:ce.z.uuid().optional(),invoiceUrl:ce.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.z.array(ce.z.strictObject({action:ce.z.literal("invoice_open"),label:Dt})).max(1).optional(),membershipActions:ce.z.array(ce.z.object({value:ce.z.string().max(100),label:Dt}).strict()).max(3).optional()}).strict(),wx=ce.z.object({key:qr,name:Dt,spendable:Dt,reserved:Dt,available:Dt,expiry:Dt.nullable(),sources:ce.z.array(Tm).max(50),sourceCount:ce.z.number().int().nonnegative(),sourcePage:ce.z.number().int().positive(),hasNextSources:ce.z.boolean(),hasPreviousSources:ce.z.boolean()}).strict(),Ox=ce.z.object({source:km,status:ce.z.enum(["idle","loading","ready","error"]),stale:ce.z.boolean(),preview:ce.z.boolean(),errorCode:ce.z.string().max(80).optional(),errorMessage:Dt.optional(),resources:ce.z.array(wx).max(500),rows:ce.z.array(Tm).max(50),hasNext:ce.z.boolean(),hasPrevious:ce.z.boolean(),page:ce.z.number().int().positive(),filter:ce.z.string().max(40),updatedAt:ce.z.iso.datetime().optional(),buyingId:ce.z.uuid().optional(),membershipBusy:ce.z.boolean().optional(),billingBusy:ce.z.boolean().optional(),membershipReview:ce.z.object({title:Dt,note:Dt,facts:ce.z.array(ce.z.object({label:Dt,value:Dt}).strict()).max(100)}).strict().optional(),membershipResult:Dt.optional()}).strict(),Nm=ce.z.object({nodes:ce.z.record(ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ox)}).strict(),zC=ce.z.object({nodeId:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.z.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.z.string().max(100).optional()}).strict();var K=require("zod"),vt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Fm=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Vt=K.z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Fm.has(e),"Reserved UI identifier"),Kc=K.z.union([K.z.string().max(2e3),K.z.number().finite(),K.z.boolean(),K.z.null()]),Px=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("enum"),values:K.z.array(Kc).min(1).max(vt.enumValues),default:Kc}),K.z.strictObject({type:K.z.literal("number"),min:K.z.number().finite(),max:K.z.number().finite(),step:K.z.number().finite().positive(),default:K.z.number().finite()}),K.z.strictObject({type:K.z.literal("text"),maxLength:K.z.number().int().min(0).max(2e3),default:K.z.string().max(2e3).nullable()}),K.z.strictObject({type:K.z.literal("boolean"),default:K.z.boolean()})]);function Qc(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 Cx=Px.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"}),Qc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),_x=["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 Ex(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 Zr=K.z.lazy(()=>K.z.union([Kc,K.z.strictObject({ref:Vt}),K.z.strictObject({op:K.z.enum(_x),args:K.z.array(Zr).max(vt.expressionNodes)}).superRefine((e,t)=>{Ex(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function kn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Jr(e,t,n){if(!e||typeof e!="object")return!0;if(!kn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Fm.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 Ci(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(!Jr(a.value,t,a.path))return;if(kn(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 GC=K.z.unknown().superRefine((e,t)=>{Ci(e,t,[],{nodes:0})}).pipe(Zr),Hc=K.z.record(Vt,Zr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=vt.state,"UI assignments need 1\u201332 state keys"),Rx=K.z.strictObject({target:Vt,property:K.z.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Zr,className:Vt.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"})}),kx=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("scroll_latch"),target:Vt,state:Vt}),K.z.strictObject({type:K.z.literal("input"),target:Vt,state:Vt,set:Hc.optional()}),K.z.strictObject({type:K.z.literal("action"),target:Vt,set:Hc}),K.z.strictObject({type:K.z.literal("carousel"),target:Vt,state:Vt,initialIndex:K.z.number().int().nonnegative().optional(),maxWidth:K.z.number().int().min(1).max(1e4).optional(),previousTarget:Vt.optional(),nextTarget:Vt.optional(),inactiveTargets:K.z.array(Vt).max(20).optional(),inactiveMaxWidth:K.z.number().int().min(1).max(1e4).optional()})]),jx=K.z.strictObject({afterMs:K.z.number().int().min(0).max(6e4),set:Hc}),Tx=K.z.strictObject({type:K.z.literal("mosaic_waves"),target:Vt,color:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Zr.optional(),speed:K.z.number().min(0).max(4).optional(),pitch:K.z.number().min(.05).max(4).optional(),fill:K.z.number().min(.05).max(1).optional(),feather:K.z.number().min(0).max(1).optional(),warp:K.z.number().min(0).max(4).optional(),warpScale:K.z.number().min(0).max(32).optional(),detailScale:K.z.number().min(0).max(32).optional(),waveScale:K.z.number().min(0).max(32).optional(),falloff:K.z.number().min(.1).max(32).optional(),brightness:K.z.number().min(0).max(32).optional(),ambient:K.z.number().min(0).max(1).optional(),gamma:K.z.number().min(.05).max(8).optional(),vignette:K.z.number().min(0).max(1).optional(),opacity:K.z.number().min(0).max(1).optional()}),Nx=K.z.strictObject({type:K.z.literal("number_counter"),target:Vt,value:Zr,prefix:K.z.string().max(20).optional(),format:K.z.enum(["number","short"]).optional()}),Dx=K.z.strictObject({state:K.z.record(Vt,Cx).refine(e=>Object.keys(e).length<=vt.state,"Too many UI state keys").optional(),derived:K.z.record(Vt,Zr).refine(e=>Object.keys(e).length<=vt.derived,"Too many UI derived keys").optional(),bindings:K.z.array(Rx).max(vt.bindings).optional(),controls:K.z.array(kx).max(vt.controls).optional(),timers:K.z.array(jx).max(vt.timers).optional(),effects:K.z.array(K.z.discriminatedUnion("type",[Tx,Nx])).max(vt.effects).optional(),clock:K.z.boolean().optional()});function Fx(e,t){if(!Jr(e,t,[])||!kn(e))return;for(let[r,i]of[["state",vt.state],["derived",vt.derived]]){let a=e[r];if(!Jr(a,t,[r]))return;if(kn(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(!Jr(i,t,["effects",r]))return}if(kn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Jr(i,t,["state",r]))return;if(kn(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(kn(e.derived))for(let[r,i]of Object.entries(e.derived))Ci(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(!(!Jr(o,t,[r,a])||!kn(o))){if(r==="bindings")Ci(o.expression,t,[r,a,"expression"],n);else if(Jr(o.set,t,[r,a,"set"])&&kn(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))Ci(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())kn(i)&&i.type==="number_counter"?Ci(i.value,t,["effects",r,"value"],n):kn(i)&&i.enabled!==void 0&&Ci(i.enabled,t,["effects",r,"enabled"],n)}function Dm(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 Mm=K.z.unknown().superRefine(Fx).pipe(Dx).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 Dm(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 Dm(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&&!Qc(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"])});var st=require("zod"),Mx=st.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ka=st.z.discriminatedUnion("type",[st.z.object({type:st.z.literal("fixed"),productVersionId:st.z.string().min(1).max(200)}).strict(),st.z.object({type:st.z.literal("picker"),pickerId:Mx,allowedProductVersionIds:st.z.array(st.z.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")]),qx=st.z.strictObject({min:st.z.number().finite().min(1).max(1800),max:st.z.number().finite().min(1).max(1800),viewport:st.z.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),qm={desktopWidth:qx.optional(),mobile:st.z.enum(["sheet","fullscreen"]).optional(),backdrop:st.z.enum(["none","scrim","dim","strong-dim","blur"]).optional()},jn=st.z.discriminatedUnion("type",[st.z.strictObject({type:st.z.literal("modal"),size:st.z.enum(["sm","md","lg"]),...qm}),st.z.strictObject({type:st.z.literal("sheet"),size:st.z.enum(["sm","md","lg"]),...qm}),st.z.strictObject({type:st.z.literal("fullscreen")}),st.z.strictObject({type:st.z.literal("inline")})]);var Bx=4,Nn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},_o=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ve=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vx=I.z.enum(["none","xs","sm","md","lg","xl"]),Lx=I.z.enum(["none","sm","md","lg","full"]),Jc=I.z.string().regex(/^#[0-9a-fA-F]{6}$/),Wc=I.z.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"),Zc=I.z.union([Wc,I.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Um=I.z.object({primary:Jc,background:Jc,text:Jc,radius:Lx,font:I.z.enum(["system","serif","rounded","mono"]),fontAssets:I.z.object({family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.z.array(I.z.object({url:Wc,weight:I.z.number().int().min(100).max(900).multipleOf(100),family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),Eo=I.z.union([I.z.enum(["primary","text","muted","background","surface"]),I.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ue=(e,t)=>I.z.number().int().min(e).max(t),Bm=I.z.union([I.z.enum(["fit","fill"]),Ue(1,1200)]),zx=I.z.object({top:Ue(0,200),right:Ue(0,200),bottom:Ue(0,200),left:Ue(0,200)}).strict(),$x=I.z.object({top:Ue(-100,200),right:Ue(-100,200),bottom:Ue(-100,200),left:Ue(-100,200)}).strict(),Vm=I.z.object({x:Ue(0,100),y:Ue(0,100)}).strict(),Gx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("color"),color:Eo}).strict(),I.z.object({type:I.z.literal("linear"),angle:Ue(0,360),stops:I.z.array(I.z.object({color:Eo,at:Ue(0,100)}).strict()).min(2).max(4)}).strict(),I.z.object({type:I.z.literal("image"),src:Zc,fit:I.z.enum(["cover","contain"]),position:Vm.optional()}).strict()]),Kx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("rect"),radius:I.z.union([Ue(0,200),I.z.object({topLeft:Ue(0,200),topRight:Ue(0,200),bottomRight:Ue(0,200),bottomLeft:Ue(0,200)}).strict()])}).strict(),I.z.object({type:I.z.literal("pill")}).strict()]),Hx=I.z.object({width:Ue(0,12),color:Eo,style:I.z.enum(["solid","dashed"])}).strict(),Qx=I.z.object({x:Ue(-40,40),y:Ue(-40,40),blur:Ue(0,80),spread:Ue(-20,40),color:Eo}).strict(),Jx=I.z.object({font:I.z.enum(["system","serif","rounded","mono"]),size:Ue(8,96),weight:I.z.number().int().min(100).max(900).multipleOf(100),lineHeight:I.z.number().min(.8).max(3),letterSpacing:I.z.number().min(-5).max(20),color:Eo,align:I.z.enum(["start","center","end"]),italic:I.z.boolean(),decoration:I.z.enum(["none","underline","line-through"]),transform:I.z.enum(["none","uppercase"])}).strict().partial(),Wr=I.z.object({width:Bm,height:Bm,padding:zx,margin:$x,gap:Ue(0,120),grow:I.z.union([I.z.boolean(),I.z.number().min(0).max(12)]),background:Gx,opacity:I.z.number().min(0).max(1),clipContent:I.z.boolean(),shape:Kx,border:Hx,shadow:Qx,text:Jx}).strict().partial(),an={id:_o,name:I.z.string().trim().min(1).max(60).optional(),hidden:I.z.boolean().optional(),style:Wr.optional(),fallback:Ve.optional()},Zx=I.z.object({...an,type:I.z.literal("text"),productField:I.z.enum(["name","price","trial","period"]).optional(),feature:I.z.object({id:I.z.uuid(),field:I.z.enum(["name","allowance"])}).strict().optional(),text:Ve,variant:I.z.enum(["title","heading","body","caption"])}).strict(),Wx=I.z.object({...an,type:I.z.literal("image"),src:Zc,localizedSrc:I.z.record(En,Zc).optional(),alt:Ve,aspect:I.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.z.enum(["cover","contain"]),position:Vm.optional()}).strict(),Yx=I.z.object({...an,type:I.z.literal("button"),label:Ve,variant:I.z.enum(["primary","secondary","link"]),action:Ve,purpose:I.z.enum(["purchase","navigation","close"]).optional(),bind:za.optional()}).strict(),Xx=I.z.object({...an,type:I.z.literal("divider")}).strict(),eS=I.z.object({...an,type:I.z.literal("customer_data"),title:Ve,data:jm}).strict(),tS=I.z.object({...an,type:I.z.literal("spacer"),size:Vx}).strict(),nS=I.z.object({...an,type:I.z.literal("custom_html"),html:I.z.record(En,I.z.string().max(Nn.customHtml)),css:I.z.string().max(Nn.customCss),ui:Mm.optional()}).strict(),rS=I.z.object({...an,type:I.z.literal("price"),fallback:Ve,parts:I.z.object({current:Wr.optional(),original:Wr.optional(),period:Wr.optional()}).strict().optional()}).strict(),iS=I.z.object({...an,type:I.z.literal("coupon_code"),label:Ve,fallback:Ve}).strict(),oS=I.z.object({...an,type:I.z.literal("countdown"),source:I.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.z.iso.datetime().optional(),granularity:I.z.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"),aS=I.z.object({...an,type:I.z.literal("plan_picker"),label:Ve,fallback:Ve,planIds:I.z.array(I.z.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.z.string().min(1).max(200).optional(),grouping:$a.safeExtend({monthLabel:Ve,yearLabel:Ve,unavailableLabel:Ve}).optional(),states:I.z.object({selected:Wr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ga(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),sS=I.z.object({...an,type:I.z.literal("quantity_picker"),bind:za.optional(),label:Ve,fallback:Ve,internalFeatureId:I.z.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"),cS=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("input"),label:Ve,keyboard:I.z.enum(["text","email","tel","url"]),maxLength:Ue(1,500)}).strict(),I.z.object({type:I.z.literal("multiselect"),label:Ve,min:Ue(0,50),max:Ue(1,50)}).strict(),I.z.object({type:I.z.literal("select"),label:Ve,defaultIndex:Ue(0,49),purpose:I.z.enum(["option","product","tier"]).optional(),pickerId:_o.optional(),selectedStyle:Wr.optional()}).strict(),I.z.object({type:I.z.literal("tabs"),label:Ve,defaultIndex:Ue(0,49),purpose:I.z.literal("tier").optional()}).strict(),I.z.object({type:I.z.literal("toggle"),label:Ve,defaultEnabled:I.z.boolean()}).strict(),I.z.object({type:I.z.literal("carousel"),label:Ve}).strict()]),Tn={...an,type:I.z.literal("stack"),direction:I.z.enum(["vertical","horizontal","overlay"]),align:I.z.enum(["start","center","end","stretch"]),justify:I.z.enum(["start","center","end","between"]),productSlot:I.z.object({index:Ue(0,19),period:I.z.enum(["month","year"]).optional(),requireBinding:I.z.boolean().optional()}).strict().optional(),interaction:cS.optional(),states:I.z.object({selected:Wr.optional()}).strict().optional(),purpose:I.z.literal("benefits").optional(),purchaseAction:Ve.optional(),buttonVariant:I.z.enum(["primary","secondary","link"]).optional(),bind:za.optional()},Lm=I.z.lazy(()=>I.z.object({...an,type:Tn.type,direction:Tn.direction,align:Tn.align,justify:Tn.justify,children:I.z.array(uS).max(Nn.children),productSlot:Tn.productSlot,interaction:Tn.interaction,states:Tn.states,purpose:Tn.purpose,purchaseAction:Tn.purchaseAction,buttonVariant:Tn.buttonVariant,bind:Tn.bind}).strict()),uS=I.z.lazy(()=>I.z.union([Lm,Zx,Wx,Yx,Xx,tS,nS,rS,iS,oS,aS,sS,eS])),lS=I.z.union([I.z.string().max(500),I.z.number().finite(),I.z.boolean(),I.z.null()]),Co={id:Ve,event:Ve,properties:I.z.record(Ve,lS).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},dS=I.z.discriminatedUnion("type",[I.z.object({...Co,type:I.z.literal("navigate"),close:I.z.literal(!1),pageId:_o}).strict(),I.z.object({...Co,type:I.z.literal("event"),close:I.z.boolean()}).strict(),I.z.object({...Co,type:I.z.literal("close"),close:I.z.literal(!0)}).strict(),I.z.object({...Co,type:I.z.literal("open_url"),close:I.z.boolean(),url:Wc}).strict(),I.z.object({...Co,type:I.z.literal("claim_offer"),close:I.z.boolean(),couponId:I.z.uuid()}).strict()]),pS=I.z.object({defaultLocale:En,locales:I.z.record(En,I.z.record(Ve,I.z.string().max(Nn.stringLength)))}).strict(),mS=I.z.enum(["popup","paywall","onboarding","page","banner"]);var fS=I.z.object({kind:I.z.literal("screen"),schemaVersion:I.z.literal(Bx),name:I.z.string().trim().min(1).max(80),surface:mS,initialPageId:_o.optional(),presentation:jn,theme:Um,pages:I.z.array(I.z.object({id:_o,name:I.z.string().trim().min(1).max(60),root:Lm,theme:Um.optional(),editorPosition:I.z.object({x:I.z.number().finite().min(-1e5).max(1e5),y:I.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Nn.pages),strings:pS,actions:I.z.array(dS).max(Nn.actions)}).strict();function Yt(e,t){for(let n of e.pages)nr(n.root,t)}var hn=fS.superRefine((e,t)=>{let n=Nn;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>Nn.locales&&r(`\u6700\u591A ${Nn.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;Yt(e,(l,p)=>{if(c++,p>Nn.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 ${Nn.depth} \u5C42`)});function nr(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)nr(i,t,n+1,e)}function Ha(e){let t=[],n=new Set;return Yt(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 hS(e,t,n){if(t.field==="html"){let r;return Yt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Ro(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 fr(e){let t=Ha(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=>!hS(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 gS(e,t){let n=null;return nr(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Ro(e,t){for(let n of e.pages){let r=gS(n.root,t);if(r)return r}return null}var Lt=require("zod"),wt=Lt.z.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"),Yc=Lt.z.strictObject({type:Lt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Lt.z.boolean(),enum:Lt.z.array(Lt.z.string().max(255)).min(1).max(100).optional()}),_i=Yc.extend({type:Lt.z.enum([...Yc.shape.type.options,"array"]),items:Yc.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"})}),Ei=_i.safeExtend({source:Lt.z.discriminatedUnion("type",[Lt.z.strictObject({type:Lt.z.literal("input")}),Lt.z.strictObject({type:Lt.z.literal("node")}),Lt.z.strictObject({type:Lt.z.enum(["parameter","attribute"]),key:wt})])}),r_=Lt.z.record(wt,Ei),Xc=Lt.z.record(wt,wt).refine(e=>Object.keys(e).length<=20);function In(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=>In(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&&Lt.z.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 eu(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&&eu(e.items,t.items)}function Qa(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(!In(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Ri(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 zm(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"||!In(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")}var hr=require("zod");var Dn=hr.z.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"),Ln=hr.z.discriminatedUnion("source",[hr.z.strictObject({source:hr.z.literal("literal"),value:ve}),hr.z.strictObject({source:hr.z.literal("variable"),key:hr.z.string().min(1).max(255),path:Dn.optional()})]);function $m(e,t){if(!t)return e;for(let n of Dn.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 tu(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Qa(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse($m(n[e.key],e.path)))}function nu(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&&!Dn.safeParse(r).success?null:{key:n,path:r}}function ru(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Yt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(_m))]}function Ja(e){return ru(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function gn(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 gr=Oe.z.enum(["page","popup","banner"]),yS=3e5,Gm=Oe.z.strictObject({type:Oe.z.enum(["string","number","boolean","strings","json"]),nullable:Oe.z.boolean()}),AS=Oe.z.strictObject({inputs:Oe.z.record(Ve,Gm.extend({required:Oe.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Oe.z.record(Ve,Gm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),bS=Oe.z.strictObject({kind:gr,schemaVersion:Oe.z.literal(1),name:Oe.z.string().trim().min(1).max(80),screen:hn,contract:AS}),Za=bS.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"]),gn(e)>yS&&n("Content document exceeds its byte budget",[])});function xS(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 SS=Za.superRefine((e,t)=>{for(let n of Ja(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&&!xS(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}fr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Km=Oe.z.strictObject({id:Oe.z.uuid(),kind:gr,projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),name:Oe.z.string(),revision:Oe.z.number().int().nonnegative(),status:Oe.z.enum(["draft","published","archived"]),publishedVersionId:Oe.z.uuid().nullable(),createdAt:Oe.z.iso.datetime({offset:!0}),updatedAt:Oe.z.iso.datetime({offset:!0})}),y_=Km.extend({draft:Za}),A_=Oe.z.strictObject({rows:Oe.z.array(Km).max(200),nextCursor:Oe.z.uuid().nullable()}),iu=Oe.z.strictObject({id:Oe.z.uuid(),kind:gr,resourceId:Oe.z.uuid(),projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),version:Oe.z.number().int().positive(),sourceRevision:Oe.z.number().int().nonnegative(),document:SS,createdAt:Oe.z.iso.datetime({offset:!0})}),b_=iu.omit({document:!0}),x_=Oe.z.discriminatedUnion("action",[Oe.z.strictObject({action:Oe.z.literal("create"),kind:gr,id:Oe.z.uuid(),document:Za}),Oe.z.strictObject({action:Oe.z.literal("save"),kind:gr,id:Oe.z.uuid(),revision:Oe.z.number().int().nonnegative(),document:Za}),Oe.z.strictObject({action:Oe.z.enum(["publish","archive"]),kind:gr,id:Oe.z.uuid(),revision:Oe.z.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"})});var ou=require("zod"),ki={funnelId:ou.z.uuid().optional(),funnelVersionId:ou.z.uuid().optional()};var ko=require("zod"),Wa=ko.z.strictObject({runId:ko.z.uuid(),bindingId:ko.z.uuid(),receiptId:ko.z.uuid()});var ct=require("zod");var Le=require("zod");var nt=require("zod"),w_=nt.z.discriminatedUnion("action",[nt.z.strictObject({action:nt.z.literal("create"),couponId:nt.z.uuid(),productBindingId:nt.z.uuid(),storeOfferId:nt.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:nt.z.enum(["introductory","promotional"])}),nt.z.strictObject({action:nt.z.literal("set_enabled"),id:nt.z.uuid(),revision:nt.z.number().int().nonnegative(),enabled:nt.z.boolean()})]),O_=nt.z.array(nt.z.strictObject({id:nt.z.uuid(),couponId:nt.z.uuid(),productBindingId:nt.z.uuid(),storeOfferId:nt.z.string().min(1).max(255).nullable(),storeOfferType:nt.z.enum(["introductory","promotional"]),enabled:nt.z.boolean(),revision:nt.z.number().int().nonnegative()})).max(500),ji=nt.z.strictObject({offerKind:nt.z.enum(["none","introductory","promotional"]),offerId:nt.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:nt.z.number().int().min(0).max(1e8),trialDays:nt.z.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"})}),P_=nt.z.record(nt.z.uuid(),ji).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var au=Le.z.object({type:Le.z.literal("native_purchase"),receiptId:Le.z.uuid(),orderId:Le.z.uuid(),productVersionId:Le.z.uuid(),provider:Le.z.enum(["apple","google"]),productId:Le.z.string().min(1).max(255),productKind:Ld,replacement:Le.z.strictObject({sourceOrderId:Le.z.uuid(),sourceProductId:Le.z.string().min(1).max(255),policy:Le.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:Le.z.array(Le.z.uuid()).max(50)}).nullable(),appAccountToken:Le.z.uuid().optional(),obfuscatedAccountId:Le.z.string().min(1).max(64).optional(),obfuscatedProfileId:Le.z.uuid().optional(),basePlanId:Le.z.string().min(1).max(255).optional(),offerId:Le.z.string().min(1).max(255).optional(),offerKind:Le.z.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Le.z.number().int().nonnegative().max(1e8),discountMinor:Le.z.number().int().nonnegative().max(1e8),trialDays:Le.z.number().int().min(1).max(730).nullable(),seatBundle:Le.z.array(Le.z.strictObject({key:Le.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Le.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Le.z.strictObject({offerId:Le.z.string().min(1).max(255),keyId:Le.z.string().min(1).max(255),nonce:Le.z.uuid(),signature:Le.z.string().min(1).max(1024),timestamp:Le.z.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"})});var f=require("zod");var _e=require("zod/v4"),Hm=require("zod/v4"),IS=Hm.z.registry(),{BillingInterval:Qm}=(()=>{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:vS}=(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.z),{withSpecDefault:wS}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(IS),{COMMON:Jm}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:OS}={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:PS}=(e=>({COMMON_SET:new Set(e)}))(Jm),{hasNoDuplicateCurrencies:Zm}={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:Wm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:CS}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e.z),{Infinite:_S}={Infinite:"inf"},{TierBehavior:ES}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Ym}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:RS}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:kS}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jS}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:TS}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e.z),{ApiCreditTierSchema:Xm}=(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.z),{VIOLATION_MESSAGES:NS}={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:ef}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e.z),{ModelMarkupsSchema:DS}=((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.z,ef),{InvoiceUsageEntrySchema:FS}=(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.z),{AttachDiscountSchema:tf}=(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.z),{CustomLineItemSchema:MS}=(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.z),{UnixMsTimestampSchema:qS}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e.z),{CreateInvoicePreviewLineSchema:US}=(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.z),{ReissueInvoiceParamsSchema:nf}=(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.z),{InvoiceModeParamsSchema:Yr}=(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.z),{InvoiceTemplateSchema:BS}=(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.z),{BasePriceSchema:VS}=((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.z,Qm,vS),{CURRENCY_CODES:LS}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Jm,OS,PS),{ApiPriceProcessorsSchema:rf}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e.z,CS),{AllocatedBillingFieldSchema:zS}=((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.z,RS),{CreditDimensionNameSchema:$S}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e.z,kS,jS),{ApiCreditMatchSchema:of}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(TS),{findCreditTierViolations:GS}=(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}}))(NS),{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.z,of),{ProviderMarkupsSchema:HS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e.z,ef),{InvoiceFeatureQuantitySchema:af}=((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.z,Ym,FS),{CreateInvoicePreviewSchema:su}=((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.z,US),{SUPPORTED_SET:QS}=(e=>({SUPPORTED_SET:new Set(e)}))(LS),{ApiCreditDimensionBaseSchema:JS}=((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.z,of),{refineGraduatedTiers:sf}=(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"]})}}))(GS),{ApiFeatureMarkupsOverrideSchema:ZS}=((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.z,HS,DS),{isValidCurrencyCode:WS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(QS),{ApiCreditDimensionSchema:YS}=((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.z,JS,Xm,sf),{CurrencyCodeSchema:cf}=((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.z,WS),{AdditionalCurrencyTierSchema:XS}=((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.z,cf),{ApiCreditSchemaItemBaseSchema:uf}=((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.z,$S,YS,KS),{ApiFlatCreditSchemaItemSchema:e0}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(uf,_e.z),{AdditionalCurrencyPriceSchema:t0}=((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.z,cf),{AdditionalCurrencyTierArraySchema:n0}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,XS,Zm,Wm),{ApiGraduatedCreditSchemaItemSchema:r0}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(uf,_e.z,Xm,sf),{AdditionalCurrencyPriceArraySchema:lf}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,t0,Zm,Wm),{ApiUsageTierWithCurrenciesSchema:i0}=((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.z,_S,n0),{ApiCreditSchemaItemSchema:o0}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e.z,r0,e0),{BasePriceParamsSchema:a0}=((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."})}))(VS,wS,_e.z,lf),{PlanItemPriceParamsSchema:s0}=((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.z,lf,i0,ES,Qm,Ym,zS),{ApiFeatureOverrideSchema:c0}=((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.z,o0,ZS),{InvoiceBasePriceParamsSchema:df}=((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()}))(a0,rf),{InvoiceItemPriceParamsSchema:u0}=((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()}))(s0,rf),{InvoiceLicenseQuantitySchema:l0}=((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.z,df,af),{InvoiceCustomizeItemSchema:d0}=((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.z,u0,c0),{InvoiceCustomizeSchema:p0}=((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.z,df,d0),{InvoicePlanParamsSchema:m0}=((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.z,p0,af,l0,tf),{CreateInvoiceParamsSchema:Ti}=((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.z,m0,MS,tf,qS);var ff=f.z.strictObject({requestId:f.z.uuid(),predecessorOperationId:f.z.uuid().optional(),invoiceMode:Yr.optional(),entityId:f.z.uuid().optional(),billingSubscriptionId:f.z.uuid().optional(),newBillingSubscription:f.z.literal(!0).optional(),offerId:f.z.uuid().optional(),nativeOffer:ji.optional(),plans:f.z.array(f.z.strictObject({productVersionId:f.z.uuid(),seatQuantities:f.z.record(Ia,f.z.number().int().min(0).max(1e4)).optional(),featureQuantities:f.z.record(f.z.uuid(),f.z.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.z.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"),ei=f.z.strictObject({operationId:f.z.uuid()}),zt=f.z.number().int().min(0).max(1e8),f0=f.z.strictObject({lineId:f.z.uuid(),productVersionId:f.z.uuid(),productName:f.z.string().min(1).max(80),interval:f.z.enum(["free","week","month","year","one_time"]),intervalCount:f.z.number().int().min(1).max(156).optional(),baseAmountMinor:zt,seats:f.z.array(f.z.strictObject({key:Ia,quantity:f.z.number().int().min(0).max(1e4),includedQuantity:f.z.number().int().min(0).max(1e4),maximumQuantity:f.z.number().int().min(0).max(1e4),unitAmountMinor:zt})).max(20),prepaid:f.z.array(rm).max(100).optional(),catalogAmountMinor:zt,trial:ro.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+Pa({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"),hf=f.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),h0=f.z.strictObject({id:hf,name:f.z.string().min(1).max(40),percent_off:f.z.number().gt(0).max(100).optional(),amount_off:f.z.number().int().positive().optional(),currency:f.z.string().regex(/^[a-z]{3}$/).optional(),duration:f.z.enum(["once","repeating","forever"]),duration_in_months:f.z.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"),g0=f.z.strictObject({subscriptionId:f.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.z.array(f.z.strictObject({id:f.z.string(),price_id:f.z.string(),quantity:f.z.number().int().nonnegative(),discounts:f.z.array(f.z.strictObject({id:f.z.string(),coupon:f.z.string(),start:f.z.number(),end:f.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.z.number().int().nonnegative(),amountMinor:f.z.number().int().positive(),periodStartMs:f.z.number(),periodEndMs:f.z.number()}),gf=f.z.strictObject({invoiceMode:Yr.optional(),append:g0.optional(),provider:f.z.literal("stripe"),executor:f.z.enum(["indiana","merchant"]),accountId:f.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.z.enum(["payment","subscription"]),lineItems:f.z.array(f.z.strictObject({price:f.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.z.number().int().min(1).max(1e4),priceId:f.z.uuid(),productName:f.z.string().min(1).max(80),amountMinor:f.z.number().int().min(0).max(1e8),currency:f.z.string().regex(/^[a-z]{3}$/),interval:f.z.enum(["week","month","year","one_off"]),intervalCount:f.z.number().int().min(1).max(52),slot:f.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.z.strictObject({mode:f.z.enum(["graduated","volume"]),tiers:f.z.array(f.z.strictObject({upTo:f.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.z.number().int().min(0).max(1e8),flatAmountMinor:f.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.z.array(f.z.strictObject({coupon:hf,terms:h0})).max(1),trialPeriodDays:f.z.number().int().min(1).max(730).nullable(),metadata:f.z.strictObject({grooveCheckoutId:f.z.uuid(),grooveCustomerId:f.z.uuid()}),expiresAt:f.z.iso.datetime({offset:!0})}),Ni=f.z.strictObject({operationId:f.z.uuid(),merchantTerms:xi.optional(),entityId:f.z.uuid().nullable(),billingSubscriptionId:f.z.uuid().nullable(),discount:f.z.strictObject({offerId:f.z.uuid(),couponId:f.z.uuid(),discount:mr,duration:mn,amountMinor:zt,allocations:f.z.array(f.z.strictObject({productVersionId:f.z.uuid(),amountMinor:zt})).min(1).max(20),expiresAt:f.z.iso.datetime({offset:!0})}).nullable(),charge:f.z.strictObject({effectiveAt:f.z.iso.datetime({offset:!0}),periodEndsAt:f.z.iso.datetime({offset:!0}),debitMinor:zt,discountMinor:zt,taxMinor:zt,totalMinor:zt}).nullable(),expiresAt:f.z.iso.datetime({offset:!0}),provider:f.z.enum(["stripe","apple","google","merchant"]),nativeOffer:ji.optional(),currency:Ie,lines:f.z.array(f0).min(1).max(20),catalogAmountMinor:zt,automaticTax:f.z.boolean(),execution:f.z.union([gf,la]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&ba(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"),Di=f.z.strictObject({operationId:f.z.uuid(),orderId:f.z.uuid(),append:f.z.boolean().optional(),invoiceMode:f.z.boolean().optional(),status:f.z.enum(["pending","complete","cancelled","failed"]),executor:f.z.enum(["indiana","merchant"]),checkoutUrl:f.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:f.z.union([gf,la]).nullable(),currency:Ie,catalogAmountMinor:zt,taxMinor:zt,totalMinor:f.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.z.boolean(),nativePurchase:au.nullable(),confirmedAt:f.z.iso.datetime({offset:!0}).nullable().optional(),quote:Ni.optional(),merchantExecution:Fr.nullable().optional(),problem:to.nullable().optional(),authority:Sa.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"),Xa=f.z.strictObject({enabled:f.z.literal(!0),featureIds:f.z.array(f.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),yf=f.z.strictObject({requestId:f.z.uuid(),invoiceMode:Yr.optional(),membershipId:f.z.uuid(),carryOverBalances:Xa.optional(),carryOverUsages:Xa.optional(),membershipIds:f.z.array(f.z.uuid()).min(1).max(20).optional(),prorationBehavior:f.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.z.enum(["immediate","renewal","store"]),change:f.z.discriminatedUnion("type",[f.z.strictObject({type:f.z.literal("plan"),productVersionId:f.z.uuid()}),f.z.strictObject({type:f.z.literal("seats"),licenseKey:Ia,quantity:f.z.number().int().min(0).max(1e4)}),f.z.strictObject({type:f.z.literal("quantity"),internal_feature_id:f.z.uuid(),quantity:f.z.number().int().min(0).max(1e4)}),f.z.strictObject({type:f.z.literal("cancel")}),f.z.strictObject({type:f.z.literal("uncancel")}),f.z.strictObject({type:f.z.literal("billing_cycle"),billingCycleAnchor:f.z.union([f.z.literal("now"),f.z.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"),Ya=f.z.string().regex(/^price_[A-Za-z0-9]+$/),pf=f.z.strictObject({grooveUpdateId:f.z.uuid(),grooveCustomerId:f.z.uuid()}),mf=f.z.strictObject({price:Ya.nullable(),priceId:f.z.uuid().optional(),quantity:f.z.number().int().min(0).max(1e4)}),Af=f.z.strictObject({provider:f.z.literal("stripe"),invoiceMode:Yr.optional(),executor:f.z.enum(["indiana","merchant"]),accountId:f.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.z.enum(["update","cancel","schedule","release"]),update:f.z.strictObject({items:f.z.array(mf).max(20),remove:f.z.array(Ya).max(20),restoreItems:f.z.array(f.z.strictObject({price:Ya,quantity:f.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.z.number().int().positive().optional(),paymentBehavior:f.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.z.boolean().optional(),clearCancelAt:f.z.literal(!0).optional(),billingCycleAnchorNow:f.z.literal(!0).optional(),metadata:pf}).nullable(),cancel:f.z.strictObject({prorate:f.z.literal(!1),invoiceNow:f.z.literal(!1)}).nullable(),schedule:f.z.strictObject({currentItems:f.z.array(f.z.strictObject({price:Ya,quantity:f.z.number().int().min(0).max(1e4)})).max(20),nextItems:f.z.array(mf).min(1).max(20),switchAt:f.z.number().int().positive(),interval:f.z.enum(["week","month","year"]),intervalCount:f.z.number().int().min(1).max(52),resetBillingCycleAnchor:f.z.literal(!0).optional(),metadata:pf}).nullable(),release:f.z.strictObject({schedule:f.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.z.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"),es=f.z.strictObject({merchantTerms:xi.optional(),carryOverBalances:Xa.optional(),carryOverUsages:Xa.optional(),operationId:f.z.uuid(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),timing:f.z.enum(["immediate","renewal"]),effectiveAt:f.z.iso.datetime({offset:!0}),expiresAt:f.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:zt,debitMinor:zt,discountMinor:zt,taxMinor:zt,totalMinor:zt,retainedProductVersionIds:f.z.array(f.z.uuid()).max(19),execution:f.z.union([Af,rr])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&ba(e.merchantTerms,e.operationId,"subscription_change",e.currency)),y0=f.z.strictObject({operationId:f.z.uuid(),invoiceMode:f.z.boolean().optional(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),status:f.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.z.enum(["immediate","renewal"]),effectiveAt:f.z.iso.datetime({offset:!0}),checkoutUrl:f.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.z.enum(["indiana","merchant"]),execution:f.z.union([Af,rr]).nullable(),confirmedAt:f.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Fr.nullable().optional(),problem:to.nullable().optional(),quote:es.optional(),authority:Sa.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),A0=f.z.strictObject({operationId:f.z.uuid(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),timing:f.z.literal("store"),effectiveAt:f.z.null(),expiresAt:f.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:f.z.null(),debitMinor:f.z.null(),discountMinor:f.z.null(),taxMinor:f.z.null(),totalMinor:f.z.null(),retainedProductVersionIds:f.z.array(f.z.uuid()).max(19),store:f.z.strictObject({provider:f.z.enum(["apple","google"]),productId:f.z.string().min(1).max(255),catalogAmountMinor:zt,policy:f.z.enum(["apple_store","google_full_price"])})}),b0=f.z.strictObject({operationId:f.z.uuid(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),status:f.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.z.literal("store"),effectiveAt:f.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.z.null(),nativePurchase:au.nullable()}),bf=f.z.union([es,A0]),cu=f.z.union([y0,b0]),uu=fc,Xr=ga,xf=f.z.strictObject({requestId:f.z.uuid(),invoiceId:f.z.uuid(),...Ur.shape}).refine(io,"A partial refund states amountMinor; a full refund refunds the remaining amount"),Sf=f.z.strictObject({provider:f.z.literal("stripe"),executor:f.z.enum(["indiana","merchant"]),accountId:f.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uu,currency:f.z.string().regex(/^[a-z]{3}$/),metadata:f.z.strictObject({indianaRefundId:f.z.uuid()}),idempotencyKey:f.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.z.array(f.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),lu=f.z.strictObject({operationId:f.z.uuid(),merchantTerms:xi.optional(),invoiceId:f.z.uuid(),providerInvoiceId:f.z.string().min(1).max(200),currency:Ie,paidMinor:Xr,refundedMinor:Xr,pendingMinor:Xr,amountMinor:uu,mode:f.z.enum(["full","partial"]),entitlementAction:f.z.enum(["retain","revoke"]),revokes:f.z.strictObject({customerProductIds:f.z.array(f.z.uuid()).max(100),subscriptionIds:f.z.array(f.z.string().min(1).max(200)).max(20)}),execution:f.z.union([Sf,da]),expiresAt:f.z.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&ba(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"),ts=f.z.strictObject({operationId:f.z.uuid(),invoiceId:f.z.uuid(),providerInvoiceId:f.z.string().min(1).max(200),status:f.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.z.enum(["indiana","merchant"]),currency:Ie,amountMinor:uu,mode:f.z.enum(["full","partial"]),entitlementAction:f.z.enum(["retain","revoke"]),refundId:f.z.string().min(1).max(200).nullable(),quote:lu.optional(),execution:f.z.union([Sf,da]).nullable(),confirmedAt:f.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Fr.nullable().optional(),problem:to.nullable().optional(),authority:Sa.optional(),failureReason:f.z.string().min(1).max(200).nullable(),createdAt:f.z.iso.datetime({offset:!0}),completedAt:f.z.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"),G_=f.z.strictObject({invoiceId:f.z.uuid(),currency:Ie,paidMinor:Xr,refundedMinor:Xr,pendingMinor:Xr,refundableMinor:Xr,executor:f.z.enum(["indiana","merchant"]).nullable(),canRefund:f.z.boolean(),operations:f.z.array(ts).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),K_=f.z.strictObject({requestId:f.z.uuid(),...Ur.shape}).refine(io,"A partial refund states amountMinor; a full refund refunds the remaining amount");var If=ct.z.strictObject({requestId:ct.z.uuid(),targets:ct.z.array(ct.z.strictObject({membershipId:ct.z.uuid(),action:ct.z.enum(["cancel","uncancel"]),timing:ct.z.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"),ns=ct.z.strictObject({batchId:ct.z.uuid()}),x0=ct.z.strictObject({operationId:ct.z.uuid(),membershipIds:ct.z.array(ct.z.uuid()).min(1).max(20),provider:ct.z.enum(["stripe","apple","google"]),action:ct.z.enum(["cancel","uncancel"]),timing:ct.z.enum(["immediate","renewal"]),status:ct.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:es.nullable(),managementUrl:ct.z.url().nullable(),failureCode:ct.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),jo=ct.z.strictObject({batchId:ct.z.uuid(),ready:ct.z.boolean(),status:ct.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ct.z.iso.datetime({offset:!0}),acceptedAt:ct.z.iso.datetime({offset:!0}).nullable(),groups:ct.z.array(x0).min(1).max(100)});var Te=require("zod"),S0=Te.z.string().trim().min(1).max(240),du={requestId:Te.z.uuid(),reason:S0},rs=Te.z.discriminatedUnion("action",[Te.z.strictObject({...du,action:Te.z.literal("start"),productVersionId:Te.z.uuid(),entityId:Te.z.uuid().optional(),days:Te.z.number().int().min(1).max(730).optional()}),Te.z.strictObject({...du,action:Te.z.literal("extend"),membershipId:Te.z.uuid(),days:Te.z.number().int().min(1).max(730)}),Te.z.strictObject({...du,action:Te.z.literal("end"),membershipId:Te.z.uuid()})]),vf=Te.z.strictObject({operationId:Te.z.uuid()}),wf=Te.z.iso.datetime({offset:!0}),I0=Te.z.strictObject({provider:Te.z.literal("stripe"),executor:Te.z.enum(["indiana","merchant"]),accountId:Te.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Te.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Te.z.union([Te.z.literal("now"),wf]),prorationBehavior:Te.z.literal("none")}),pu=Te.z.strictObject({operationId:Te.z.uuid(),action:Te.z.enum(["start","extend","end"]),status:Te.z.enum(["pending","effective"]),managedBy:Te.z.enum(["indiana","stripe"]),membershipIds:Te.z.array(Te.z.uuid()).min(1).max(20),endsAt:wf.nullable(),execution:I0.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"),Z_=Te.z.strictObject({groupId:Te.z.uuid(),productVersionId:Te.z.uuid(),enabled:Te.z.boolean()});var Ye=require("zod");var Of=Ye.z.strictObject({requestId:Ye.z.uuid(),currency:Ie,makeDefault:Ye.z.boolean()}),Pf=Ye.z.strictObject({setupId:Ye.z.uuid()}),v0=Ye.z.strictObject({provider:Ye.z.literal("stripe"),executor:Ye.z.literal("merchant"),accountId:Ye.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ye.z.literal("setup"),currency:Ye.z.string().regex(/^[a-z]{3}$/),customer:Ye.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ye.z.uuid(),metadata:Ye.z.strictObject({grooveProjectId:Ye.z.uuid(),grooveEnvironmentId:Ye.z.uuid(),grooveCustomerId:Ye.z.uuid(),groovePaymentSetupId:Ye.z.uuid()}),setDefaultPaymentMethod:Ye.z.boolean(),expiresAt:Ye.z.iso.datetime({offset:!0})}),mu=Ye.z.strictObject({id:Ye.z.uuid(),provider:Ye.z.literal("stripe"),status:Ye.z.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:Ye.z.boolean(),url:Ye.z.url().nullable(),createdAt:Ye.z.iso.datetime({offset:!0}),expiresAt:Ye.z.iso.datetime({offset:!0}),completedAt:Ye.z.iso.datetime({offset:!0}).nullable(),execution:v0.nullable()});var Ft=require("zod"),Cf=Ft.z.union([Ft.z.string(),Ft.z.number(),Ft.z.boolean(),Ft.z.null()]),_f=Ft.z.strictObject({customerId:Ft.z.uuid()}),Ef=Ft.z.strictObject({customerId:Ft.z.uuid(),provider:Ft.z.literal("stripe"),checkedAt:Ft.z.iso.datetime({offset:!0}),status:Ft.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.z.number().int().nonnegative(),differences:Ft.z.array(Ft.z.strictObject({subscriptionId:Ft.z.string().startsWith("sub_"),itemId:Ft.z.string().nullable(),field:Ft.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Cf,actual:Cf})).max(1e4)});var we=require("zod");var is=we.z.iso.datetime({offset:!0}),os=we.z.strictObject({createdAt:is,id:we.z.uuid()}),as=we.z.strictObject({customerId:we.z.uuid().optional(),entityId:we.z.uuid().optional(),productId:we.z.string().min(1).max(256).optional(),provider:we.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:os.optional(),limit:we.z.number().int().min(1).max(100).optional()}),fu={id:we.z.uuid(),customerId:we.z.uuid(),entityId:we.z.uuid().nullable(),productId:we.z.string().min(1).max(256),productVersionId:we.z.uuid(),name:we.z.string().min(1).max(120),provider:we.z.enum(["stripe","apple","google","merchant","free"]),createdAt:is},w0=we.z.strictObject({...fu,status:we.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.z.boolean(),billingSubscriptionId:we.z.uuid().nullable()}),O0=we.z.strictObject({...fu,status:we.z.enum(["active","ended","refunded"]),orderId:we.z.uuid().nullable(),transactionId:we.z.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),P0=we.z.strictObject({...fu,status:we.z.enum(["blocked","resolved"]),conflict:we.z.strictObject({detectedAt:is,blockingMembershipIds:we.z.array(we.z.uuid()).min(1).max(100),transactionId:we.z.uuid()}),resolvedAt:is.nullable()}),Rf=as.extend({status:we.z.enum(["blocked","resolved"]).optional()}),kf=we.z.strictObject({customerId:we.z.uuid(),orderId:we.z.uuid()}),jf=we.z.strictObject({orderId:we.z.uuid(),status:we.z.enum(["blocked","resolved"])}),Tf=we.z.strictObject({items:we.z.array(w0).max(100),nextCursor:os.nullable()}),Nf=we.z.strictObject({items:we.z.array(O0).max(100),nextCursor:os.nullable()}),Df=we.z.strictObject({items:we.z.array(P0).max(100),nextCursor:os.nullable()});var it=require("zod");var Ff=it.z.union([it.z.strictObject({intent:it.z.literal("read"),requestId:it.z.uuid(),purchaseIntentId:it.z.uuid()}),it.z.strictObject({requestId:it.z.uuid(),provider:it.z.literal("apple"),purchaseIntentId:it.z.uuid(),productId:it.z.string().min(1).max(255).optional(),signedTransaction:it.z.string().min(1).max(131072)}),it.z.strictObject({requestId:it.z.uuid(),provider:it.z.literal("google"),purchaseIntentId:it.z.uuid(),productId:it.z.string().min(1).max(255).optional(),purchaseToken:it.z.string().min(1).max(16384)})]),Mf=it.z.strictObject({requestId:it.z.uuid(),orderId:it.z.uuid(),purchaseIntentId:it.z.uuid(),status:it.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:it.z.boolean(),completion:it.z.strictObject({transactionIds:it.z.array(it.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:it.z.boolean()}).nullable()});var L=require("zod"),gu=L.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),C0=L.z.record(L.z.string(),L.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),_0=3,To=20,E0=_0*To,hu=L.z.strictObject({type:L.z.literal("product"),productId:gu}),qf={type:L.z.literal("group"),key:L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.z.string().trim().min(1).max(80)},R0=L.z.discriminatedUnion("type",[hu,L.z.strictObject({...qf,items:L.z.array(hu).max(To)})]),k0=L.z.discriminatedUnion("type",[hu,L.z.strictObject({...qf,items:L.z.array(R0).max(To)})]),j0=L.z.array(k0).max(To).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>To||i>E0)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function yu(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:yu(t))}var Fi=L.z.strictObject({lookupKey:L.z.string().trim().min(1).max(200),displayName:L.z.string().trim().min(1).max(1500),items:j0,metadata:C0}),T0=L.z.strictObject({product:L.z.record(L.z.string(),L.z.json()),prices:L.z.array(L.z.record(L.z.string(),L.z.json())),entitlements:L.z.array(L.z.record(L.z.string(),L.z.json())),freeTrials:L.z.array(L.z.record(L.z.string(),L.z.json())),licenses:L.z.array(L.z.record(L.z.string(),L.z.json()))}),Uf=Fi.extend({id:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),state:L.z.enum(["active","archived"]),isCurrent:L.z.boolean(),revision:L.z.number().int().nonnegative(),publishedVersionId:L.z.uuid().nullable(),createdAt:L.z.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"})}),Bf=L.z.strictObject({id:L.z.uuid(),offeringId:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),version:L.z.number().int().positive(),document:Fi,productEvidence:L.z.record(gu,T0),createdAt:L.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=yu(e.document);(!n.length||F0(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"})}),N0=L.z.strictObject({rows:L.z.array(Uf).max(200),versions:L.z.array(Bf).max(500)}),o1=L.z.discriminatedUnion("action",[L.z.strictObject({action:L.z.literal("create"),document:Fi}),L.z.strictObject({action:L.z.literal("save"),id:L.z.uuid(),revision:L.z.number().int().nonnegative(),document:Fi}),L.z.strictObject({action:L.z.enum(["publish","set_current","archive","restore"]),id:L.z.uuid(),revision:L.z.number().int().nonnegative()})]),a1=L.z.strictObject({record:Uf,version:Bf.nullable()}),Vf=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("current")}),L.z.strictObject({type:L.z.literal("id"),id:L.z.uuid()}),L.z.strictObject({type:L.z.literal("lookup_key"),lookupKey:L.z.string().min(1).max(200)}),L.z.strictObject({type:L.z.literal("version"),versionId:L.z.uuid()})]),D0=L.z.strictObject({internalId:gu,id:L.z.string(),name:L.z.string().nullable(),version:L.z.number().int().positive(),archived:L.z.boolean()}),s1=N0.extend({products:L.z.array(D0).max(500),pagination:L.z.strictObject({rows:L.z.string().nullable(),versions:L.z.string().nullable(),products:L.z.string().nullable()}).optional()});function F0(e){let t=[];yu(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}var No=require("zod");var Lf=No.z.strictObject({id:No.z.uuid(),offeringId:No.z.uuid(),version:No.z.number().int().positive(),document:Fi});var Ot=require("zod");var Ae=require("zod");var ti=require("zod");var ss=ti.z.strictObject({items:ti.z.array(ti.z.strictObject({productVersionId:ti.z.string().min(1).max(200),label:ti.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:ti.z.string().min(1).max(200).nullable(),grouping:$a.optional()});function zf(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 Au=Ae.z.discriminatedUnion("type",[Ae.z.strictObject({type:Ae.z.literal("event"),event:Ae.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),Ae.z.strictObject({type:Ae.z.literal("open_url"),url:Ae.z.url().refine(e=>new URL(e).protocol==="https:")})]),M0=hn,q0=Ae.z.discriminatedUnion("type",[Ae.z.object({type:Ae.z.literal("checkout"),product:Ka}).strict(),Ae.z.object({type:Ae.z.literal("close")}).strict(),Ae.z.object({type:Ae.z.literal("action"),action:Au}).strict()]),Mi=Ae.z.object({schemaVersion:Ae.z.literal(3),kind:Ae.z.literal("paywall"),name:Ae.z.string().trim().min(1).max(80),presentation:jn,requirement:_n.optional(),products:ss,offeringVersionId:Ae.z.uuid().nullable(),offeringId:Ae.z.uuid(),screen:M0,buttons:Ae.z.record(Ae.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),q0)}).strict(),b1=Mi.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 B0(e))t.addIssue({code:"custom",message:r});for(let r of U0(e))t.addIssue({code:"custom",message:r});fr(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 U0(e){let t=e.products.items.map(a=>a.productVersionId),n=Em(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&&(!Ga(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")),Yt(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"),Yt(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 B0(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),nr(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 $f=Ae.z.object({id:Ae.z.uuid(),projectId:Ae.z.uuid(),environmentId:Ae.z.uuid(),revision:Ae.z.number().int().nonnegative(),state:Ae.z.enum(["active","archived"]),publishedVersionId:Ae.z.uuid().nullable(),updatedAt:Ae.z.iso.datetime({offset:!0}),draft:Mi}).strict(),x1=Ae.z.object({rows:Ae.z.array($f).max(200),nextCursor:Ae.z.uuid().nullable()}).strict(),S1=$f.omit({draft:!0}).extend({name:Ae.z.string(),productCount:Ae.z.number().int().nonnegative()}).strict(),I1=Ae.z.discriminatedUnion("action",[Ae.z.object({action:Ae.z.literal("save"),id:Ae.z.uuid().nullable(),revision:Ae.z.number().int().nonnegative(),document:Mi}).strict(),Ae.z.object({action:Ae.z.enum(["publish","archive"]),id:Ae.z.uuid(),revision:Ae.z.number().int().nonnegative()}).strict()]),v1=Ae.z.object({paywalls:Ae.z.array(Ae.z.object({id:Ae.z.uuid(),paywallId:Ae.z.uuid(),version:Ae.z.number().int().positive(),name:Ae.z.string().min(1).max(80),presentation:jn,buttons:Mi.shape.buttons}).strict()).max(500),limited:Ae.z.boolean()}).strict();var Re=require("zod");var Kt=require("zod");var qi=Kt.z.string().regex(/^[a-f0-9]{64}$/),V0=La.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Gf=Kt.z.strictObject({couponDigests:Kt.z.record(Kt.z.uuid(),qi),variables:Kt.z.record(En,Kt.z.record(Kt.z.uuid(),Kt.z.partialRecord(Kt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.z.string()))),locales:Kt.z.record(En,Pi.extend({nodes:Kt.z.record(Kt.z.string(),Kt.z.strictObject({base:V0})),plans:Kt.z.object({}).strict(),pickers:Kt.z.object({}).strict()}).omit({paywall:!0}))});var ze=require("zod");var Do=require("zod"),bu=Do.z.strictObject({eventsEnabled:Do.z.boolean(),experimentViewsEnabled:Do.z.boolean(),featureUsageEnabled:Do.z.boolean()}),_1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Kf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var xu=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),L0=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(xu).max(100)}),z0=$.z.strictObject({id:$.z.string().min(1).max(255),condition:nn,gate:$.z.boolean().optional()}),$0=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),Hf={condition:nn.optional(),parentConditions:$.z.array(z0).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(L0).max(100).optional(),ranges:$.z.array(xu).max(20).optional(),meta:$.z.array($0).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},Ui=$.z.strictObject({...Hf,key:$.z.string().min(1).max(255),variations:$.z.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Su=$.z.strictObject({value:ve,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),G0=$.z.strictObject({...Hf,id:$.z.string().max(255).optional(),force:ve.optional(),variations:$.z.array(ve).min(2).max(20).optional(),key:$.z.string().optional(),range:xu.optional(),tracks:$.z.array($.z.strictObject({experiment:Ui,result:Su})).max(100).optional()}),K0=$.z.strictObject({defaultValue:ve.optional(),rules:$.z.array(G0).max(500).optional()}),Fo=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:nn})])),vn=$.z.strictObject({scope:Me,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),K0),savedGroups:Fo,experiments:$.z.record($.z.uuid(),Ui)});var Mo=vn.extend({analyticsConfig:bu,remoteFeatures:ze.z.array(ze.z.string().min(1).max(255)).max(500)}),Iu=Mo.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"})}),Qf=ze.z.strictObject({attributes:Et,features:ze.z.array(ze.z.string().min(1).max(255)).max(500).optional(),customerId:ze.z.uuid().optional()}),H0=ze.z.strictObject({value:ve,source:ze.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ze.z.boolean(),off:ze.z.boolean(),ruleId:ze.z.string(),experimentResult:Su.optional()}),cs=ze.z.strictObject({generation:vn.shape.generation,evaluatedAt:vn.shape.evaluatedAt,expiresAt:vn.shape.expiresAt,features:ze.z.record(ze.z.string(),H0),merchandiseContext:ze.z.strictObject({merchandiseId:ze.z.uuid(),merchandise:Et}).optional()}),Jf=ze.z.strictObject({customerId:ze.z.uuid().optional(),events:ze.z.array(ze.z.strictObject({eventUuid:ze.z.uuid(),timestamp:ze.z.iso.datetime({offset:!0}),name:ze.z.string().min(1).max(255),merchandise:kp.optional(),properties:ze.z.record(ze.z.string(),ve).default({}),deviceId:ze.z.string().min(1).max(255).optional(),sessionId:ze.z.string().min(1).max(255).optional()})).min(1).max(100)}),Zf=ze.z.strictObject({inserted:ze.z.number().int().nonnegative(),duplicates:ze.z.number().int().nonnegative(),rejected:ze.z.number().int().nonnegative(),skipped:ze.z.number().int().nonnegative(),analyticsConfig:bu});var z=require("zod");var Wf=require("zod"),Yf=Wf.z.enum(["funnel-run/1","funnel-process/1"]),Xf="funnel-process/1";function vu(e,t=[]){let n=[];Yt(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(Ha(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 eh(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>eh(t)??[])}}function Q0(e){let t=e.pages.map(i=>{let a=eh(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(Ha({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 th(e,t=[]){let n=hn.parse(structuredClone(Q0(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=vu(n,t);if(i.length)throw new Error(i.join("; "));return n}var Q=require("zod");var M=require("zod");var ft=require("zod"),us=ft.z.strictObject({schemaVersion:ft.z.literal(1),renderKey:ft.z.string().min(1).max(256),routeTemplate:ft.z.string().startsWith("/").max(2048),selectors:ft.z.array(ft.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ft.z.array(ft.z.number().int().min(0)).min(1),absent:ft.z.array(ft.z.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"})}),nh=ft.z.strictObject({renderKey:ft.z.string().min(1).max(256),routeKey:ft.z.string().min(1).max(256),stateKey:ft.z.string().min(1).max(256),documentKey:ft.z.string().min(1).max(256),documentHash:ft.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:ft.z.string().min(1).max(256),entryMode:ft.z.enum(["hard","soft"]),match:ft.z.strictObject({present:ft.z.array(ft.z.number().int().min(0)),absent:ft.z.array(ft.z.number().int().min(0))})});var yr=require("zod"),J0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],wu="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Z0=yr.z.string().regex(new RegExp(`^${wu}/${wu}/${wu}/manifest\\.json$`)),rh=yr.z.strictObject({kind:yr.z.literal("gcs-resumable"),url:yr.z.url(),bucket:yr.z.enum(J0),objectKey:Z0,byteLength:yr.z.number().int().positive(),expiresAt:yr.z.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 St=M.z.string().min(1).max(256),yn=M.z.string().regex(/^[a-f0-9]{64}$/),ls=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:yn,sourceGraphDigest:yn,pageKey:St,stateKey:St,documentKey:St,documentHash:yn,elementKey:St.optional(),nodeId:St.optional(),contentHash:yn.optional(),renderKey:St.optional()}),ih=M.z.strictObject({pageKey:St,documentKey:St,expectedDocumentHash:yn,renderKey:St.optional(),nodeId:St,elementKey:St,expectedContentHash:yn,property:M.z.enum(["text","fontSize","color"]),value:M.z.union([M.z.string().max(4e3),M.z.number().finite()])}),oh=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:yn,sourceGraphDigest:yn,pageKey:St,stateKey:St,documentKey:St,documentHash:yn,renderKey:St.optional(),patches:M.z.array(ih.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),W0=/^[a-z][a-z0-9-]{0,39}$/,qo=M.z.string().regex(W0),Pu=M.z.enum(["web","ios","android"]),G1=M.z.discriminatedUnion("action",[M.z.strictObject({action:M.z.literal("register"),requestId:M.z.uuid(),client:qo,platform:Pu,label:M.z.string().trim().min(1).max(100),sha256:yn,bytes:M.z.number().int().min(1),transferBytes:M.z.number().int().min(1)}),M.z.strictObject({action:M.z.literal("complete"),versionId:M.z.uuid()}),M.z.strictObject({action:M.z.literal("current"),versionId:M.z.uuid(),expectedCurrent:M.z.uuid().nullable()}),M.z.strictObject({action:M.z.literal("delivery"),enabled:M.z.boolean()}),M.z.strictObject({action:M.z.literal("changes"),versionId:M.z.uuid(),experimentId:M.z.uuid(),variationId:St,changesetId:M.z.uuid().nullable(),expectedRevision:yn.nullable(),editorUrl:M.z.string().url().max(2048),patches:M.z.array(ih).max(200)})]),Cu=M.z.strictObject({id:M.z.uuid(),projectId:M.z.uuid(),environmentId:M.z.uuid(),clientKey:qo,platform:Pu,label:M.z.string(),sha256:yn,bytes:M.z.number().int().positive(),objectKey:M.z.string(),state:M.z.enum(["uploading","ready","rejected"]),isCurrent:M.z.boolean(),revision:M.z.number().int().nonnegative(),createdAt:M.z.string(),expiresAt:M.z.string(),readyAt:M.z.string().nullable(),summary:M.z.record(M.z.string(),M.z.json()),routeTree:M.z.json().nullable(),validation:M.z.record(M.z.string(),M.z.json())}),Y0=M.z.strictObject({key:qo,platform:Pu,currentId:M.z.uuid().nullable()}),K1=M.z.strictObject({rows:M.z.array(Cu).max(100),nextCursor:M.z.uuid().nullable(),clients:M.z.array(Y0).max(20)}),Ou=M.z.strictObject({storedBytes:M.z.number().int().nonnegative(),reservedBytes:M.z.number().int().nonnegative(),chargedBytes:M.z.number().int().nonnegative(),versions:M.z.number().int().nonnegative(),objects:M.z.number().int().nonnegative(),orphanObjects:M.z.number().int().nonnegative(),missingReadyObjects:M.z.number().int().nonnegative(),unknownObjectSizes:M.z.number().int().nonnegative(),byteLimit:M.z.number().int().positive(),versionLimit:M.z.number().int().positive(),remainingBytes:M.z.number().int().nonnegative()}),H1=M.z.strictObject({asOf:M.z.iso.datetime({offset:!0}),reclamation:M.z.literal("manual-review-required"),buckets:M.z.strictObject({source:Ou,runtime:Ou,previews:Ou})}),Q1=M.z.strictObject({version:Cu,actorId:M.z.uuid(),claims:M.z.record(M.z.string(),M.z.json())}),J1=M.z.strictObject({version:Cu,upload:rh.nullable()}),Z1=M.z.object({format:M.z.literal("indiana-route-state-index"),schemaVersion:M.z.literal(3),routes:M.z.array(M.z.object({routeKey:St,path:M.z.string(),documentKey:St,documentHash:yn,initialStateKey:St,initialRenderKey:St})),renders:M.z.array(nh)}).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"})}),W1=M.z.strictObject({rows:M.z.array(M.z.object({id:M.z.uuid(),name:M.z.string(),status:M.z.string(),variations:M.z.array(M.z.object({id:St,key:St,name:M.z.string().optional()}).loose())}).loose()),limited:M.z.boolean()}),Y1=M.z.strictObject({enabled:M.z.boolean(),allowedOrigins:M.z.array(M.z.string())});var ni=require("zod");var ah=ni.z.strictObject({id:ni.z.uuid(),name:ni.z.string().trim().min(1).max(80),client:qo,source:ls,event:ni.z.enum(["screen_enter","button_click"]),cooldownSeconds:ni.z.number().int().min(0).max(2592e3),behavior:ni.z.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"})});var Ke=require("zod");var _u=ve,X0=["parameters","answers","results","variables"];function Eu(e){return X0.some(t=>e===t||e.startsWith(t+"."))}function Ru(e){let t={};for(let[r,i]of Object.entries(Qa(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])=>!Eu(r))),variables:t}}var gt=require("zod");var ds=gt.z.discriminatedUnion("kind",[gt.z.object({kind:gt.z.literal("ledger"),cursor:Va}).strict(),gt.z.object({kind:gt.z.literal("billing"),cursor:gt.z.uuid()}).strict()]),eI=gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ar=gt.z.record(gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gt.z.union([gt.z.string().max(500),gt.z.boolean(),gt.z.array(gt.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),tI=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function ku(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>ku(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||tI.test(n)||ku(r,t+1)))}var nI=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,br=gt.z.record(eI,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!ku(e)&&!nI.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var sh=gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ps=gt.z.array(gt.z.object({variable:sh,componentId:sh,required:gt.z.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"),cE=gt.z.object({bindings:ps,answers:Ar,values:gt.z.record(gt.z.string(),ve).optional()}).strict();var ch=require("zod"),ms=ch.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var ju=Ke.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),uh=Ke.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),lh=br.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Tu=Ke.z.record(ju,Ke.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),rI=Ln,dh=Ke.z.strictObject({type:Ke.z.literal("external_task"),endpointId:Ke.z.uuid(),taskKey:ju,inputs:Ke.z.record(ju,rI).refine(e=>Object.keys(e).length<=20),outputs:Tu}),ph=Ke.z.strictObject({maxAttempts:Ke.z.number().int().min(1).max(5),retryDelaySeconds:Ke.z.number().int().min(1).max(30),backoff:Ke.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Ke.z.number().int().min(1).max(10),timeoutSeconds:Ke.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var gE=Ke.z.strictObject({outcome:Ke.z.enum(["success","failure"]),data:lh});var yE=Ke.z.discriminatedUnion("operation",[Ke.z.strictObject({operation:Ke.z.literal("signal"),runId:Ke.z.uuid(),nodeId:uh,eventName:ms,eventId:Ke.z.uuid(),data:lh}),Ke.z.strictObject({operation:Ke.z.literal("read_results"),runId:Ke.z.uuid()})]),AE=Ke.z.strictObject({scope:Me,runId:Ke.z.uuid(),eventId:Ke.z.uuid(),accepted:Ke.z.boolean()}),iI=Ke.z.record(uh,_u),bE=Ke.z.strictObject({scope:Me,runId:Ke.z.uuid(),results:iI});var Fn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},mh="00000000-0000-0000-0000-000000000000";var J=require("zod");var Xe=require("zod");var wE=Xe.z.enum(["local","remote"]),Nu=Xe.z.strictObject({port:Xe.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Xe.z.array(Xe.z.strictObject({expected:mo.nullable(),next:mo})).max(100),exposures:Xe.z.array(ve).max(100),features:Xe.z.array(ve).max(100)}),fh=Xe.z.strictObject({type:Xe.z.literal("evaluate"),receiptId:Xe.z.uuid(),environmentId:Xe.z.uuid(),policyRevision:Xe.z.number().int().nonnegative(),attributes:Et,sticky:Xe.z.record(Xe.z.string(),mo)}),hh=fh.extend({runId:Xe.z.uuid(),versionId:Xe.z.uuid(),nodeId:Xe.z.string().min(1).max(64),visit:Xe.z.number().int().nonnegative(),revision:Xe.z.number().int().nonnegative()}),Du=fh.omit({type:!0,receiptId:!0}).extend({type:Xe.z.literal("evaluate_segment")}),gh=Xe.z.strictObject({nodeId:Xe.z.string().min(1).max(64),result:Nu}),yh=Du.extend({runId:Xe.z.uuid(),versionId:Xe.z.uuid(),nodeId:Xe.z.string().min(1).max(64),visit:Xe.z.number().int().nonnegative(),revision:Xe.z.number().int().nonnegative(),parameters:br,answers:Ar,variables:Xe.z.record(Xe.z.string(),ve)});var ue=require("zod");var Fu=ue.z.array(ue.z.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"),fs=ue.z.intersection(Et,ue.z.looseObject({tags:Fu.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),hs=ue.z.string().trim().max(80),gs=ue.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ys=ue.z.union([ue.z.email().max(254),ue.z.literal("")]),As=ue.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Ah=ue.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),bh=ue.z.object({externalUserId:Ah.optional(),name:hs.default(""),email:ys.default(""),phone:gs.optional(),attributes:fs.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ri=ue.z.discriminatedUnion("type",[ue.z.strictObject({type:ue.z.literal("id"),value:ue.z.uuid()}),ue.z.strictObject({type:ue.z.literal("externalUserId"),value:Ah})]),Bi=ue.z.strictObject({name:hs.optional(),email:ys.optional(),phone:gs.optional(),attributes:fs.optional(),fingerprint:As.optional()}),bs=e=>!e.customerData||e.customer?.type==="externalUserId",xs="customerData requires an externalUserId customer",Vi=ue.z.object({id:ue.z.uuid(),externalUserId:ue.z.string().min(1).max(255).nullable(),name:hs,email:ys,phone:gs.optional(),attributes:fs,createdAt:ue.z.iso.datetime()}).strict(),xh=ue.z.object({customer:Vi,changed:ue.z.boolean(),replayed:ue.z.boolean()}).strict(),oI=ue.z.discriminatedUnion("type",[ue.z.object({type:ue.z.literal("id"),value:ue.z.uuid()}).strict(),ue.z.object({type:ue.z.literal("externalUserId"),value:ue.z.string().trim().min(1).max(255)}).strict()]),aI=ue.z.object({name:hs.optional(),email:ys.optional(),phone:gs.optional(),attributes:fs.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.z.array(ue.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.z.strictObject({add:Fu,remove:Fu}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Mu=ue.z.object({lookup:oI}).strict(),Sh=Mu.extend({requestId:ue.z.uuid(),patch:aI}).strict(),Ih=ue.z.object({search:ue.z.string().trim().max(200).default(""),tag:ue.z.string().trim().max(40).default(""),planId:ue.z.string().max(200).default(""),versionId:ue.z.string().max(200).default(""),holdingStatus:ue.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),createdUntil:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),offset:ue.z.coerce.number().int().min(0).max(1e5).default(0),limit:ue.z.coerce.number().int().min(1).max(100).default(50)}).strict(),vh=ue.z.object({customers:Vi.array(),hasMore:ue.z.boolean(),total:ue.z.number().int().nonnegative().nullable(),evaluatedAt:ue.z.iso.datetime()}).strict();var Uo=J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("literal"),value:ve}),J.z.strictObject({type:J.z.literal("variable"),key:wt,path:Dn.optional()}),J.z.strictObject({type:J.z.literal("feature"),featureKey:J.z.string().min(1).max(128)})]),sI=J.z.strictObject({requestId:J.z.uuid(),decisionId:J.z.uuid(),customerId:J.z.uuid(),externalUserId:J.z.string().min(1).max(255).nullable(),versionId:J.z.uuid(),receiptId:J.z.uuid(),value:ve}),cI={funnelId:J.z.uuid(),requestId:J.z.uuid(),customer:ri,customerData:Bi.optional(),attributes:Et.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},NE=J.z.discriminatedUnion("operation",[J.z.strictObject({operation:J.z.literal("decide"),...cI}).refine(bs,xs),J.z.strictObject({operation:J.z.literal("read_decision"),decisionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("evaluate_decision"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),receiptId:J.z.uuid(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),result:Nu}),J.z.strictObject({operation:J.z.literal("feature_config"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("commit_decision_segment"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),steps:J.z.array(gh).max(32),boundary:J.z.strictObject({nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative()}).optional()}),J.z.strictObject({operation:J.z.literal("segment_configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid().optional()}),J.z.strictObject({operation:J.z.literal("local_configuration"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("report_used"),decisionId:J.z.uuid(),eventId:J.z.uuid(),occurredAt:J.z.iso.datetime({offset:!0}),reference:J.z.string().min(1).max(128).optional()})]),DE=J.z.strictObject({scope:Me,decisionId:J.z.uuid(),requestId:J.z.uuid(),status:J.z.enum(["pending","completed","failed"]),decision:sI.nullable(),evaluation:J.z.discriminatedUnion("type",[hh,yh]).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"),FE=J.z.strictObject({scope:Me,decisionId:J.z.uuid(),eventId:J.z.uuid(),source:J.z.literal("caller_reported")});var Mt=require("zod");var wh=Mt.z.strictObject({type:Mt.z.literal("bundle"),paywall:Ln.optional(),offering:Ln.optional(),coupons:Ln,data:Ln}),uI=e=>Mt.z.strictObject({type:Mt.z.literal(e),id:Mt.z.uuid()}),VE=Mt.z.strictObject({type:Mt.z.literal("bundle"),paywallVersionId:Mt.z.uuid().optional(),offeringVersionId:Mt.z.uuid().optional(),couponIds:Mt.z.array(Mt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var LE=Mt.z.strictObject({type:Mt.z.literal("bundle"),offering:uI("offering_version").nullable(),paywall:Mt.z.strictObject({versionId:Mt.z.uuid(),paywallId:Mt.z.uuid(),offeringVersionId:Mt.z.uuid()}).nullable(),coupons:Mt.z.array(fo).max(20),data:ve});var wn=require("zod");var An=require("zod");var Oh=An.z.union([An.z.string(),An.z.number().finite(),An.z.boolean(),An.z.null()]),lI=An.z.union([Oh,An.z.array(Oh).min(1).max(20)]),dI=An.z.record(Dn,lI).refine(e=>Object.keys(e).length<=10),Ph=An.z.strictObject({path:Dn,type:An.z.enum(["string","number","boolean","strings"]),nullable:An.z.boolean().optional(),aggregation:An.z.enum(["count","exists"]).optional(),where:dI.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 pI=["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"],Ch=wn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),mI=Ln,_h=wn.z.discriminatedUnion("type",[dh,wn.z.strictObject({type:wn.z.literal("claim_offer"),coupon:Ln}),wn.z.strictObject({type:wn.z.literal("event"),event:Ch}),wn.z.strictObject({type:wn.z.literal("api"),operation:wn.z.enum(pI),inputs:wn.z.record(Dn,mI).refine(e=>Object.keys(e).length<=40),outputs:wn.z.record(Ch,Ph).refine(e=>Object.keys(e).length<=20)})]);var mt=ms,fI=Q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),bn={id:mt,name:Q.z.string().trim().min(1).max(80),position:Q.z.strictObject({x:Q.z.number().finite(),y:Q.z.number().finite()}).optional()},hI={success:mt,cancel:mt,unavailable:mt,failure:mt},qu=Q.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Uu=Q.z.enum(["same_window","new_window"]),gI=Q.z.discriminatedUnion("type",[Q.z.strictObject({...bn,type:Q.z.literal("entry"),next:mt,triggers:Q.z.array(ah).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.z.strictObject({...bn,type:Q.z.literal("screen"),screenId:mt,presentation:jn,outputs:Q.z.record(mt,mt),offering:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("variable"),key:wt}),Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()})]).optional()}),Q.z.strictObject({...bn,type:Q.z.literal("offering"),configuration:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()}),Q.z.strictObject({source:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("coupon"),couponId:Q.z.uuid(),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("coupons"),couponIds:Q.z.array(Q.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("output"),value:Q.z.discriminatedUnion("type",[...Uo.options,wh,Q.z.strictObject({type:Q.z.literal("selection"),screenId:mt,offeringKey:wt})])}),Q.z.strictObject({...bn,type:Q.z.literal("condition"),cases:Q.z.array(Q.z.strictObject({condition:nn,target:mt})).min(1).max(50),default:mt}),Q.z.strictObject({...bn,type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("split"),experimentId:Q.z.uuid(),applyPageExperiment:Q.z.literal(!0).optional(),routes:Q.z.record(fI,mt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:mt}),Q.z.strictObject({...bn,type:Q.z.literal("action"),...hI,execution:ph,action:_h,writes:Xc.optional()}),Q.z.strictObject({...bn,type:Q.z.literal("external_page"),appManifest:ls.optional(),url:qu,openIn:Uu,opened:mt,failed:mt}),Q.z.strictObject({...bn,type:Q.z.literal("end"),outcome:Q.z.enum(["completed","closed","ineligible","failed"]),output:Uo.optional()}),Q.z.strictObject({...bn,type:Q.z.literal("wait"),writes:Xc.optional(),wait:Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("duration"),delaySeconds:Q.z.number().int().min(1).max(2592e3),elapsed:mt}),Q.z.strictObject({type:Q.z.literal("event"),eventName:mt,outputs:Tu,timeoutSeconds:Q.z.number().int().min(1).max(2592e3),received:mt,timeout:mt})])})]),Bu=Q.z.strictObject({version:Q.z.literal(5),entry:mt,nodes:Q.z.array(gI).min(1).max(Fn.flowNodes)}),Vu=Bu.superRefine((e,t)=>{yI(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ss(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 yI(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>Fn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Fn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let p of Ss(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 Ss(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 Lu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Eh(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 pr(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]}var q=require("zod");var Li=q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Is=e=>q.z.record(q.z.string(),ve).refine(t=>gn(t)<=e,"Funnel evidence exceeds its byte budget"),hR=q.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),$u=q.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Gu=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("flag"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("experiment"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("saved_group"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("config"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("constant"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("paywall_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("offering_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("reward"),id:q.z.uuid()})]),Bo=q.z.strictObject({schemaVersion:q.z.literal(1),kind:$u,selector:Gu.nullable(),context:Is(131072),contract:q.z.strictObject({version:q.z.number().int().positive(),evaluator:q.z.string().min(1).max(128),policyRevision:q.z.number().int().nonnegative()})}).refine(e=>gn(e)<=131072,"Node input exceeds its byte budget"),Rh=q.z.strictObject({schemaVersion:q.z.literal(1),kind:$u,outcome:q.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Is(131072),route:q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Is(131072)}).refine(e=>gn(e)<=131072,"Node result exceeds its byte budget"),gR=q.z.strictObject({schemaVersion:q.z.literal(1),operations:q.z.record(Li,q.z.strictObject({attempts:q.z.number().int().nonnegative(),maxAttempts:q.z.number().int().min(1).max(5),deadlineAt:q.z.iso.datetime({offset:!0}),retryAt:q.z.iso.datetime({offset:!0}).nullable(),error:q.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.z.strictObject({type:Li,id:q.z.uuid()}).nullable()}))}).refine(e=>gn(e)<=65536,"Execution state exceeds its byte budget"),ii={receiptId:q.z.uuid()},zu=q.z.iso.datetime({offset:!0}),yR=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("node_entered"),details:q.z.strictObject({kind:$u})}),q.z.strictObject({type:q.z.literal("presentation_shown"),details:q.z.strictObject({...ii,source:q.z.literal("client"),occurredAt:zu.optional()})}),q.z.strictObject({type:q.z.literal("decision_accepted"),details:q.z.strictObject(ii)}),q.z.strictObject({type:q.z.literal("signal_received"),details:q.z.strictObject({signalId:q.z.uuid(),nodeId:Li,eventName:Li,data:Is(8192),source:q.z.literal("server"),occurredAt:zu})}),q.z.strictObject({type:q.z.literal("signal_consumed"),details:q.z.strictObject({...ii,signalId:q.z.uuid()})}),q.z.strictObject({type:q.z.literal("wait_elapsed"),details:q.z.strictObject(ii)}),q.z.strictObject({type:q.z.literal("wait_timeout"),details:q.z.strictObject(ii)}),q.z.strictObject({type:q.z.literal("operation_completed"),details:q.z.strictObject({...ii,operation:Li,reference:q.z.strictObject({type:Li,id:q.z.uuid()}).nullable()})}),q.z.strictObject({type:q.z.literal("execution_recovered"),details:q.z.strictObject({generation:q.z.number().int().positive(),reason:q.z.enum(["interrupted","expired_lease","delivery_failed"])})}),q.z.strictObject({type:q.z.literal("execution_failed"),details:q.z.strictObject({generation:q.z.number().int().positive(),code:q.z.string().regex(/^[a-z_]{1,64}$/)})}),q.z.strictObject({type:q.z.literal("run_completed"),details:q.z.strictObject({outcome:q.z.enum(["completed","ineligible","failed"])})}),q.z.strictObject({type:q.z.literal("run_closed"),details:q.z.strictObject({source:q.z.enum(["client","server","expiry"])})}),q.z.strictObject({type:q.z.literal("treatment_used"),details:q.z.strictObject({...ii,source:q.z.enum(["client","server"]),occurredAt:zu,reference:q.z.string().min(1).max(128).optional()})})]);var On=z.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),AI=z.z.discriminatedUnion("type",[z.z.strictObject({id:On,type:z.z.literal("owned"),publicData:Gf.optional(),document:hn.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.z.strictObject({id:On,type:z.z.literal("paywall"),paywallVersionId:z.z.uuid()})]),Ku={executionContract:Yf.optional(),kind:z.z.literal("funnel"),schemaVersion:z.z.literal(4),screens:z.z.array(AI).max(Fn.pages),references:z.z.record(On,Gu).refine(e=>Object.keys(e).length<=500),inputs:z.z.array(z.z.strictObject({variable:On,screenId:On,componentId:On,required:z.z.boolean()})).max(Fn.questions),variables:z.z.record(wt,Ei).refine(e=>Object.keys(e).length<=Fn.logicNodes),outputSchema:_i,execution:z.z.strictObject({runTimeoutSeconds:z.z.number().int().min(1).max(Lu.runTimeoutSeconds),maxTransitions:z.z.number().int().min(1).max(Lu.maxTransitions)})},FR=z.z.strictObject({...Ku,graph:Bu});function bI(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 ws(e){return Array.isArray(e)?e.some(ws):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===mh:ws(n))}function xI(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=th(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&&!Ro(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}),bI(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"&&ws(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ws(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function kh(e,t){for(let{message:n,reason:r,path:i}of xI(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function jh(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}fr(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),nr(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"&&!In(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",g),d.type==="output"&&d.value.type==="literal"&&!In(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&&!eu(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 ru(v.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!nu(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 Xn(v.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let C of pr(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=>!In({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=[...Eh(d,c),...g?.type==="owned"?Ja(g.document).map(y=>nu(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]:[]:Ss(_)).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"?Ro(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)nr(d.root,()=>{l++});p+=h.document.actions.length}(l>Fn.components||p>Fn.actions||gn(e)>Fn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var SI=z.z.strictObject({...Ku,graph:Vu}).superRefine(jh),zi=z.z.strictObject({...Ku,graph:Vu,displayName:z.z.string().trim().min(1).max(80)}).superRefine(jh),MR=zi.superRefine(kh),qR=SI.superRefine(kh),vs=z.z.string().regex(Ut),Vo={requestId:z.z.uuid(),nodeId:On,visit:z.z.number().int().nonnegative(),revision:z.z.number().int().nonnegative(),customerToken:vs.optional()},II=z.z.discriminatedUnion("type",[z.z.strictObject({type:z.z.literal("screen"),output:On,answers:Ar,selection:z.z.record(On,z.z.union([z.z.string().max(200),z.z.boolean(),z.z.number().int().min(0).max(1e4)])).optional()}),z.z.strictObject({type:z.z.literal("paywall_quote"),featureQuantities:z.z.record(z.z.uuid(),z.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:On,productVersionId:z.z.uuid(),offerId:z.z.uuid().optional(),nativeOffer:ji.optional(),predecessor:z.z.strictObject({operationId:z.z.uuid().nullable(),generation:z.z.number().int().positive()}).optional()}),z.z.strictObject({type:z.z.literal("paywall_confirm"),operationId:z.z.uuid()}),z.z.strictObject({type:z.z.literal("paywall_cancel"),operationId:z.z.uuid()}),z.z.strictObject({type:z.z.literal("client_action"),receiptId:z.z.uuid(),outcome:z.z.enum(["success","cancel","failure","opened","failed"])})]),vI=z.z.object({nodeId:On,visit:z.z.number().int().nonnegative(),revision:z.z.number().int().nonnegative(),components:z.z.record(On,z.z.object({resourceKey:z.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.z.number().int().min(1).max(1e5),after:ds.nullable(),filter:z.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Rt=z.z.discriminatedUnion("operation",[z.z.strictObject({operation:z.z.literal("start"),funnelId:z.z.uuid(),requestId:z.z.uuid(),customer:ri.optional(),customerData:Bi.optional(),locale:z.z.string().min(1).max(35),parameters:br}).refine(bs,xs),z.z.strictObject({operation:z.z.literal("get"),settlementRequestId:z.z.uuid().optional(),data:vI.optional(),purchase:z.z.strictObject({receiptId:z.z.uuid(),operationId:z.z.uuid()}).optional(),customerToken:vs.optional()}),z.z.strictObject({operation:z.z.literal("resume"),requestId:z.z.uuid(),customerToken:vs.optional()}),z.z.strictObject({operation:z.z.literal("submit"),...Vo,input:II}),z.z.strictObject({operation:z.z.literal("back"),...Vo}),z.z.strictObject({operation:z.z.literal("shown"),...Vo}),z.z.strictObject({operation:z.z.literal("close"),...Vo}),z.z.strictObject({operation:z.z.literal("commit_segment"),...Vo,policyRevision:z.z.number().int().nonnegative(),generation:z.z.string().min(1).max(256)}),z.z.strictObject({operation:z.z.literal("review"),receiptId:z.z.uuid().optional(),customerToken:vs.optional()})]);function Os(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 Xn(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&&Eu(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)}}var ae=require("zod");function Th(e,t){let n=[],r={};Yt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Yt(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 Nh(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Yt(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}var $i=require("zod");var Dh=$i.z.object({defaultLocale:En,locales:$i.z.record(En,$i.z.object({name:$i.z.string().max(80),description:$i.z.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 wI=["customer_data","coupon_code"],Fh=ae.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),OI=ae.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ps=(e,t)=>new Set(e.map(t)).size===e.length,PI=ae.z.strictObject({currency:Ie,amountMinor:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),CI=ae.z.strictObject({featureId:ae.z.uuid(),name:ae.z.string().trim().min(1).max(120),allowance:ae.z.string().max(40).nullable(),access:ae.z.boolean()}),_I=ae.z.strictObject({stripe:ae.z.strictObject({prices:ae.z.array(PI).min(1).max(50)}).optional(),apple:ae.z.strictObject({productIds:ae.z.array(Fh).min(1).max(10)}).optional(),google:ae.z.strictObject({products:ae.z.array(ae.z.strictObject({productId:Fh,basePlanId:OI.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Ps(e.stripe.prices,n=>n.currency)||e.apple&&!Ps(e.apple.productIds,n=>n)||e.google&&!Ps(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),EI=ae.z.strictObject({name:ae.z.string().trim().min(1).max(80),interval:ae.z.enum(["free","week","month","year","one_time"]),intervalCount:ae.z.number().int().min(1).max(100),trial:ae.z.strictObject({days:ae.z.number().int().min(1).max(730),cardRequired:ae.z.boolean()}).nullable(),benefits:ae.z.array(CI).max(50).refine(e=>Ps(e,t=>t.featureId),"Duplicate benefit"),channels:_I,prepaid:ae.z.array(Po).max(100).optional()}),RI=ae.z.strictObject({digest:qi,content:ae.z.strictObject({discount:mr,duration:mn,appliesTo:Mc,displayCopy:Dh.nullable(),firstPurchaseOnly:ae.z.boolean(),qualificationRequired:ae.z.boolean(),startsAt:ae.z.iso.datetime().nullable(),endsAt:ae.z.iso.datetime().nullable(),grantWindowHours:ae.z.number().int().positive(),perCustomerLimit:ae.z.number().int().positive()})}),kI=ae.z.discriminatedUnion("type",[ae.z.strictObject({type:ae.z.literal("checkout"),product:Ka}),ae.z.strictObject({type:ae.z.literal("close")}),ae.z.strictObject({type:ae.z.literal("action"),action:Au})]),Cs=ae.z.strictObject({kind:ae.z.literal("paywall"),formatVersion:ae.z.literal(1),name:ae.z.string().trim().min(1).max(80),offeringVersionId:ae.z.uuid(),presentation:jn,screen:hn,products:ss,catalog:ae.z.record(ae.z.uuid(),EI),buttons:ae.z.record(Ve,kI),coupons:ae.z.record(ae.z.uuid(),RI)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Th(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),vu(r,wI).forEach(n),fr(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Yt(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")}),Mh=ae.z.strictObject({state:ae.z.enum(["published","archived"]),controlRevision:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.z.uuid(),versions:ae.z.record(ae.z.uuid(),ae.z.strictObject({version:ae.z.number().int().positive(),artifact:ae.z.string().min(1),sourceDigest:ae.z.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},Hu=Re.z.string().regex(/^[a-f0-9]{64}$/),Qu=Re.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Zu=Me.extend({environmentId:Re.z.uuid()}),qh=Re.z.strictObject({features:Re.z.array(Re.z.string()).max(500),experiments:Re.z.record(Re.z.uuid(),Re.z.array(Re.z.string()).max(20)),savedGroups:Re.z.array(Re.z.string()).max(1e3)}),Wu=Re.z.strictObject({kind:Re.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.z.number().int().positive(),url:Re.z.string().min(1).max(2048),sha256:Hu,byteLength:Re.z.number().int().positive().max(sn.maxArtifactBytes),generation:Hu.optional()}),jI=Re.z.strictObject({state:Re.z.enum(["active","paused","archived"]),controlRevision:Qu,evaluationMode:Re.z.enum(["local","remote"]),evaluationRevision:Qu,currentVersionId:Re.z.uuid(),versions:Re.z.record(Re.z.uuid(),Re.z.strictObject({artifact:Re.z.string(),dependencies:qh,definitionDigest:qi.optional(),couponDigests:Re.z.record(Re.z.uuid(),qi).optional()}))}),Yu=Re.z.strictObject({kind:Re.z.literal("sdk_configuration"),schemaVersion:Re.z.literal(1),scope:Zu,revision:Qu,generation:Hu,policy:Re.z.strictObject({refreshIntervalSeconds:Re.z.number().positive().max(15),maxControlAgeSeconds:Re.z.number().positive().max(60)}),gb:Re.z.strictObject({features:Re.z.string().nullable(),pageExperiments:Re.z.string().nullable()}),artifacts:Re.z.record(Re.z.string(),Wu),funnels:Re.z.record(Re.z.uuid(),jI),paywalls:Re.z.record(Re.z.uuid(),Mh).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 kt(e){if(Array.isArray(e))return`[${e.map(kt).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)}:${kt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Xu(e){return ir(ar(typeof e=="string"?new TextEncoder().encode(e):e))}function Uh(e){return Xu(kt(e))}var Ju=class extends Error{constructor(n,r){super(n);Be(this,"dependency",r)}};function Bh(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 Ju(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=Os(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||!In(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 Xn(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 qh.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 Vh(e){return zi.parse(e)}var Lh=Ot.z.strictObject({processContext:Wa.optional(),...ki,selector:Ot.z.discriminatedUnion("type",[Ot.z.strictObject({type:Ot.z.literal("paywall"),paywallId:Ot.z.uuid()}),Ot.z.strictObject({type:Ot.z.literal("version"),versionId:Ot.z.uuid()})]),customerId:Ot.z.uuid().optional(),commerce:Si,locale:Ot.z.string().min(1).max(35),requirement:_n.optional()}),Lo=Ot.z.strictObject({id:Ot.z.uuid(),paywallId:Ot.z.uuid(),version:Ot.z.number().int().positive(),document:Mi.omit({requirement:!0,offeringId:!0}),offering:Ot.z.strictObject({id:Ot.z.uuid()}),content:Ot.z.strictObject({environmentId:Ot.z.uuid(),offeringVersionId:Ot.z.uuid(),artifact:Wu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Pi,check:ur.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"})}),oi=Ot.z.strictObject(Lo.shape).omit({document:!0,offering:!0}).extend({content:Lo.shape.content.unwrap()});function zh(e,t){let n=Cs.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 Lo.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}})}var Ht=require("zod");var $h={requestId:Ht.z.uuid(),sourceId:Ht.z.uuid(),expectedAvailable:Wt},Gh=Ht.z.discriminatedUnion("action",[Ht.z.strictObject({...$h,action:Ht.z.enum(["add","subtract","set_remaining"]),amount:de}),Ht.z.strictObject({...$h,action:Ht.z.literal("edit"),granted:de,expiresAt:Ht.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.z.number().int().nonnegative()})]),el=Ht.z.strictObject({sourceId:Ht.z.uuid(),available:Wt,held:Wt,spent:Wt,adjustmentGrantId:Ht.z.uuid().nullable()}),Kh=el.extend({granted:Wt,expiresAt:Ht.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.z.iso.datetime({offset:!0}).nullable(),revision:Ht.z.number().int().nonnegative()});var cn=require("zod"),Hh=cn.z.discriminatedUnion("action",[cn.z.object({action:cn.z.literal("upsert"),externalId:cn.z.string().min(1).max(128),name:cn.z.string().trim().min(1).max(80)}).strict(),cn.z.object({action:cn.z.literal("archive"),entityId:cn.z.uuid()}).strict()]),Qh=cn.z.object({id:cn.z.uuid(),externalId:cn.z.string().min(1).max(128),name:cn.z.string().min(1).max(80),archived:cn.z.boolean()}).strict();var $t=require("zod");var xr=require("zod"),Zh=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Jh=xr.z.string().regex(/.+\/.+/),tl=xr.z.number().min(-100),ai=xr.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),TI=xr.z.strictObject({input:ai,output:ai,cache_read:ai.optional(),cache_write:ai.optional(),reasoning:ai.optional(),input_audio:ai.optional(),output_audio:ai.optional()}),nl=(e,t)=>xr.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),Rk=xr.z.strictObject({defaultMarkup:tl,providerMarkups:nl(xr.z.string().min(1),tl),modelMarkups:nl(Jh,tl),customModels:nl(Jh,TI.partial())});var xe=require("zod"),si=xe.z.iso.datetime({offset:!0}),Sr=xe.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),NI=xe.z.discriminatedUnion("kind",[xe.z.object({kind:xe.z.literal("absolute"),from:si,to:si}).strict(),xe.z.object({kind:xe.z.literal("last_days"),days:xe.z.union([xe.z.literal(1),xe.z.literal(7),xe.z.literal(30),xe.z.literal(90)])}).strict(),xe.z.object({kind:xe.z.literal("billing_cycles"),membershipId:xe.z.uuid(),count:xe.z.number().int().min(1).max(12),includeCurrent:xe.z.boolean()}).strict()]),Wh=xe.z.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"),DI=xe.z.object({key:xe.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:xe.z.array(xe.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ci=xe.z.object({range:NI,timezone:Wh,filterBy:xe.z.array(DI).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:xe.z.enum(["hour","day","week","month"]),internal_feature_id:xe.z.uuid().nullable(),entityId:xe.z.uuid().nullable(),topN:xe.z.number().int().min(1).max(50).nullable(),groupBy:xe.z.union([xe.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),xe.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:xe.z.object({bucket:si,group:xe.z.string().max(240),isOther:xe.z.boolean(),internal_feature_id:xe.z.uuid(),resourceId:xe.z.uuid()}).strict().nullable(),limit:xe.z.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)"})}),Yh=xe.z.object({from:si,to:si,interval:xe.z.enum(["hour","day","week","month"]),timezone:Wh,rows:xe.z.array(xe.z.object({bucket:si,group:xe.z.string().max(240),isOther:xe.z.boolean(),internal_feature_id:xe.z.uuid(),resourceId:xe.z.uuid(),consumedUnits:Sr,refundedUnits:Sr,reservedUnits:Sr,charged:Sr,refunded:Sr,reserved:Sr,netUnits:Sr,netCharged:Sr}).strict()).max(100),nextCursor:xe.z.object({bucket:si,group:xe.z.string().max(240),isOther:xe.z.boolean(),internal_feature_id:xe.z.uuid(),resourceId:xe.z.uuid()}).strict().nullable()}).strict();var Gi=$t.z.string().regex(/^(0|[1-9]\d{0,29})$/),Xh=$t.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),rl=$t.z.strictObject({bucket:$t.z.iso.datetime({offset:!0}),group:$t.z.string().max(240),isOther:$t.z.boolean(),internal_feature_id:$t.z.uuid()}),eg=$t.z.strictObject({...ci.shape,groupBy:$t.z.union([$t.z.enum(["customer","entity","entitlement"]),$t.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:rl.nullable()}).superRefine((e,t)=>{let n=ci.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),tg=$t.z.strictObject({from:$t.z.iso.datetime({offset:!0}),to:$t.z.iso.datetime({offset:!0}),interval:ci.shape.interval,timezone:ci.shape.timezone,rows:$t.z.array($t.z.strictObject({...rl.shape,eventCount:Gi,units:Xh,tokenEventCount:Gi,tokens:$t.z.strictObject(Object.fromEntries(Zh.map(e=>[e,Gi]))),totalTokens:Gi,providerCostEventCount:Gi,providerCostUsd:Xh,invalidTelemetryEventCount:Gi})).max(100),nextCursor:rl.nullable()});var yt=require("zod");var ng=yt.z.object({requestId:yt.z.uuid(),items:yt.z.array(yt.z.object({customerId:yt.z.uuid(),command:xo.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"),rg=yt.z.object({batchId:yt.z.uuid(),after:yt.z.number().int().min(-1).max(999),limit:yt.z.number().int().min(1).max(100)}).strict(),ig=yt.z.object({batchId:yt.z.uuid(),status:yt.z.enum(["queued","complete"]),total:yt.z.number().int().min(1).max(1e3),processed:yt.z.number().int().min(0).max(1e3),items:yt.z.array(yt.z.object({position:yt.z.number().int().min(0).max(999),customerId:yt.z.uuid(),idempotencyKey:yt.z.string().min(1).max(120),status:yt.z.enum(["queued","accepted","rejected","failed"]),receipt:So.nullable(),errorCode:yt.z.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:yt.z.number().int().min(0).max(999).nullable()}).strict();var k=require("zod");var FI=k.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),og=k.z.enum(["draft","active","paused","archived"]),ag=k.z.string().min(1).max(256),sg=k.z.array(ag).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),MI=k.z.strictObject({duration:k.z.enum(["day","week","month","year"]),length:k.z.number().int().min(1).max(3660)}),qI=k.z.strictObject({internal_feature_id:k.z.uuid(),allowance:k.z.number().nonnegative().max(1e15).nullable(),expiry:MI.nullable()}),UI=k.z.discriminatedUnion("type",[k.z.strictObject({type:k.z.literal("feature_grant"),grants:k.z.array(qI).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.z.strictObject({type:k.z.literal("free_product"),productId:ag,duration:mn}),k.z.strictObject({type:k.z.literal("invoice_credits"),amount:k.z.number().positive().max(1e8),duration:mn,rollover:k.z.boolean(),productIds:sg})]),BI=k.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),cg=k.z.object({key:BI,name:k.z.string().trim().min(1).max(80),configuration:UI}).strict(),ug=k.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),il=k.z.object({code:ug,maxUses:k.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.z.boolean()}).strict(),lg=k.z.object({key:k.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.z.string().trim().min(1).max(80),rewardId:k.z.uuid(),redeemOn:k.z.enum(["customer_creation","checkout"]),receivedBy:k.z.enum(["referrer","all"]),maxRedemptions:k.z.number().int().min(1).max(1e6).nullable(),productIds:sg,excludeTrial:k.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),dg={id:k.z.uuid(),projectId:k.z.uuid(),environmentId:k.z.uuid(),revision:k.z.number().int().nonnegative(),status:og,createdAt:k.z.iso.datetime({offset:!0}),updatedAt:k.z.iso.datetime({offset:!0})},VI=cg.extend(dg).strict(),LI=lg.safeExtend(dg).strict(),Bk=k.z.strictObject({id:k.z.uuid(),key:k.z.string(),name:k.z.string(),type:FI,status:og}),Vk=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:cg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),Lk=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:lg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),pg=k.z.object({id:k.z.uuid(),rewardId:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid(),referrerId:k.z.uuid().nullable(),status:k.z.enum(["pending","applied","unavailable"]),result:k.z.record(k.z.string(),k.z.unknown()).nullable(),createdAt:k.z.iso.datetime({offset:!0})}).strict(),mg=k.z.object({code:ug,requestId:k.z.uuid()}).strict(),fg=k.z.strictObject({redemptionId:k.z.uuid(),currency:Ie,requestId:k.z.uuid(),accepted:k.z.literal(!0)}),zI=k.z.strictObject({type:k.z.literal("checkout"),orderId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:mn,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.z.url().nullable()}),hg=k.z.discriminatedUnion("type",[zI,k.z.strictObject({type:k.z.literal("subscription"),operationId:k.z.uuid(),membershipId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:mn,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["pending","running","applied","failed"])})]),gg=k.z.object({programId:k.z.uuid(),requestId:k.z.uuid()}).strict(),yg=k.z.object({id:k.z.uuid(),programId:k.z.uuid(),code:il.shape.code,createdAt:k.z.iso.datetime({offset:!0})}).strict(),zk=k.z.object({rows:k.z.array(VI).max(100),nextCursor:k.z.uuid().nullable()}).strict(),$k=k.z.object({rows:k.z.array(LI).max(100),nextCursor:k.z.uuid().nullable()}).strict(),$I=il.extend({id:k.z.uuid(),redemptions:k.z.number().int().nonnegative()}).strict(),GI=k.z.strictObject({id:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid().nullable(),referrerId:k.z.uuid().nullable(),code:k.z.string().nullable(),status:k.z.enum(["pending","triggered","applied"]),createdAt:k.z.iso.datetime({offset:!0})}),Gk=k.z.object({codes:k.z.array($I).max(100),redemptions:k.z.array(GI).max(100),customers:k.z.record(k.z.uuid(),k.z.string()),codesCursor:k.z.uuid().nullable(),redemptionsCursor:k.z.uuid().nullable()}).strict(),Kk=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("create"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),input:il}).strict(),k.z.object({action:k.z.literal("remove"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),codeId:k.z.uuid()}).strict()]);var w=require("zod");var Z=require("zod"),zn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},zo=e=>new Set(e).size===e.length,ol=Z.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),KI=Z.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),$o=Z.z.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"))),HI=Z.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ag=Z.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var bg=Z.z.strictObject({id:Z.z.uuid(),repo:KI,platform:Z.z.enum(["github","gitlab","bitbucket"]),branches:Z.z.array($o).min(1).max(4).refine(zo),workflow:Z.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.z.array(Z.z.uuid()).min(1).max(4).refine(zo),include:Z.z.array(Ag).min(1).max(16),exclude:Z.z.array(Ag).max(16),methods:Z.z.array(Z.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(zo),maxAgeHours:Z.z.number().int().min(1).max(720)}),xg=bg.extend({revision:Z.z.number().int().positive()}),Qk=Z.z.strictObject({repository:bg,expectedRevision:Z.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Sg=Z.z.strictObject({repositoryId:Z.z.uuid(),branch:$o}),QI=Z.z.array(ol).max(zn.keys).refine(zo),Ig=Z.z.strictObject({repository:xg.omit({keyIds:!0}),branch:$o,keys:QI,keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/)}),JI=Z.z.strictObject({filePath:HI,startingLineNumber:Z.z.number().int().min(1).max(1e7)}),al=Z.z.strictObject({protocol:Z.z.literal(1),repositoryId:Z.z.uuid(),branch:$o,workflow:Z.z.string().max(200),configurationRevision:Z.z.number().int().positive(),keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/),commit:Z.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.z.uuid(),runNumber:Z.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.z.number().int().min(1).max(1e4),scannerVersion:Z.z.literal("1"),scannedAt:Z.z.iso.datetime({offset:!0}),coverage:Z.z.strictObject({complete:Z.z.literal(!0),files:Z.z.number().int().min(0).max(zn.files),sourceBytes:Z.z.number().int().min(0).max(zn.sourceBytes),unresolvedCalls:Z.z.number().int().min(0).max(1e6),unsupportedFiles:Z.z.number().int().min(0).max(zn.files)}),features:Z.z.array(Z.z.strictObject({key:ol,refs:Z.z.array(JI).max(zn.referencesPerKey)})).max(zn.keys)}).superRefine((e,t)=>{zo(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)>zn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),sl=Z.z.strictObject({scanId:Z.z.uuid(),commit:Z.z.string(),receivedAt:Z.z.string(),references:Z.z.number().int().nonnegative(),removedReferences:Z.z.number().int().nonnegative()}),ZI=sl.extend({repositoryId:Z.z.uuid(),branch:$o,workflow:Z.z.string(),digest:Z.z.string(),configurationRevision:Z.z.number().int().positive(),runNumber:Z.z.number().int().positive(),runAttempt:Z.z.number().int().positive(),scannedAt:Z.z.string(),keySetHash:Z.z.string(),coverage:al.shape.coverage}),WI=Z.z.strictObject({repositories:Z.z.array(xg).max(zn.repositories),scans:Z.z.array(ZI).max(zn.repositories*zn.branches)}),YI=Z.z.strictObject({key:ol,references:Z.z.number().int().nonnegative(),coveredTargets:Z.z.number().int().nonnegative(),expiredTargets:Z.z.number().int().nonnegative(),uncertainTargets:Z.z.number().int().nonnegative()}),Jk=Z.z.strictObject({available:Z.z.boolean().default(!0),settings:WI,expectedTargets:Z.z.number().int().min(0).max(80),features:Z.z.array(YI).max(2001),truncated:Z.z.boolean()});var Ee=require("zod");var un=Ee.z.string().min(1).max(200),_s=Ee.z.iso.datetime({offset:!0}),Go=Ee.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),cl=Ee.z.number().int().min(0).max(1e12),Og=Ee.z.number().int().min(1).max(1e12),vg={...Jt,type:Ee.z.literal("coupon.redeemed"),grantId:Ee.z.uuid()},wg={...Jt,type:Ee.z.literal("usage.observed"),merchantTransactionId:un,resource:un,unit:un,quantity:Og},XI=Ee.z.strictObject({...Jt,type:Ee.z.literal("fulfillment.updated"),operationId:Ee.z.uuid(),merchantFulfillmentId:un,status:Ee.z.enum(["pending","applied","failed"])}),ev=Ee.z.strictObject({...Jt,type:Ee.z.literal("benefit.claimed"),merchantBenefitId:un,resource:un,unit:un,quantity:Og,expiresAt:_s.nullable(),revision:Go}),tv=Ee.z.strictObject({...Jt,type:Ee.z.literal("benefit.closed"),merchantBenefitId:un,status:Ee.z.enum(["failed","expired","canceled"]),revision:Go}),nv=Ee.z.strictObject({...Jt,type:Ee.z.literal("benefit.updated"),merchantBenefitId:un,status:Ee.z.enum(["active","expired","revoked"]),remainingQuantity:cl.nullable(),expiresAt:_s.nullable(),revision:Go}),rv=Ee.z.strictObject({...Jt,type:Ee.z.literal("authorization.updated"),merchantAuthorizationId:un,kind:Ee.z.literal("auto_topup"),status:Ee.z.enum(["pending","effective","revoked","failed"]),termsReference:un.nullable(),revision:Go}),iv=Ee.z.strictObject({...Jt,type:Ee.z.literal("balance.observed"),resource:un,unit:un,availableQuantity:cl,reservedQuantity:cl,periodStartsAt:_s.nullable(),periodEndsAt:_s.nullable(),revision:Go}),Pg=Ee.z.union([Ee.z.discriminatedUnion("type",[...md,XI,ev,tv,nv,rv,iv]),Ee.z.strictObject({...vg,productVersionId:Ee.z.uuid(),subscriptionId:Ee.z.string().trim().min(1).max(255)}),Ee.z.strictObject({...vg,merchandiseId:Ee.z.uuid()}),Ee.z.strictObject({...wg,operation:Ee.z.literal("consume")}),Ee.z.strictObject({...wg,operation:Ee.z.literal("reverse"),reversalOf:un})]),Cg=Ee.z.strictObject({id:Ee.z.uuid(),eventId:Ee.z.string().min(1).max(200),source:Ee.z.literal("merchant"),providerVerified:Ee.z.literal(!1),outcome:Ee.z.string().min(1).max(100)});var oe=require("zod");var _g=nf,ov=_g.extend({invoice_id:_g.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ul=oe.z.strictObject({name:oe.z.string().trim().min(1).max(255),memo:oe.z.string().max(1e4).nullable().optional(),footer:oe.z.string().max(1e4).nullable().optional(),net_terms_days:oe.z.number().int().positive().nullable().optional()}),av=ul.extend({id:oe.z.string().min(1).max(255),created_at:oe.z.number().nullable()}),Eg=oe.z.strictObject({items:oe.z.array(av).max(50),nextCursor:oe.z.uuid().nullable()}),ej=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),values:ul}),oe.z.strictObject({action:oe.z.literal("update"),id:oe.z.string().min(1).max(255),values:ul}),oe.z.strictObject({action:oe.z.literal("delete"),id:oe.z.string().min(1).max(255)})]),Rg=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),params:Ti}),oe.z.strictObject({action:oe.z.enum(["finalize","send","pay","void"]),requestId:oe.z.uuid(),invoiceId:oe.z.uuid()}),oe.z.strictObject({action:oe.z.literal("reissue"),requestId:oe.z.uuid(),invoiceId:oe.z.uuid(),params:ov})]),ll=oe.z.strictObject({id:oe.z.uuid(),customerId:oe.z.uuid(),providerInvoiceId:oe.z.string().nullable(),status:oe.z.enum(["draft","open","paid","void","uncollectible"]),currency:oe.z.string(),totalMinor:oe.z.string().regex(/^-?\d+$/),paidMinor:oe.z.string().regex(/^\d+$/),refundedMinor:oe.z.string().regex(/^\d+$/),hostedInvoiceUrl:oe.z.url().nullable(),createdAt:oe.z.number(),collectionMethod:oe.z.enum(["send_invoice","charge_automatically"]).nullable()}),kg=ll.extend({lines:oe.z.array(oe.z.strictObject({id:oe.z.uuid(),description:oe.z.string(),amountMinor:oe.z.string().regex(/^-?\d+$/),netAmountMinor:oe.z.string().regex(/^-?\d+$/),quantity:oe.z.number().nullable(),periodStart:oe.z.number().nullable(),periodEnd:oe.z.number().nullable()})).max(1e3)}),Ki=oe.z.strictObject({taskId:oe.z.uuid(),status:oe.z.enum(["ready","running","done","dead"]),invoice:ll.nullable(),errorCode:oe.z.string().nullable()}),jg=oe.z.strictObject({items:oe.z.array(ll).max(50),nextCursor:oe.z.uuid().nullable(),operations:oe.z.array(Ki).max(50),operationsLimited:oe.z.boolean()});var sv=w.z.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"]),Tg={scope:Me,permissions:w.z.array(sv),expiresAt:w.z.iso.datetime().nullable()},Kj=w.z.discriminatedUnion("kind",[w.z.object({...Tg,kind:w.z.literal("server"),keyId:w.z.string().min(1)}),w.z.object({...Tg,kind:w.z.literal("customer"),customerId:w.z.string().min(1),identityKind:w.z.enum(["identified","guest"]),expiresAt:w.z.iso.datetime()})]),V=w.z.object({requestId:w.z.uuid(),scope:Me}).strict(),cv=bh.safeExtend({fingerprint:As.optional()}).strict(),uv=V.extend({customer:Vi,created:w.z.boolean()});function Ng(){return V.extend({offer:fo.nullable(),reason:Np.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:wm,response:V.extend({message:w.z.object({messageId:w.z.uuid(),channel:Oo,acceptedAt:w.z.iso.datetime({offset:!0}),status:w.z.enum(["accepted","sending","completed","canceled"]),replayed:w.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.z.strictObject({messageId:w.z.uuid()}),response:V.extend({message:w.z.object({id:w.z.uuid(),channel:Oo,status:w.z.enum(["accepted","sending","completed","canceled"]),deliveries:w.z.array(w.z.object({id:w.z.uuid(),status:Pm,attempts:w.z.number().int().nonnegative(),receipts:w.z.array(w.z.object({kind:Cm,occurredAt:w.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Wl,response:V.extend({installation:Dr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Yl,response:V.extend({installation:Dr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:sa,response:V.extend({installation:Dr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.z.strictObject({channel:Oo}),response:V.extend({preference:Ys})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Om,response:V.extend({preference:Ys})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.z.strictObject({cursor:w.z.uuid().optional()}),response:V.extend({templates:Eg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),params:Ti}),response:V.extend({preview:su})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),requestId:w.z.uuid(),params:Ti}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:Ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Rg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:Ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),taskId:w.z.uuid()}),response:V.extend({operation:Ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),cursor:w.z.uuid().optional()}),response:V.extend({invoices:jg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),invoiceId:w.z.uuid()}),response:V.extend({invoice:kg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Sg,response:V.extend({config:Ig})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:al,response:V.extend({receipt:sl})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.z.strictObject({}),response:V.extend({payload:Mo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Qf,response:V.merge(cs)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Jf,response:V.merge(Zf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sourceId:w.z.uuid()}),response:V.extend({balance:Kh})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Gh}),response:V.extend({balance:el})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.z.strictObject({internal_feature_id:w.z.uuid(),customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.z.uuid(),config:wc,model_markups:Oa})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),query:Ba}),response:V.extend({usage:Io})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:hm}),response:V.extend({usage:Io})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:um}),response:V.extend({grant:Vc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:lm,response:V.extend({grants:dm})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.z.union(Ff.options.map(e=>e.extend({customerId:w.z.uuid().optional(),customerToken:w.z.string().regex(Ut).optional()}))),response:V.extend({operation:Mf})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Of.extend({customerId:w.z.uuid().optional()}),response:V.extend({setup:mu})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Pf.extend({customerId:w.z.uuid().optional()}),response:V.extend({setup:mu})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:If.safeExtend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ns.extend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ns.extend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ns.extend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.z.discriminatedUnion("action",[rs.options[0].extend({customerId:w.z.uuid()}),rs.options[1].extend({customerId:w.z.uuid()}),rs.options[2].extend({customerId:w.z.uuid()})]),response:V.extend({trial:pu})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:vf.extend({customerId:w.z.uuid()}),response:V.extend({trial:pu})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:as,response:V.extend({subscriptions:Tf})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:as,response:V.extend({purchases:Nf})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Rf,response:V.extend({conflicts:Df})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:kf,response:V.extend({resolution:jf})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:_f,response:V.extend({verification:Ef})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ff.safeExtend({...ki,customerId:w.z.uuid().optional()}),response:V.extend({quote:Ni})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Pg,response:V.extend({record:Cg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional(),merchantConfirmation:so.optional()}),response:V.extend({operation:Di})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional()}),response:V.extend({operation:Di})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:yf.safeExtend({customerId:w.z.uuid().optional()}),response:V.extend({quote:bf})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional(),merchantConfirmation:so.optional()}),response:V.extend({operation:cu})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional()}),response:V.extend({operation:cu})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:xf.safeExtend({customerId:w.z.uuid()}),response:V.extend({quote:lu})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:ei.extend({customerId:w.z.uuid(),merchantConfirmation:so.optional()}),response:V.extend({operation:ts})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:ei.extend({customerId:w.z.uuid()}),response:V.extend({operation:ts})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Qp,response:V.extend({controls:Uc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Vp,response:V.extend({prepared:zp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:$p,response:V.extend({authorization:Fa})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Xp,response:V.extend({coupons:em})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Gp,response:V.extend({authorization:Fa})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Wp,response:V.extend({invoices:Yp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Zp.extend({customerId:w.z.uuid()}),response:V.extend({operation:Ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Jp,response:V.extend({invoice:yo})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:Hp}).strict(),response:V.extend({controls:Uc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:Hh}).strict(),response:V.extend({entity:Qh})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid().nullable(),query:eg}),response:V.extend({analytics:tg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.z.object({customerId:w.z.uuid().nullable(),query:ci}).strict(),response:V.extend({analytics:Yh})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:ng,response:V.extend({batchId:w.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:rg,response:V.extend({batch:ig})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:$d.extend({customerId:w.z.string().min(1).optional()}),response:V.extend({check:ur})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.z.strictObject({kind:gr,selector:w.z.discriminatedUnion("type",[w.z.strictObject({type:w.z.literal("resource"),id:w.z.uuid()}),w.z.strictObject({type:w.z.literal("version"),id:w.z.uuid()})]),customerId:w.z.string().min(1).optional()}),response:V.extend({content:iu})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lh,response:V.extend({paywall:oi})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.z.strictObject({processContext:Wa.optional(),...ki,selector:Vf,customerId:w.z.string().min(1).optional(),commerce:Si,requirement:_n.optional()}),response:V.extend({offering:Lf,candidates:w.z.array(Sc).max(20),availability:w.z.array(w.z.strictObject({productVersionId:w.z.uuid(),available:w.z.boolean(),reason:w.z.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:ur.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).strict(),response:V.extend({holdings:gm})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),query:Am}).strict(),response:V.extend({ledger:bm})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:pm.extend({customerId:w.z.uuid().optional()}),response:V.extend({detail:mm})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Lc.safeExtend({customerId:w.z.uuid().optional()}),response:V.extend({statement:fm})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),command:xo.options[0]}).strict(),response:V.extend({quote:am})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:w.z.union([w.z.strictObject({eventName:w.z.string().min(1),quantity:de.optional(),properties:_t.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)}),w.z.strictObject({internal_feature_id:w.z.uuid(),quantity:de.optional(),properties:_t.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)})])}),response:V.extend({receipts:w.z.array(So).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:xo.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:So})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:mg,response:V.extend({redemption:pg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:gg,response:V.extend({referralCode:yg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:fg,response:V.extend({checkout:hg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Sm,response:V.extend({seats:Gc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Im,response:V.extend({seats:Gc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:cv,response:uv},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Mu,response:V.extend({customer:Vi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Ih,response:V.extend(vh.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Sh,response:V.extend(xh.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.z.object({customerId:w.z.uuid()}).strict(),response:V.extend(cr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.z.strictObject({}),response:V.extend(cr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sessionId:w.z.uuid().optional()}),response:V.extend({revoked:w.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:As.optional()}),response:V.extend({customerId:w.z.uuid(),guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(cr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.z.uuid()}),response:V.extend({customer:Vi,switched:w.z.boolean(),replayed:w.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.z.strictObject({code:w.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.z.uuid()}),response:Ng()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.z.object({}).strict(),response:V.extend({offers:w.z.array(fo)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:Nd,response:V.extend({operation:yc})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:Dd,response:V.extend({operation:yc})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.z.object({customerId:w.z.string().min(1).max(255).optional(),couponId:w.z.uuid(),...ki,requestId:w.z.uuid(),couponContentDigest:w.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Ng()}},Hj={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};var Es=require("zod");var Ko=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function dl(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 Ko("Required GB Feature is unavailable");i=Yn(e.featureKey,t),o=i.value,Object.assign(r,Ri(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Ko("Required GB Experiment is unavailable");if(a=Na(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 Ko("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Yn(e.configuration.featureKey,t).value;o={type:"offering_version",id:Es.z.uuid().parse(u)},Object.assign(r,Ri(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,Ri(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 Dg(e,t,n){Es.z.uuid().parse(e),Es.z.number().int().nonnegative().parse(t);let r=ir(ar(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)}`}var H=require("zod");var Ir=H.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),lv=H.z.enum(["running","waiting","completed","closed","ineligible","failed"]),pl=H.z.discriminatedUnion("type",[Du,H.z.strictObject({type:H.z.literal("wait"),receiptId:H.z.uuid(),kind:H.z.enum(["timer","event","operation"]),deadline:H.z.iso.datetime({offset:!0}).nullable(),eventName:Ir.optional()}),H.z.strictObject({type:H.z.literal("open_url"),receiptId:H.z.uuid(),url:qu,openIn:Uu}),H.z.strictObject({type:H.z.literal("event"),receiptId:H.z.uuid(),event:Ir})]),Rs=H.z.strictObject({type:H.z.literal("funnel"),id:H.z.uuid(),versionId:H.z.uuid()}),dv={id:Ir,presentation:jn,outputs:H.z.array(Ir).max(250),inputs:ps,values:H.z.record(H.z.string(),ve).optional(),offeringKey:wt.optional(),capabilities:Pi,customerData:Nm,dataCursors:H.z.record(Ir,ds.nullable())},pv=H.z.strictObject({...dv,content:H.z.strictObject({type:H.z.literal("document"),document:hn})}),Ho=H.z.strictObject({id:H.z.uuid(),source:Rs,revision:H.z.number().int().nonnegative(),visit:H.z.number().int().nonnegative(),nodeId:Ir,nodeType:H.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:lv,stopped:H.z.boolean(),canBack:H.z.boolean(),authenticated:H.z.boolean(),locale:H.z.string().min(1).max(35),answers:Ar,parameters:br,variables:H.z.record(H.z.string(),ve),output:ve.nullable(),screen:pv.nullable(),paywall:H.z.strictObject({receiptId:H.z.uuid(),resolution:H.z.union([Lo,oi]),quote:Ni.nullable(),operation:Di.nullable(),purchaseRequestId:H.z.uuid().nullable(),selectionGeneration:H.z.number().int().nonnegative().optional(),canReselect:H.z.boolean().optional()}).nullable(),instruction:pl.nullable(),pendingRequest:H.z.strictObject({requestId:H.z.uuid(),authenticationRequired:H.z.boolean()}).nullable(),runExpiresAt:H.z.iso.datetime({offset:!0}),credentialExpiresAt:H.z.iso.datetime({offset:!0}).nullable()}),ks=H.z.strictObject({scope:Me,run:Ho,settlement:H.z.strictObject({requestId:H.z.uuid(),state:H.z.enum(["pending","unknown","settled"]),operationId:H.z.uuid().nullable(),receiptId:H.z.uuid().nullable().optional()}).optional(),purchase:H.z.strictObject({receiptId:H.z.uuid(),quote:Ni.nullable(),operation:Di.nullable(),canReselect:H.z.boolean().optional()}).optional(),review:H.z.strictObject({activeOperationId:H.z.uuid().nullable(),pages:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),nodeId:Ir,visit:H.z.number().int().nonnegative()})).max(100),page:H.z.strictObject({receiptId:H.z.uuid(),nodeId:Ir,visit:H.z.number().int().nonnegative(),document:hn,answers:Ar,inputs:ps,values:H.z.record(H.z.string(),ve).optional()}).nullable(),coupons:H.z.array(H.z.strictObject({grantId:H.z.uuid(),status:H.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.z.string().nullable()})).max(100),purchases:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),operationId:H.z.uuid(),status:H.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.z.uuid().optional()}),Fg=ks.extend({run:Ho.extend({paywall:Ho.shape.paywall.unwrap().extend({resolution:oi}).nullable()})});var Mg="X-Indiana-Server-Key";var se=require("zod");var be=require("zod");var Pt=require("zod");var mv=Pt.z.strictObject({selector:Pt.z.string().min(1).max(2048),action:Pt.z.enum(["set","append","remove"]),attribute:Pt.z.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:Pt.z.string().max(5e4).optional(),parentSelector:Pt.z.string().max(2048).optional(),insertBeforeSelector:Pt.z.string().max(2048).optional()}),fv=Pt.z.strictObject({variation:Pt.z.string().min(1).max(128),description:Pt.z.string().max(2e3).default(""),css:Pt.z.string().max(1e5).default(""),js:Pt.z.string().max(1e5).default(""),domMutations:Pt.z.array(mv).max(200).default([]),iam:oh.optional(),renderGuard:us.optional()}),ml=fv.omit({variation:!0,description:!0,iam:!0}),hv=Ui.omit({variations:!0,active:!0}).extend({changeId:Pt.z.string().regex(/^[a-f0-9]{64}$/),variations:Pt.z.tuple([ml,ml]).rest(ml).refine(e=>e.length<=20)}),qg=Pt.z.strictObject({trackExposures:Pt.z.boolean(),environmentId:Pt.z.uuid(),generation:Pt.z.string().regex(/^[a-f0-9]{64}$/),experiments:Pt.z.array(hv).max(100),savedGroups:Fo});var Qo=be.z.string().regex(/^[a-f0-9]{64}$/),vT=be.z.strictObject({iam:Qo,executionContracts:be.z.union([be.z.tuple([be.z.literal("funnel-run/1")]),be.z.tuple([be.z.literal("funnel-process/1")])]).default(["funnel-run/1"])}),gv=be.z.strictObject({release:Qo,render:us,button:be.z.strictObject({selector:be.z.string().min(1).max(512),elementKey:be.z.string().min(1).max(256),tag:be.z.enum(["button","a","input"])}).nullable()}),wT=be.z.strictObject({scope:Me.extend({environmentId:be.z.uuid()}),release:Qo,validatedAt:be.z.iso.datetime({offset:!0}),validUntil:be.z.iso.datetime({offset:!0}),entries:be.z.array(be.z.strictObject({id:be.z.uuid(),funnelId:be.z.uuid(),versionId:be.z.uuid(),event:be.z.enum(["screen_enter","button_click"]),target:gv})).max(4e3)}),Ug=be.z.strictObject({operation:be.z.literal("entry_start"),funnelId:be.z.uuid(),versionId:be.z.uuid(),entryId:be.z.uuid(),release:Qo,requestId:be.z.uuid(),locale:be.z.string().min(1).max(35).default("en")}),Bg=be.z.strictObject({scope:Me,suppressed:be.z.literal(!0),reason:be.z.enum(["frequency","in_progress"]),retryAt:be.z.iso.datetime({offset:!0}).nullable()}),OT=be.z.strictObject({experimentId:be.z.uuid(),splitNodeId:be.z.string().min(1).max(128)}),yv=be.z.strictObject({experimentId:be.z.uuid(),experimentKey:be.z.string().min(1).max(128),variationKey:be.z.string().min(1).max(128),inExperiment:be.z.boolean(),generation:be.z.string().min(1).max(256)}),Jo=be.z.strictObject({operation:be.z.literal("page_experiments"),release:Qo,usedReceiptIds:be.z.array(be.z.uuid()).max(20).default([]),customerToken:be.z.string().regex(Ut).optional()}),Vg=be.z.strictObject({scope:Me,runId:be.z.uuid(),assignments:be.z.array(yv.extend({receiptId:be.z.uuid()})).max(100),payload:qg});var Mn=se.z.literal(Xf),Av=se.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),fl=se.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Lg=se.z.discriminatedUnion("type",[se.z.strictObject({type:se.z.literal("guest"),guestToken:fl}),se.z.strictObject({type:se.z.literal("customer"),customer:ri,customerData:Bi.optional()})]),hl=se.z.strictObject({id:se.z.uuid(),runId:se.z.uuid(),customerId:se.z.uuid(),requestId:se.z.uuid(),acceptedAt:se.z.iso.datetime({offset:!0})}),bv=se.z.strictObject({participantId:se.z.uuid(),startedAs:se.z.enum(["guest","identified"]),binding:hl.omit({runId:!0,requestId:!0}).nullable()}),xv=se.z.union([pl,se.z.strictObject({type:se.z.literal("authentication_required"),reason:se.z.enum(["customer_required","customer_experiment_required"]),nodeId:se.z.string().min(1).max(64),visit:se.z.number().int().nonnegative()})]),Sv=Ho.omit({authenticated:!0}).extend({identity:bv,instruction:xv.nullable()}),Iv=se.z.discriminatedUnion("operation",[Rt.options[2].omit({customerToken:!0}),Rt.options[3].omit({customerToken:!0}),Rt.options[4].omit({customerToken:!0}),Rt.options[5].omit({customerToken:!0}),Rt.options[6].omit({customerToken:!0}),Rt.options[7].omit({customerToken:!0})]),js={contract:Mn,customerToken:se.z.string().regex(Ut)},zg={contract:Mn,requestId:se.z.uuid(),runToken:Av,externalUserId:ri.options[1].shape.value},$g=se.z.discriminatedUnion("operation",[se.z.strictObject({contract:Mn,operation:se.z.literal("describe")}),se.z.strictObject({contract:Mn,operation:se.z.literal("start"),source:Lg,funnelId:Rt.options[0].shape.funnelId,requestId:se.z.uuid(),locale:Rt.options[0].shape.locale,parameters:Rt.options[0].shape.parameters}),Ug.omit({operation:!0}).extend({contract:Mn,operation:se.z.literal("entry_start"),source:Lg}),se.z.strictObject({...zg,operation:se.z.literal("bind_customer"),guestToken:fl,claimRequestId:se.z.uuid(),expectedBindingId:se.z.null()}),se.z.strictObject({...zg,operation:se.z.literal("binding_status"),guestToken:fl.optional()}),Rt.options[1].omit({operation:!0,customerToken:!0}).extend({...js,operation:se.z.literal("get"),settlementBindingId:se.z.uuid().nullable().optional()}),Rt.options[8].omit({operation:!0,customerToken:!0}).extend({...js,operation:se.z.literal("review")}),Jo.omit({customerToken:!0}).extend(js),se.z.strictObject({...js,operation:se.z.literal("command"),identity:se.z.strictObject({bindingId:se.z.uuid().nullable()}),command:Iv})]),gl=ks.omit({run:!0}).extend({contract:Mn,run:Sv,settlement:ks.shape.settlement.unwrap().extend({accepted:se.z.boolean().nullable().optional()}).optional()}),NT=Bg.extend({contract:Mn}),DT=se.z.discriminatedUnion("operation",[$g.options[1].omit({contract:!0,source:!0,requestId:!0}),$g.options[2].omit({contract:!0,source:!0,requestId:!0})]),FT=gl.extend({binding:hl,outcome:se.z.enum(["bound","already_bound"]),replayed:se.z.boolean()}),MT=se.z.discriminatedUnion("state",[se.z.strictObject({contract:Mn,scope:Me,state:se.z.literal("not_accepted")}),se.z.strictObject({contract:Mn,scope:Me,state:se.z.literal("conflict")}),se.z.strictObject({contract:Mn,scope:Me,state:se.z.literal("bound"),binding:hl})]),qT=se.z.strictObject({contract:Mn,scope:Me,keyId:se.z.uuid(),operations:se.z.array(se.z.string()).max(20)});var De=require("zod");var Hi=De.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Kg=De.z.strictObject({entry:Hi,nodes:De.z.array(De.z.strictObject({id:Hi,type:De.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:De.z.record(De.z.string(),Hi),writes:De.z.record(wt,wt),resources:De.z.strictObject({screenId:Hi.optional(),paywallVersionId:De.z.uuid().optional(),couponId:De.z.uuid().optional(),couponIds:De.z.array(De.z.uuid()).max(20).optional(),experimentId:De.z.uuid().optional(),featureKey:De.z.string().optional(),offeringVersionId:De.z.uuid().optional()})})).min(1).max(500)}),Gg={scope:Me,funnelId:De.z.uuid(),versionId:De.z.uuid(),evaluationRevision:De.z.number().int().nonnegative(),expiresAt:De.z.iso.datetime({offset:!0}).nullable(),topology:Kg},Ts=De.z.discriminatedUnion("evaluationMode",[De.z.strictObject({...Gg,evaluationMode:De.z.literal("local"),growth:vn,conditions:De.z.record(Hi,De.z.array(De.z.strictObject({condition:nn,port:De.z.string()})))}),De.z.strictObject({...Gg,evaluationMode:De.z.literal("remote")})]),vv=Ts.options[0].extend({evaluation:De.z.strictObject({maxTransitions:De.z.number().int().min(1).max(1e4),variables:De.z.record(wt,Ei),outputSchema:_i,terminals:De.z.record(Hi,De.z.strictObject({outcome:De.z.enum(["completed","closed","ineligible","failed"]),output:Uo.nullable()}))})});function wv(e){return Kg.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=De.z.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 yl(e){let t=zi.parse(e.document),n=e.evaluationMode==="local"?vn.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:wv(t)};return Ts.parse(e.evaluationMode==="remote"?r:{...r,growth:Os(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 Hg(e){let t=yl(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=zi.parse(e.document);return vv.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}]]}))}})}var ot=require("zod");var Qg=ot.z.string().regex(/^[a-f0-9]{64}$/),Ov=Ui.omit({variations:!0,active:!0}).extend({changeId:Qg,variations:ot.z.array(ot.z.strictObject({urlRedirect:ot.z.string().max(2048)})).min(2).max(20)}),Jg=ot.z.strictObject({environmentId:ot.z.uuid(),trackExposures:ot.z.boolean(),generation:Qg,experiments:ot.z.array(Ov).max(100),savedGroups:Fo}),Pv=ot.z.strictObject({eventUuid:ot.z.uuid(),timestamp:ot.z.iso.datetime({offset:!0}).optional(),deviceId:ot.z.string().min(1).max(128),sessionId:ot.z.string().min(1).max(128).optional(),url:ot.z.url().max(2048),pageTitle:ot.z.string().max(512).optional(),experimentKey:ot.z.string().min(1).max(255),variationKey:ot.z.string().min(1).max(64)}),JT=ot.z.strictObject({events:ot.z.array(Pv).min(1).max(20)}),ZT=ot.z.strictObject({inserted:ot.z.number().int().nonnegative(),duplicates:ot.z.number().int().nonnegative(),skipped:ot.z.number().int().nonnegative(),rejected:ot.z.array(ot.z.strictObject({index:ot.z.number().int().nonnegative(),reason:ot.z.string()}))});var lt=require("zod");var bl=32,Cv=522240;function xl(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 _v=lt.z.strictObject({nodeId:lt.z.string().min(1).max(64),visit:lt.z.number().int().nonnegative(),revision:lt.z.number().int().nonnegative()}),Al=lt.z.record(lt.z.string(),ve),Ev=lt.z.strictObject({id:lt.z.uuid(),nodeId:lt.z.string().min(1).max(64),visit:lt.z.number().int().nonnegative(),input:lt.z.strictObject({schemaVersion:Bo.shape.schemaVersion,kind:Bo.shape.kind,selector:Bo.shape.selector,contract:Bo.shape.contract}),context:Al,removed:lt.z.array(lt.z.string()).max(100),attributes:Al,removedAttributes:lt.z.array(lt.z.string()).max(100),result:Rh,offeringVersionId:lt.z.uuid().nullable(),events:lt.z.strictObject({entered:lt.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:lt.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),tN=lt.z.strictObject({schemaVersion:lt.z.literal(1),mode:lt.z.enum(["local","remote"]),versionId:lt.z.uuid(),generation:lt.z.number().int().positive(),base:_v,context:Al,steps:lt.z.array(Ev).min(1).max(bl)}).refine(e=>gn(e)<=Cv,"Segment exceeds its byte budget");var Rv=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Zo(e){return Array.isArray(e)?e.some(Zo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Zo(n):!Rv.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=>Zo(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"||Zo(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"||Zo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Sl=class extends Error{constructor(n,r){super(r);Be(this,"code",n);this.name="FunnelLocalCalculationError"}},Wg=(e,t)=>new Sl(e,t),kv=e=>({experiments:e.experiments,features:e.features});function jv(e,t=Wg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Ii(e.growth.savedGroups),i=kv(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Yn(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=dl({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=dl({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 Tv(e,t){let n=Ts.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=jv(n,t);return(o,s)=>(i(),Nv(a,o,s))}function Nv(e,t,n){let r=Et.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 Dv(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 Yg(e,t,n,r=Wg){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=Tv(e,r)),Dv(m,R,{attributes:Ru({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<bl;R++){let y=a.get(u);if(!y||!xl(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"?tu({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||!In(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(gn({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=Ri(y,{value:C});zm(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&&(!xl(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=ca(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 Wo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},Fv=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 $n(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 Xg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Me.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 Fv(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=Dr.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(nd(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=$n(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,xt=Xl.parse(await h("detach",{sequence:Se,platform:x.platform}));try{let et=await t.request("push/installations/detach",{...x.scope,...xt},"POST",{installationDetach:!0});if(!et||typeof et!="object"||!("installation"in et))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Fe=m(et.installation);if(Fe.bound||Fe.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(et){if(et instanceof b&&et.status===404)_=et;else if(!(et instanceof b)||et.status!==412)throw et}_||$n(x,et=>({...et,detachSeq:et.detachSeq===Se?null:et.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&&$n(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=$n(j,Fe=>C?Fe:{...Fe,addressSeq:Wo(Fe.addressSeq)}),Se=await h(C?"recovery_confirm":"recovery_request",{...x,sequence:ye.addressSeq,credentialDigest:await p(le),...C?{challenge:C}:{}}),xt=C?td.parse(Se):ed.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let et=await d(`push/installations/recovery/${C?"confirm":"request"}`,xt,le);if(l(_),X!==a||$n(j,Fe=>Fe).addressSeq!==ye.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Fe=O.updatePushAddress.response.parse(et),at=m(Fe.installation);if(!at.bound||at.identitySeq!==o||at.addressSeq!==ye.addressSeq||at.connectionId!==x.connectionId||at.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return at}if(!et||typeof et!="object"||!("recovery"in et))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ws.parse(et.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Ws.parse(await A(v,x))},async confirm(v,C){return Dr.parse(await A(C,x,v))}}},identify(x){if(!e)return;o=$n(e,C=>({...C,identitySeq:Wo(C.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{$n(e,x=>{let v=Wo(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=$n(x,X=>{if(X.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Wo(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=$n(j,Se=>({...Se,addressSeq:Wo(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||$n(j,Se=>Se).addressSeq!==X.addressSeq?null:m(le.response.parse(ke).installation)}}}}var ty=require("zod");function ey(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof ty.ZodError?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=ey(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):ey(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 ny(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 ry={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 qv=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Uv(e){return e.replace(qv,"$1\uFFFD")}function Ol(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 py(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 iy(e){let t;if(Array.isArray(e)){let n=e.map(We);if(n.length===2)return n}else if((t=py(e))!=null){let n=Ol(t.next()),r=Ol(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 oy="0123456789ABCDEF",Bv=/(?:%[0-9A-Fa-f]{2})+/g;function Gn(e){return`%${oy[e>>4&15]}${oy[15&e]}`}function my(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Gn(e):String.fromCharCode(e):e<=2047?Gn(192|e>>6)+Gn(128|63&e):e<=65535?Gn(224|e>>12)+Gn(128|e>>6&63)+Gn(128|63&e):Gn(240|e>>18)+Gn(128|e>>12&63)+Gn(128|e>>6&63)+Gn(128|63&e)}function Pl(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Cl(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(Bv,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function ea(e){return e<=31||e>126}function Vv(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return ea(e)}}function Nl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return ea(e)}}function Lv(e){return Nl(e)||e===39}function _l(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Nl(e)}}function qs(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 _l(e)}}function ay(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 qs(n)}})(e)}}function fy(e,t){return my(e=e||0,t)}function Kn(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+=my(o,t,n)}return i}function Dl(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([Cl(i.slice(0,a),!0),Cl(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function El(e){let t="";for(let n=0;n<e.length;n++){let r=Kn(e[n][0],ay,!0),i=Kn(e[n][1],ay,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var zv=[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],$v=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Gv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Kv=[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 Hv(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[Qv,Jv,Zv,sy]=[[[],"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 Wv(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 hy(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Yo(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 Yv(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&&hy(Kv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Yo(sy,t[i]);)i--;let a=n+1;for(;a<t.length&&Yo(sy,t[a]);)a++;if(!(i>=0&&a<t.length&&Yo(Jv,t[i])&&Yo(Zv,t[a])))return!1}return!0}var Xv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,ew=/\p{Script=Latin}/u;function tw(e){return!Xv.test(e)||!ew.test(e)}var vr=36,Ds=1,Rl=26,nw=38,rw=700,iw=72,ow=128,aw=2147483647;function cy(e){return String.fromCharCode(e+22+75*+(e<26))}function sw(e,t,n){let r=0;for(e=n?Math.floor(e/rw):e>>1,e+=Math.floor(e/t);e>(vr-Ds)*Rl>>1;r+=vr)e=Math.floor(e/(vr-Ds));return Math.floor(r+(vr-Ds+1)*e/(e+nw))}function cw(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=ow,o=0,s=iw;for(;r<t.length;){let c=aw;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=vr;;m+=vr){let h=m<=s?Ds:m>=s+Rl?Rl:m-s;if(p<h)break;n+=cy(h+(p-h)%(vr-h)),p=Math.floor((p-h)/(vr-h))}n+=cy(p),s=sw(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Il(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=Pl(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function uy(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function gy(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function yy(e){return e.length===2&&gy(e.codePointAt(0),e.codePointAt(1))}function ly(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function At(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ay(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function kl(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=Pl(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+Pl(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 ly(r)?null:Kn(r,ea)})(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)&&!hy(zv,p)||Yo(Qv,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=Wv(p,m);if(h){l+=h;continue}let d=$v.indexOf(m);l+=d<0?p:Gv[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(Hv(u)||l&&(/^\p{Mark}/u.test(u)||!Yv(u)||!tw(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${cw(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Cl(e));return n===null||ly(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(Il(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=Il(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Il(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function jl(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 by(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 xy(e){return e.username!==""||e.password!==""}function vl(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Pe="",He=null,B,Fs=!1,Ms=!1,ui=!1,bt;function xn(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,Pe="",He=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Fs=!1,Ms=!1,ui=!1,bt=r||0;let i=uw;switch(r){case 3:case 4:i=Us;break;case 5:i=Ml;break;case 6:i=li;break;case 7:i=wr;break;case 8:i=Hn}return i(G(e,E))!==1?B:null}function ne(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 Sy(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var uw=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 Pe=U.slice(E,n).toLowerCase(),E=n,lw(n<U.length?e:void 0)}else return bt?1:(--E,ne(t,e)?Iy(G(U,E)):0)},lw=e=>{let t=E;if(e===58){if(bt){if(At(B.scheme)!==At(Pe))return 0;if((xy(B)||B.port!==null)&&Pe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Pe,bt?(B.port===Ay(B.scheme)&&(B.port=null),0):(Pe="",B.scheme==="file"?ne(t,e)?ql(G(U,E)):0:At(B.scheme)&&He!==null&&He.scheme===B.scheme?ne(t,e)?dw(G(U,E)):0:At(B.scheme)?ne(t,e)?mw(G(U,E)):0:G(U,E+1)===47?(E++,ne(t,e)?pw(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ne(t,e)?wy(G(U,E)):0))}else return bt?1:(Pe="",E=-1,ne(t,e)?Iy(G(U,E)):0)},Iy=e=>{let t=E;return He===null||He.opaquePath&&e!==35?1:He.opaquePath&&e===35?(B.scheme=He.scheme,B.path=He.path.slice(),B.opaquePath=He.opaquePath,B.query=He.query,B.fragment="",ne(t,e)?Hn(G(U,E)):0):He.scheme==="file"?(E--,ne(t,e)?ql(G(U,E)):0):(E--,ne(t,e)?Fl(G(U,E)):0)},dw=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ne(t,e)?Vs(G(U,E)):0):(E--,ne(t,e)?Fl(G(U,E)):0)},pw=e=>{let t=E;return e===47?ne(t,e)?Qi(G(U,E)):0:(E--,ne(t,e)?Un(G(U,E)):0)},Fl=e=>{let t=E;return B.scheme=He.scheme,e===47||At(B.scheme)&&e===92?ne(t,e)?dy(G(U,E)):0:(B.username=He.username,B.password=He.password,B.host=He.host,B.port=He.port,B.path=He.path.slice(),B.query=He.query,e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ne(t,e)?Un(G(U,E)):0):ne(t,e)?Fl(G(U,E)):0)},dy=e=>{let t=E;return At(B.scheme)&&(e===47||e===92)?ne(t,e)?Vs(G(U,E)):0:e===47?ne(t,e)?Qi(G(U,E)):0:(B.username=He.username,B.password=He.password,B.host=He.host,B.port=He.port,E--,ne(t,e)?Un(G(U,E)):0)},mw=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ne(t,e)?Vs(G(U,E)):0},Vs=e=>{let t=E;return e!==47&&e!==92?(E--,ne(t,e)?Qi(G(U,E)):0):ne(t,e)?Vs(G(U,E)):0},Qi=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!At(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&&At(B.scheme))break;n+=qn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?Qi(G(U,E)):0}if(e===64){Fs&&(Pe=`%40${Pe}`),Fs=!0;for(let n=0;n<Pe.length;n++){let r=Pe.codePointAt(n);if(r===58&&!Ms){Ms=!0;continue}let i=fy(r,qs);Ms?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Pe="",ne(t,e)?Qi(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&At(B.scheme)?Fs&&Pe===""?1:(E-=Pe.length+1,Pe="",ne(t,e)?Us(G(U,E)):0):(Pe+=Sy(e),ne(t,e)?Qi(G(U,E)):0)},Us=e=>{let t=E;if(bt&&B.scheme==="file")return E--,ne(t,e)?Ul(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!At(B.scheme))){let n=E+qn(e);for(e===91?ui=!0:e===93&&(ui=!1);n<U.length;){let r=G(U,n);if(r==null||!ui&&r===58||r===35||r===47||r===63||r===92&&At(B.scheme))break;r===91?ui=!0:r===93&&(ui=!1),n+=qn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?Us(G(U,E)):0}else if(e===58&&!ui){if(Pe===""||bt===4)return 1;let n=kl(Pe,!At(B.scheme));return n===null?1:(B.host=jl(n),Pe="",ne(t,e)?Ml(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&At(B.scheme)){if(E--,At(B.scheme)&&Pe==="")return 1;if(bt&&Pe===""&&(xy(B)||B.port!==null))return 1;let n=kl(Pe,!At(B.scheme));return n===null?1:(B.host=jl(n),Pe="",bt?0:ne(t,e)?li(G(U,E)):0)}else return Pe+=Sy(e),ne(t,e)?Us(G(U,E)):0},Ml=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 Pe+=U.slice(E,n),E=n-1,ne(t,e)?Ml(G(U,E)):0}else if(bt||e==null||e===35||e===47||e===63||e===92&&At(B.scheme)){if(Pe!==""){let n=parseInt(Pe,10);if(n>65535)return 1;if(B.port=n===Ay(B.scheme)?null:n,Pe="",bt)return 0}return bt?1:(E--,ne(t,e)?li(G(U,E)):0)}else return 1};function vy(e,t){let n=e.length-t;if(n<2)return!1;if(gy(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 ql=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ne(t,e)?fw(G(U,E)):0:He?.scheme==="file"?(B.host=He.host,B.path=He.path.slice(),B.opaquePath=He.opaquePath,B.query=He.query,e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):e!=null?(B.query=null,vy(U,E)?B.path=[]:by(B),E--,ne(t,e)?Un(G(U,E)):0):ne(t,e)?ql(G(U,E)):0):(E--,ne(t,e)?Un(G(U,E)):0)},fw=e=>{let t=E;return e===47||e===92?ne(t,e)?Ul(G(U,E)):0:(He!==null&&He.scheme==="file"&&(!vy(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})(He.path[0])&&B.path.push(He.path[0]),B.host=He.host),E--,ne(t,e)?Un(G(U,E)):0)},Ul=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 Pe+=U.slice(E,n),E=n-1,ne(t,e)?Ul(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!bt&&yy(Pe))return ne(t,e)?Un(G(U,E)):0;if(Pe==="")return B.host="",bt?0:ne(t,e)?li(G(U,E)):0;{let n=kl(Pe,!At(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=jl(n),Pe="",bt?0:ne(t,e)?li(G(U,E)):0)}}return 1},li=e=>{let t=E;return At(B.scheme)?(e!==92&&e!==47&&E--,ne(t,e)?Un(G(U,E)):0):!bt&&e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):!bt&&e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):e!=null?(e!==47&&E--,ne(t,e)?Un(G(U,E)):0):(bt&&B.host===null&&B.path.push(""),ne(t,e)?li(G(U,E)):0)},Un=e=>{let t=E;if(e!=null&&e!==47&&(!At(B.scheme)||e!==92)&&(bt||e!==63&&e!==35)){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||At(B.scheme)&&r===92||!bt&&(r===63||r===35))break;n+=qn(r)}Pe+=Kn(U.slice(E,n),_l),E=n,e=G(U,n)}if(e==null||e===47||At(B.scheme)&&e===92||!bt&&(e===63||e===35)){let n=At(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}})(Pe)?(by(B),e!==47&&!n&&B.path.push("")):uy(Pe)&&e!==47&&!n?B.path.push(""):uy(Pe)||(B.scheme==="file"&&B.path.length===0&&yy(Pe)&&(Pe=`${Pe[0]}:`),B.path.push(Pe)),Pe="",e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):ne(t,e)?Un(G(U,E)):0}else return Pe+=fy(e,_l),ne(t,e)?Un(G(U,E)):0},wy=e=>{let t=E;if(e===63)return B.query="",ne(t,e)?wr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Hn(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]+=Kn(r.slice(0,-1),ea)+"%20":B.path[0]+=Kn(r,ea),E=n,(e=G(U,n))===63)return B.query="",ne(t,e)?wr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Hn(G(U,E)):0}return ne(t,e)?wy(G(U,E)):0},wr=e=>{let t=E,n=E;if(e!=null){if(bt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=At(B.scheme)?Lv:Nl;B.query+=Kn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!bt?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):ne(t,e)?wr(G(U,E)):0},Hn=e=>{let t=E;return e!=null&&(B.fragment+=Kn(U.slice(E),Vv),E=U.length),ne(t,e)?Hn(G(U,E)):0};function Tl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Oy(e){switch(e.scheme){case"blob":{let t=xn(Tl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Oy(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"),Pn=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=xn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=xn(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=xn(n,null,null,0),r==null)?!1:xn(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+=Tl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ze].url)}set href(t){let n=xn(t=We(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze].url=n,this[Ze].query&&wl(this[Ze].query,n.query)}get origin(){return Oy(this[Ze].url)}get protocol(){return`${this[Ze].url.scheme}:`}set protocol(t){xn(`${t=We(t)}:`,this[Ze].url,null,2)}get username(){return this[Ze].url.username}set username(t){t=We(t),vl(this[Ze].url)||(function(r,i){r.username=Kn(i,qs)})(this[Ze].url,t)}get password(){return this[Ze].url.password}set password(t){t=We(t),vl(this[Ze].url)||(function(r,i){r.password=Kn(i,qs)})(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||xn(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||xn(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];vl(n)||(t?xn(t,n,null,5):n.port=null)}get pathname(){return Tl(this[Ze].url)}set pathname(t){t=We(t);let{url:n}=this[Ze];n.opaquePath||(n.path=[],xn(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&&wl(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",xn(i,n,null,7),r&&wl(r,n.query)}}get searchParams(){let t=this[Ze],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Bs;return o[dt].url=i,o[dt].serialized=a==null,a&&(o[dt].list=Dl(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="",xn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(Pn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var dt=Symbol("URLSearchParamsImpl"),hw=Symbol.dispose||Symbol.for("dispose");function wl(e,t){t?e[dt].list=Dl(t):e[dt].list.length=0,e[dt].serialized=t==null}function Ns(e){if(e.url){let t=El(e.list);(function(r,i){r[Ze].url.query=i})(e.url,t||null),e.serialized=!0}}var gw=typeof Iterator<"u"?Iterator:Object,Xo=class extends gw{constructor(t,n){super(),this[dt]={ptr:t,map:n,index:0}}next(){let t=this[dt];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}[hw](){}},Bs=class{constructor(t){let n=this[dt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(iy(t[i]));else if((r=py(t))!=null){let i;for(;!(i=Ol(r.next())).done;)n.list.push(iy(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=Uv(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=Dl(i)}}get size(){return this[dt].list.length}append(t,n){t=We(t),n=We(n),this[dt].list.push([t,n]);let r=this[dt];r.url&&r.serialized?(function(a,o){let s=a[Ze].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,El([[t,n]])):Ns(r)}delete(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[dt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Ns(this[dt])}get(t){t=We(t);let{list:n}=this[dt];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[dt];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[dt];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[dt],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&&Ns(this[dt])}sort(){this[dt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Ns(this[dt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[dt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Xo(this[dt],t=>t)}keys(){return new Xo(this[dt],t=>t[0])}values(){return new Xo(this[dt],t=>t[1])}toString(){return El(this[dt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Bs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Or="https://api.longplayai.com";function Py(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=cr.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 Cy=Symbol("IndianaNoContent");function Pr(e,t,n=Pn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Me.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??Or);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??Py(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((Fe,at)=>{ke=()=>at(ye()),le.signal.addEventListener("abort",ke,{once:!0})}),xt=setTimeout(()=>le.abort(),C.timeoutMs??c),et=async()=>{let Fe=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...C.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[nc]:rc.current,[sd]:ry.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 at;try{at=Fe.status===204?Cy:await Fe.json()}catch{throw le.signal.aborted?ye():new b(Fe.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Fe.status,Fe.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(!Fe.ok){let ht=tc.safeParse(at),Xt=ht.success&&(!Zn.safeParse(ht.data.error.code).success||od(ht.data.error.code,Fe.status)),kr=Xt?ht.data.error.code:"HTTP_ERROR",jr=ca(kr,Fe.status,{retryAfter:Fe.headers.get("Retry-After"),recovery:Xt?ht.data.error.recovery:void 0,reason:Xt?ht.data.error.reason:void 0});throw new b(kr,Xt?ht.data.error.message:"Longplay request failed",Fe.status,Fe.headers.get("X-Request-Id")??(ht.success?ht.data.requestId:void 0),{...jr,...ht.success&&ht.data.error.retryable===!1?{retryable:!1}:{},...jr.retryAfterSeconds===void 0&&ht.success&&ht.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ht.data.error.retryAfterSeconds}:{}})}if(Fe.headers.get(nc)!==rc.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&at!==Cy){let ht=at&&typeof at=="object"&&"scope"in at?at:at&&typeof at=="object"&&"configuration"in at?at.configuration:null;if(!ht||typeof ht!="object"||!("scope"in ht))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Xt=Me.safeParse(ht.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 pi=Fe.headers.get("X-Indiana-Telemetry-Subject");if(pi){if(!/^[a-f0-9]{64}$/.test(pi))throw new b("INVALID_RESPONSE","Invalid telemetry identity");p!==pi&&(p=pi,t?.(p))}return at};try{return await Promise.race([et(),Se])}catch(Fe){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Fe instanceof b?Fe:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(xt),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=Me.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 _y(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(!Ut.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 Bl(e,t,n,r){if(!Kd(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 Cr(e,t,n){if(e.requirement){if(!t)throw new b("INVALID_RESPONSE","The requested access check is missing");Bl(e.requirement,t,e.customerId,n)}}function Qe(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var yw={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Ey(e){return{async checkEntitlement(t){Qe(t);let n=O.checkEntitlement,r=n.request.parse(t),i=await ge(e,n,r);return Bl(r.requirement,i.check,void 0,i.scope),i},async readHoldings(t={}){return ge(e,yw,t)}}}function Ry(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Qe(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Qe(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function ky(e){return{async setupPayment(t){Qe(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Qe(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Qe(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Qe(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Qe(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Qe(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Qe(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Qe(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Qe(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Qe(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function jy(e){return{async previewUpdate(t){Qe(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Qe(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Qe(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Qe(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Qe(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Qe(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Qe(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Ty(e){return{async redeemReward(t){return Qe(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 Qe(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Qe(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 Ny(e){return{...Ey(e),...Ry(e),...ky(e),...jy(e),...Ty(e)}}function Dy(e){return{async resolveContent(t){Qe(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Qe(t);let n=O.resolvePaywall,r=n.request.parse(t),i=await ge(e,n,r);return Cr(r,i.paywall.check,i.scope),i},async resolveOffering(t){Qe(t);let n=O.resolveOffering,r=n.request.parse(t),i=await ge(e,n,r);return Cr(r,i.check,i.scope),i}}}var Vl=e=>new TextEncoder().encode(JSON.stringify(e)).length,Fy=16384;function My(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&&!Kf(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(Vl({events:[y]})>Fy)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=Vl({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=Vl(_)+(x.length?1:0);if(x.length&&v+X>Fy)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 Ls(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:Et.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(Yn(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=cs.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=Et.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?Mo.parse(x):null,C=v??vn.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(kt(le)!==kt(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=Ii(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=Et.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 qy(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=qy(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Uy(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 xt=qy(Se);n.track(ye,ke,xt?{merchandise:xt}:{})}catch(xt){R(xt)}},A=Ls({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()}}}var By=require("zod");function Vy(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=By.z.object({funnelId:Rs.shape.id,funnelVersionId:Rs.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 Cr(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 Cr(c,u.paywall.check,u.scope),u},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Ly(e){let t=Pr(e),n=t.request,r;try{r=Xg(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=_y(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=My(n,i.isIdentified),o=Uy(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...ny(n,r),...Ny(n),...Dy(n),forFunnel(s){return i.assertActive(),Vy(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 Ji(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)=>Ji(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)&&Ji(a,Reflect.get(t,i)))}function zs(e,t){let n=Fg.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 Zi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $s(e){let t=Ut.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Zi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Rt.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=Pr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=zs(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")||!Ji(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 Ll(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 zy(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ll(e,t,n))}function Gs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Xu(n)===t.sha256}async function Ks(e,t){let n=oi.parse(t),{artifact:r,environmentId:i}=n.content,a=new Pn(e.baseUrl??Or).origin,o=new Pn(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 Ll(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(!Gs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return zh(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var $y=(e,t)=>new b(e,t);var bw=3,xw=2e3;function Sw(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Iw(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===bw||!Sw(n))throw n;await new Promise(r=>setTimeout(r,t*xw))}}async function zl(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=vw(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await Iw(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function vw(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=yl({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:vn.parse(o)}),c=ww(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 ww(e,t,n){return Yg(e,t,n,$y)}var ln=require("zod");var Gy=Rt.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}),Ky=ln.z.strictObject({schemaVersion:ln.z.literal(1),scope:Me,runId:ln.z.uuid(),funnelId:ln.z.uuid(),versionId:ln.z.uuid(),processBindingIds:ln.z.record(ln.z.uuid(),ln.z.uuid().nullable()).optional(),command:Gy.optional(),closeCommand:Gy.refine(e=>e.operation==="close").optional(),purchase:ln.z.strictObject({receiptId:ln.z.uuid(),operationId:ln.z.uuid(),generation:ln.z.number().int().nonnegative()}).optional(),closed:ln.z.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"),Hs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Hy(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:Ky.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(Hs(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=Ky.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&&!Hs(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&&!Hs(m.closeCommand,p))throw rn();return{...m,closeCommand:p,closed:!0}}if(!Hs(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 Qy(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??Or).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 Jy(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||!Ji(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(!Ut.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 _r(e){let{customerToken:t,...n}=e;return n}var Ow=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Zy({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:_r(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&&!Ow(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function h(y){let A=Rt.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(_r(a))!==JSON.stringify(_r(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(_r(i))!==JSON.stringify(_r(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,xt=le?.receiptId??ke?.receiptId,et=X?.selectionGeneration??u?.generation??0;if(e&&Se&&xt&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||et>=u.generation)){let Fe={receiptId:xt,operationId:Se,generation:et},at=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},Fe,at,j),t.assertCurrent(x),(!u||Fe.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(at?u?.operationId===Fe.operationId&&(u=void 0):u=Fe)}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 Er(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"||!Zi.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=Pr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=Jy(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Qy(e):void 0),o=a&&Hy(a),s=Zy({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,xt)=>{ye=()=>xt(X.reason),X.addEventListener("abort",ye,{once:!0}),le=setTimeout(()=>xt(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"?Jo.parse(j):Rt.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!C?{[Mg]: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,_=zs(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 zl(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;zl(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:Dg(_.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(_r(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(_r(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 Ks(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=Vg.parse(await c(Jo.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 Wy(e){if(!Ut.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=$s({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Er({...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 Yy(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 Xy(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function eA(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 tA(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 nA(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 rA(e,t){if(!Ut.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=Pr(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});Cr(n,v.paywall.check,v.scope);let C=await Ks(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&&(!Yy(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:kd(v.merchantTerms)}:{}});return Xy(ye.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(ye.operation):(s=tA(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 nA({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=zf(v.product,x.selection,i.capabilities);if(!C)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Nh(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(),eA(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 iA(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 Pw=O.trackUsage.request.shape.command,Cw=O.trackUsage.response;function oA(e){let t=Me.parse(e.scope),n=Ly({...e,scope:t}),r={...e,scope:t,session:n.session},i=iA(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 Wy({...r,customerToken:s()})},resumeFunnel(c){return s(),Er({...r,runToken:c})},paywall(c){return rA(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Pw.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=Cw.parse(p);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}var cA=require("zod");var Wi=require("zod");var _w=Wi.z.record(Wi.z.string().regex(/^[a-f0-9]{64}$/),Wi.z.strictObject({at:Wi.z.number(),text:Wi.z.string()})),di=2*1048576,Ew=100;function Rw(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function aA(e,t){let n=t===void 0?Rw():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),Ew)})]);return typeof h=="string"&&h.length<=di&&new TextEncoder().encode(h).byteLength<=di?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 _w.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>di||new TextEncoder().encode(p).byteLength>di||(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>di)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>di||(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+_>di||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 Ce=(e,t)=>new b(e,t),Rr=()=>performance.now(),sA=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function uA(e){let t=Zu.parse(e.scope),n=new Pn(e.origin??Or);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 Ce("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let W=new Pn(Y);if(W.protocol!=="https:"||W.username||W.password||W.search||W.hash||W.pathname!=="/")throw Ce("INVALID_URL","Invalid configuration asset origin");return W.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${kt(t)}`,s=aA(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&&Rr()<u&&Date.now()<l;function xt(){if(!Se())throw Ce("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function et(Y,W,me){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+me>sn.maxCacheBytes);){let fe=j.entries().next().value;X-=fe[1].byteLength,j.delete(fe[0])}j.set(Y,{text:W,byteLength:me}),X+=me}}function Fe(Y,W,me){return zy(Y,W,{signal:me,error:fe=>Ce("INVALID_RESPONSE",fe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function at(Y){let W=new Pn(Y,n);if(!r.has(W.origin)||W.username||W.password||W.hash||W.search)throw Ce("INVALID_URL","Configuration artifact origin is not trusted");return W.href}async function ta(Y,W,me=!1){let fe=await i(at(Y),{method:"GET",credentials:"omit",redirect:"error",cache:me?"default":"no-cache",signal:W,headers:{}});if(fe.status===429){let rt=fe.headers.get("retry-after")??"";x=/^\d+$/.test(rt)?Number(rt)*1e3:Math.max(0,Date.parse(rt)-Date.now())||15e3}if(!fe.ok&&fe.status!==304)throw Ce(`CONFIGURATION_HTTP_${fe.status}`,"Configuration synchronization failed");return fe}function pi(Y,W,me){let fe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),rt=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),ut=Date.parse(Y.headers.get("date")??""),Je=Y.headers.get("age"),dn=Je!==null&&/^\d+(\.\d+)?$/.test(Je)?Number(Je)*1e3:NaN;if(![fe,rt,ut,dn].every(Number.isFinite)||rt<=fe||rt-fe>sn.maxControlAgeMs||fe>ut+1e3)throw Ce("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Gt=Math.min(rt-fe,me.maxControlAgeSeconds*1e3,sn.maxControlAgeMs)-Math.max(dn,ut-fe,0)-(Rr()-W);if(Gt<=0)throw Ce("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Rr()+Gt}function ht(){if(clearTimeout(y),clearTimeout(A),m||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?ht():ye()},Math.max(1,u-Rr())),sA(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))),sA(y)}async function Xt(){if(m)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=h,W=new AbortController;R=W;let me=(async()=>{if(!le){le=!0;try{let ra=await s.readManifest();if(ra&&!c){let Jn=Yu.parse(JSON.parse(ra));kt(Jn.scope)===kt(t)&&(c=Jn)}}catch{}}W.signal.throwIfAborted();let Je=c,dn=Rr(),Qt=await ta(a,W.signal);Qt.status===304&&(!Je||!Qt.headers.has("x-indiana-config-validated-at")||!Qt.headers.has("x-indiana-config-valid-until")||!Qt.headers.has("age"))&&(Qt=await ta(a,W.signal));let Gt=Qt.status===304?Je:Yu.parse(JSON.parse(await Fe(Qt,sn.maxManifestBytes,W.signal))),{generation:mi,...fi}=Gt,Qn=Qt.headers.get("etag");if(kt(Gt.scope)!==kt(t)||Uh(fi)!==mi||Qn!==`"${mi}"`&&Qn!==`W/"${mi}"`)throw Ce("INVALID_RESPONSE","Configuration scope or content identity changed");if(Je&&(Gt.revision<Je.revision||Gt.revision===Je.revision&&Gt.generation!==Je.generation))throw Ce("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ra,Jn]of Object.entries(Je?.funnels??{})){let Nr=Gt.funnels[ra];if(Nr&&(Nr.controlRevision<Jn.controlRevision||Nr.evaluationRevision<Jn.evaluationRevision||Nr.controlRevision===Jn.controlRevision&&Nr.state!==Jn.state||Nr.evaluationRevision===Jn.evaluationRevision&&Nr.evaluationMode!==Jn.evaluationMode))throw Ce("INVALID_RESPONSE","Funnel control revision changed identity")}let Tr=pi(Qt,dn,Gt.policy);if(W.signal.throwIfAborted(),Y!==h)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Gt,u=Tr,l=Date.now()+Math.max(0,Tr-Rr()),p=!1,d=0,x=0,s.writeManifest(kt(Gt)),ye(),structuredClone(Gt)})(),fe=setTimeout(()=>W.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs),rt=new Promise((Je,dn)=>W.signal.addEventListener("abort",()=>dn(W.signal.reason),{once:!0})),ut=Promise.race([me,rt]).catch(Je=>{throw d++,(Je instanceof cA.z.ZodError||Je instanceof SyntaxError||Je instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Je.code))&&(u=0,p=!0,ye()),Je}).finally(()=>{clearTimeout(fe),g===ut&&(g=void 0),ht()});return g=ut,ut}async function kr(Y){let W=Y.sha256,me=fi=>Gs(fi,Y);at(Y.url);let fe=j.get(W);if(fe){if(fe.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(W),j.set(W,fe),fe.text}let rt=_.get(W);if(rt){if(rt.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return rt.promise}let ut=new AbortController;C.add(ut);let Je=h,dn=(async()=>{try{let Tr=await s.readArtifact(W);if(Tr&&me(Tr)){if(ut.signal.throwIfAborted(),m||Je!==h)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return et(W,Tr,Y.byteLength),Tr}}catch{}ut.signal.throwIfAborted();let fi=await ta(Y.url,ut.signal,!0),Qn=await Fe(fi,Y.byteLength,ut.signal);if(!me(Qn))throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||Je!==h)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return et(W,Qn,Y.byteLength),s.writeArtifact(W,Qn),Qn})(),Qt=setTimeout(()=>ut.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),sn.initializationMs),Gt=new Promise((fi,Qn)=>ut.signal.addEventListener("abort",()=>Qn(ut.signal.reason),{once:!0})),mi=Promise.race([dn,Gt]).finally(()=>{clearTimeout(Qt),C.delete(ut),_.delete(W)});return _.set(W,{promise:mi,byteLength:Y.byteLength}),mi}async function jr(){return Se()||await Xt(),xt(),c}async function Yi(Y){let W,me=new Promise((fe,rt)=>{W=setTimeout(()=>rt(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs)});try{return await Promise.race([Y(),me])}finally{clearTimeout(W)}}function Xi(Y,W){if(xt(),c?.generation!==Y.generation)throw Ce("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(W&&c.funnels[W]?.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Gl(Y){let W=Y.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let me=Y.artifacts[W];if(me.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let fe=Iu.parse(JSON.parse(await kr(me)));if(kt(fe.scope)!==kt({projectId:t.projectId,environment:t.environment})||fe.generation!==me.generation||fe.remoteFeatures.some(rt=>Object.hasOwn(fe.features,rt)))throw Ce("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Xi(Y),{...fe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Rr())).toISOString()}}async function Kl(Y,W){let me=await jr(),fe=me.funnels[Y];W&&(!fe||fe.evaluationMode==="local"&&!fe.versions[W])&&(g&&await g,me=await Xt()),Xi(me,Y);let rt=me.funnels[Y];if(rt.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let ut=W??rt.currentVersionId,Je=rt.versions[ut];if(!Je)throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(me.artifacts[Je.artifact].formatVersion!==3)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[dn,Qt]=await Promise.all([kr(me.artifacts[Je.artifact]).then(Gt=>Vh(JSON.parse(Gt))),rt.evaluationMode==="local"?Gl(me):void 0]);if(Qt&&kt(Bh(dn,Qt))!==kt(Je.dependencies))throw Ce("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Xi(me,Y),{document:dn,growth:Qt,versionId:ut,control:structuredClone(rt),manifest:structuredClone(me)}}async function Hl(Y,W){try{return await Kl(Y,W)}catch(me){if(!(me instanceof b)||!(me.code==="CONFIGURATION_CHANGED"||me.code==="CONFIGURATION_HTTP_404"&&Se()))throw me;let fe=c?.generation;if(g&&await g,await Xt(),me.code!=="CONFIGURATION_CHANGED"&&c?.generation===fe)throw me;return Kl(Y,W)}}function Qs(){p=!0,ye(),Xt().catch(ke)}let na=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Qs()};function pA(Y){if(m)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Qs),window.addEventListener("focus",na),document.addEventListener("visibilitychange",na)),ht()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Ql())}}function Ql(){typeof window<"u"&&(window.removeEventListener("online",Qs),window.removeEventListener("focus",na),document.removeEventListener("visibilitychange",na))}return{scope:Object.freeze({...t}),refresh:Xt,subscribe:pA,assertFresh:xt,assertFeatures(Y){xt();let W=c.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[W].generation!==Y)throw Ce("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-Rr()):0},async features(){return Yi(async()=>Gl(await jr()))},pageExperiments:()=>Yi(async()=>{let Y=await jr(),W=Y.gb.pageExperiments;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let me=Y.artifacts[W];if(me.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let fe=Jg.parse(JSON.parse(await kr(me)));if(fe.environmentId!==t.environmentId||fe.generation!==me.generation)throw Ce("INVALID_RESPONSE","Page experiment scope or generation changed");return Xi(Y),fe}),funnel:(Y,W)=>Yi(()=>Hl(Y,W)),paywall:(Y,W)=>Yi(async()=>{let me=await jr(),fe=me.paywalls?.[Y];if(!fe||!W&&fe.state!=="published")throw Ce("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let rt=W??fe.currentVersionId,ut=fe.versions[rt],Je=ut&&me.artifacts[ut.artifact];if(!Je||Je.kind!=="paywall"||Je.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let dn=Cs.parse(JSON.parse(await kr(Je)));return Xi(me),{document:dn,versionId:rt,version:ut.version,control:structuredClone(fe),manifest:structuredClone(me)}}),async localFunnel(Y,W){let me=await Yi(()=>Hl(Y,W));if(!me.growth)throw Ce("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:fe,remoteFeatures:rt,...ut}=me.growth;return Hg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:me.versionId,evaluationMode:"local",evaluationRevision:me.control.evaluationRevision,document:me.document,payload:ut})},assertFunnel(Y,W,me){xt();let fe=c.funnels[Y];if(!fe||fe.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable");if(fe.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel now executes at Longplay");if(W!==void 0&&fe.controlRevision!==W)throw Ce("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(me!==void 0&&!fe.versions[me])throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,R?.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Ql(),ye(),v.clear();for(let Y of C)Y.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function lA(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&&kt(n)!==kt(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=Zi.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=$s({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Er({...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 $l(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function dA(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=gl.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)$l(j,d.run);d.run.instruction?.type==="authentication_required"&&$l(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=Er({...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()}}}
|
|
17
|
+
*/var ve=N.z.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"})}),Et=N.z.record(N.z.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"})}),Tb=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=Et.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.z.strictObject({id:N.z.uuid(),attributeKey:N.z.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("$")&&!Tb.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)}),Nb=N.z.discriminatedUnion("type",[N.z.strictObject({type:N.z.literal("condition"),condition:nn}),N.z.strictObject({type:N.z.literal("list"),attributeKey:N.z.string().min(1).max(128),values:N.z.array(N.z.union([N.z.string(),N.z.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 Xn(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 Db=N.z.record(N.z.uuid(),Nb).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"&&Xn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Dc=N.z.tuple([N.z.number().min(0).max(1),N.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Ep=N.z.strictObject({attribute:N.z.string().optional(),seed:N.z.string().min(1),hashVersion:N.z.literal(2),ranges:N.z.array(Dc).min(1).max(100)}),Fb=N.z.strictObject({id:N.z.string().min(1).max(128),condition:nn,gate:N.z.boolean().optional()}),Nc={id:N.z.string().max(128).optional(),condition:nn.optional(),parentConditions:N.z.array(Fb).max(50).optional(),filters:N.z.array(Ep).max(20).optional()},Mb=N.z.union([N.z.strictObject({...Nc}),N.z.strictObject({...Nc,force:ve,coverage:N.z.number().min(0).max(1).optional(),range:Dc.optional(),seed:N.z.string().min(1).optional(),hashAttribute:N.z.string().optional(),hashVersion:N.z.literal(2).optional()}),N.z.strictObject({...Nc,type:N.z.literal("experiment-ref"),experimentId:N.z.uuid(),values:N.z.record(N.z.string().min(1),ve),meta:N.z.record(N.z.string().min(1),N.z.strictObject({passthrough:N.z.boolean()})).optional()})]),qb=N.z.strictObject({defaultValue:ve,rules:N.z.array(Mb).max(100)}),FP=N.z.record(N.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),qb).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)}),Ub=N.z.strictObject({name:N.z.string().max(80),reason:N.z.string().max(500),dateStarted:N.z.iso.datetime({offset:!0}),dateEnded:N.z.iso.datetime({offset:!0}).nullable(),coverage:N.z.number().min(0).max(1),variationWeights:N.z.array(N.z.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.z.array(N.z.strictObject({match:N.z.enum(["any","all","none"]),ids:N.z.array(N.z.uuid()).min(1)})).max(50),namespace:N.z.strictObject({id:N.z.uuid(),ranges:N.z.array(Dc).min(1)}).nullable(),seed:N.z.string().min(1).max(128)}),Bb=N.z.strictObject({key:N.z.string().min(1).max(128),name:N.z.string().min(1).max(80),hypothesis:N.z.string().max(2e3),status:N.z.enum(["draft","running","stopped"]),hashAttribute:N.z.string().min(1).max(128),fallbackAttribute:N.z.string().max(128).nullable(),hashVersion:N.z.literal(2),disableStickyBucketing:N.z.boolean(),bucketVersion:N.z.number().int().min(0).max(1e3),minBucketVersion:N.z.number().int().min(0).max(1e3),variations:N.z.array(N.z.strictObject({id:N.z.string().min(1),key:N.z.string().min(1),name:N.z.string().max(80),description:N.z.string().max(500)})).min(2).max(20),phases:N.z.array(Ub).min(1).max(100),releasedVariationId:N.z.string().nullable(),excludeFromPayload:N.z.boolean(),statusSchedule:N.z.strictObject({startAt:N.z.iso.datetime({offset:!0}).nullable(),stopAt:N.z.iso.datetime({offset:!0}).nullable(),stopAfter:N.z.strictObject({value:N.z.number().int().positive().max(36500),unit:N.z.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 Vb=Bb.safeExtend({filters:N.z.array(Ep).optional()}),Lb=N.z.strictObject({experiments:N.z.record(N.z.uuid(),Vb),savedGroups:Db}),mo=N.z.strictObject({attributeName:N.z.string(),attributeValue:N.z.string(),assignments:N.z.record(N.z.string(),N.z.string())}),MP=N.z.strictObject({snapshot:Lb,attributes:Et,results:Et,stickyBucketAssignmentDocs:N.z.record(N.z.string(),mo)}),qP=N.z.strictObject({variantKey:N.z.string().nullable(),bucketVersion:N.z.number().int().min(0),source:N.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.z.number().min(0).max(1).optional(),stickyBucketUsed:N.z.boolean().optional(),hashUsed:N.z.boolean().optional()});function pr(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 zb=Nt.z.enum(["active","inactive"]),$b=Nt.z.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},Et),Gb=Nt.z.strictObject({id:Nt.z.string().trim().min(1).max(255),name:Nt.z.string().trim().min(1).max(255),status:zb,metadata:$b}),zP=Gb.extend({internal_id:Nt.z.uuid(),project_id:Nt.z.uuid(),environment_id:Nt.z.uuid(),created_at:Nt.z.iso.datetime({offset:!0}),updated_at:Nt.z.iso.datetime({offset:!0})}),kp=Nt.z.union([Nt.z.strictObject({id:Nt.z.string().trim().min(1).max(255)}),Nt.z.strictObject({internalId:Nt.z.uuid()})]),$P=Nt.z.enum(["customer","merchandise","context"]),GP=Nt.z.enum(["system","stored","request"]),KP=Nt.z.enum(["customer","merchandise","mixed"]),Rp=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Fc(e,t={},n=new Set){if(pr(e).some(Rp))return!0;for(let r of Xn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Rp(i.attributeKey)||i?.type==="condition"&&Fc(i.condition,t,n))return!0}return!1}var jp=require("zod"),Kb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,En=jp.z.string().max(16).regex(Kb,"\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 YP=ee.z.enum(["draft","active","paused","archived"]),mr=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("percent"),percentOff:ee.z.number().min(1).max(100).multipleOf(.01)}).strict(),ee.z.object({type:ee.z.literal("amount"),amountOffCents:ee.z.number().int().min(1).max(1e8),currency:Ie}).strict()]),mn=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("once")}).strict(),ee.z.object({type:ee.z.literal("repeating"),months:ee.z.number().int().min(1).max(36)}).strict(),ee.z.object({type:ee.z.literal("forever")}).strict()]),Tp=[ee.z.object({type:ee.z.literal("all")}).strict(),ee.z.object({type:ee.z.literal("plans"),planIds:ee.z.array(ee.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Hb=ee.z.discriminatedUnion("type",[...Tp,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.discriminatedUnion("type",[ee.z.strictObject({type:ee.z.literal("all")}),ee.z.strictObject({type:ee.z.literal("selected"),merchandiseIds:ee.z.array(ee.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),ee.z.strictObject({type:ee.z.literal("condition"),condition:nn})])})]),Mc=ee.z.discriminatedUnion("type",[...Tp,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.strictObject({type:ee.z.enum(["all","selected","condition"])})})]),Qb=ee.z.strictObject({firstPurchaseOnly:ee.z.boolean(),condition:nn}),XP=ee.z.object({name:ee.z.string().trim().min(1).max(80),description:ee.z.string().max(500),discount:mr,duration:mn,appliesTo:Hb,eligibility:Qb,selfClaimEnabled:ee.z.boolean().default(!1),startsAt:ee.z.iso.datetime().nullable(),endsAt:ee.z.iso.datetime().nullable(),totalLimit:ee.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ee.z.number().int().min(1).max(10),grantWindowHours:ee.z.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=>!Fc(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"]}),eC=ee.z.object({code:ee.z.string().trim().transform(e=>e.toUpperCase()).pipe(ee.z.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:ee.z.number().int().min(1).max(1e6).nullable(),expiresAt:ee.z.iso.datetime().nullable(),firstPurchaseOnly:ee.z.boolean(),minimumAmountCents:ee.z.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 fo=ee.z.object({id:ee.z.uuid(),couponId:ee.z.uuid(),status:ee.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ee.z.iso.datetime(),expiresAt:ee.z.iso.datetime(),coupon:ee.z.object({name:ee.z.string(),discount:mr,duration:mn,appliesTo:Mc}).strict()}).strict(),Np=ee.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Up=S.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),qc=S.z.string().regex(/^(0|[1-9]\d{0,14})$/),vi=S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Jb=S.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),ho=Jb,er=de.refine(e=>/[1-9]/.test(e)),Zt=S.z.iso.datetime({offset:!0}),Da=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"))},Zb=S.z.array(S.z.object({upTo:er.nullable(),unitAmountMinor:Up,flatAmountMinor:S.z.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&&Da(t.upTo)>Da(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Wb=S.z.discriminatedUnion("kind",[S.z.object({kind:S.z.literal("flat"),units:er,unitAmountMinor:Up}).strict(),S.z.object({kind:S.z.enum(["graduated","volume"]),units:er,tiers:Zb}).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"),Yb=S.z.strictObject({interval:S.z.enum(["month","year"]),count:S.z.number().int().min(1).max(12),anchor:S.z.enum(["membership","calendar"])}),go=S.z.object({currency:Ie,pricing:Wb,billingCycle:Yb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Dp={requestId:S.z.uuid(),productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},Bp=S.z.strictObject({interval:S.z.enum(["hour","day","week","month"]),intervalCount:S.z.number().int().min(1).max(12),limit:S.z.number().int().min(1).max(1e6)}),Vp=S.z.discriminatedUnion("kind",[S.z.object({...Dp,kind:S.z.literal("auto_topup"),threshold:ha,quantity:er.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Bp.optional()}).strict(),S.z.object({...Dp,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:ho,maxOutstandingMinor:ho}).strict()]),Fp={productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},Lp=S.z.discriminatedUnion("kind",[S.z.object({...Fp,kind:S.z.literal("auto_topup"),threshold:ha,quantity:er.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Bp.optional(),purchaseAmountMinor:ho,purchaseUnits:er}).strict(),S.z.object({...Fp,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:ho,maxOutstandingMinor:ho,cashPrice:go}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Fa=S.z.object({id:S.z.uuid(),terms:Lp,status:S.z.enum(["prepared","active","revoked","blocked"]),createdAt:Zt,acceptedAt:Zt.nullable(),effectiveAt:Zt.nullable(),revokedAt:Zt.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"),zp=S.z.object({authorizationId:S.z.uuid(),terms:Lp,setupUrl:S.z.url().nullable()}).strict(),$p=S.z.object({authorizationId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),Gp=S.z.object({authorizationId:S.z.uuid(),requestId:S.z.uuid()}).strict(),Kp=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:_t.optional(),limit:de.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.z.array(er).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&&Da(t)>Da(i)}),"Notification thresholds must increase"),Xb=Kp.safeExtend({requestId:S.z.uuid()}),Mp={control:S.z.literal("overage"),requestId:S.z.uuid(),internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable()},ex=S.z.discriminatedUnion("action",[S.z.strictObject({...Mp,action:S.z.literal("set"),allowed:S.z.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.z.boolean()}),S.z.strictObject({...Mp,action:S.z.literal("remove")})]),Hp=S.z.union([Xb,ex]),tx=S.z.strictObject({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),allowed:S.z.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.z.boolean(),interval:S.z.enum(["day","week","month","year"]),startsAt:Zt,endsAt:Zt,used:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),nx=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:_t.optional(),startsAt:Zt,endsAt:Zt,used:tn,reserved:tn,limit:de.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),notifiedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),includedAllowance:S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.z.array(er).max(8).optional(),notifiedAbsoluteThresholds:S.z.array(er).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"),rx=S.z.object({authorizationId:S.z.uuid(),status:S.z.enum(["idle","pending","blocked"]),taskId:S.z.uuid().nullable(),invoiceId:S.z.uuid().nullable(),hostedInvoiceUrl:S.z.url().nullable(),purchaseCount:S.z.number().int().nonnegative(),purchaseWindowEndsAt:Zt.nullable(),attemptCount:S.z.number().int().nonnegative(),failedAttemptCount:S.z.number().int().nonnegative(),suspendedAt:Zt.nullable(),nextAttemptAt:Zt.nullable(),failureReason:S.z.string().min(1).max(240).nullable()}).strict(),Qp=S.z.object({internal_feature_id:S.z.uuid().optional(),entityId:S.z.uuid().optional()}).strict(),Uc=S.z.object({authorizations:S.z.array(Fa).max(100),limits:S.z.array(Kp).max(100),overages:S.z.array(tx).max(100).optional(),windows:S.z.array(nx).max(200),autoTopups:S.z.array(rx).max(100),limited:S.z.boolean()}).strict(),ix=S.z.object({id:S.z.uuid(),internal_feature_id:S.z.uuid(),productVersionId:S.z.uuid(),authorizationId:S.z.uuid(),entityId:S.z.uuid().nullable(),units:de,amountMinor:vi,cashPrice:go}).strict(),yo=S.z.object({id:S.z.uuid(),sourceKind:S.z.enum(["product","usage","manual"]),providerInvoiceId:S.z.string().min(1).max(240).nullable(),status:S.z.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Zt.nullable(),endsAt:Zt.nullable(),amountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:qc,paidAmountMinor:qc,refundedAmountMinor:qc,createdAt:Zt,hostedInvoiceUrl:S.z.url().nullable(),adjustment:S.z.object({originalInvoiceId:S.z.uuid(),amountMinor:S.z.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:Zt.nullable(),reason:S.z.string().min(1).max(500).optional()}).strict().nullable(),lines:S.z.array(ix).max(100),linesLimited:S.z.boolean()}).strict(),Jp=S.z.object({invoiceId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),Zp=S.z.strictObject({requestId:S.z.uuid(),originalInvoiceId:S.z.uuid(),amountMinor:S.z.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.z.string().trim().min(1).max(500)}),Wp=S.z.object({after:S.z.uuid().nullable(),limit:S.z.number().int().min(1).max(100)}).strict(),Yp=S.z.object({rows:S.z.array(yo).max(100),nextCursor:S.z.uuid().nullable()}).strict(),qp=S.z.strictObject({id:S.z.string(),coupon:S.z.string(),start:S.z.number().nonnegative(),end:S.z.number().nullable()}),ox=S.z.strictObject({subscriptionId:S.z.string(),customerId:S.z.string(),accountId:S.z.string(),sourceItems:S.z.array(S.z.strictObject({id:S.z.string(),price_id:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(qp).optional()})).max(100),items:S.z.array(S.z.strictObject({id:S.z.string(),price:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(S.z.strictObject({coupon:S.z.string().optional(),terms:S.z.strictObject({id:S.z.string(),name:S.z.string().optional(),percent_off:S.z.number().optional(),amount_off:S.z.number().optional(),currency:S.z.string().optional(),duration:S.z.enum(["once","forever","repeating"]),duration_in_months:S.z.number().optional()}).optional(),discount:S.z.string().optional(),receipt:qp.optional()})).max(20)})).max(100)}),Xp=S.z.strictObject({membershipId:S.z.uuid(),requestId:S.z.uuid(),grantIds:S.z.array(S.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),em=S.z.strictObject({membershipId:S.z.uuid(),operationId:S.z.uuid(),status:S.z.enum(["pending","effective"]),execution:ox.nullable(),grants:S.z.array(S.z.strictObject({id:S.z.uuid(),couponId:S.z.uuid(),name:S.z.string(),discount:mr,duration:mn,startedAt:Zt.nullable()})).max(20)});var wi=require("zod");var tm=wi.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),nm=wi.z.number().int().min(1).max(1e3),Ma=wi.z.object({cap:de.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:wi.z.number().positive().max(1e4).nullable(),cycles:wi.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var tr=require("zod");var rm=tr.z.strictObject({itemKey:tr.z.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:tr.z.uuid(),includedAmount:tr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:tr.z.number().int().min(0).max(1e4),terms:Ca,pricing:uo.optional(),unitAmountMinor:tr.z.number().int().min(0).max(1e8),productId:tr.z.string().min(1).max(255).nullable(),priceId:tr.z.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{rp(e.includedAmount,e.terms.units,e.quantity),Pa({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"})}});var te=require("zod");var Gr=de.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Ao=te.z.string().min(1).max(120),qa=te.z.enum(["cap","overflow"]),fn=(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"))},bo=e=>{try{return e()}catch{return!1}},xo=te.z.discriminatedUnion("operation",[te.z.object({operation:te.z.literal("quote"),overageBehavior:qa.optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Gr,properties:_t}).strict(),te.z.object({operation:te.z.literal("consume"),overageBehavior:qa.optional(),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:de,properties:_t,idempotencyKey:Ao}).strict(),te.z.object({operation:te.z.literal("reserve"),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Gr,properties:_t,idempotencyKey:Ao,expiresInSeconds:te.z.number().int().min(1).max(86400)}).strict(),te.z.object({operation:te.z.literal("confirm"),operationId:te.z.uuid(),quantity:Gr,properties:_t.optional(),idempotencyKey:Ao}).strict(),te.z.object({operation:te.z.literal("refund"),operationId:te.z.uuid(),quantity:Gr,idempotencyKey:Ao}).strict(),te.z.object({operation:te.z.literal("release"),operationId:te.z.uuid(),idempotencyKey:Ao}).strict()]),Bc=te.z.object({internal_credit_feature_id:te.z.uuid().nullable(),internal_metered_feature_id:te.z.uuid(),dimension:te.z.string().min(1).max(64),counterKey:te.z.string().min(1).max(240),cycleStart:te.z.iso.datetime({offset:!0}),unitCost:de,units:Gr,amount:tn,tier:te.z.number().int().min(1).max(12).nullable()}).strict(),Kr=te.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function im(e,t){let n=e.reduce((r,i)=>r+fn(i.units,12),0n)-fn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var om=te.z.discriminatedUnion("funding",[te.z.strictObject({funding:te.z.literal("balance"),sourceId:te.z.uuid(),rolloverId:te.z.uuid().nullable(),units:Kr.refine(e=>/[1-9]/.test(e)),amount:tn}),te.z.strictObject({funding:te.z.literal("unbilled"),units:Kr.refine(e=>/[1-9]/.test(e))}),te.z.object({funding:te.z.literal("prepaid"),sourceId:te.z.uuid(),units:Gr,amount:tn,pricing:te.z.array(Bc).min(1).max(12)}).strict().refine(e=>bo(()=>e.pricing.reduce((t,n)=>t+fn(n.units,6),0n)===fn(e.units,6)&&e.pricing.reduce((t,n)=>t+fn(n.amount,12),0n)===fn(e.amount,12)&&e.pricing.every(t=>fn(t.unitCost,6)*fn(t.units,6)===fn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),te.z.object({funding:te.z.literal("postpaid"),invoiceLineId:te.z.uuid().nullable(),units:Gr,authorizationId:te.z.uuid()}).strict()]),Ua=te.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),am=te.z.object({allowed:te.z.boolean(),internal_feature_id:te.z.uuid(),quantity:de,requestedQuantity:de.optional(),overageBehavior:qa.optional(),reason:Ua.nullable(),allocations:te.z.array(om).max(500)}).strict().refine(e=>bo(()=>e.allowed?e.reason===null&&im(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>bo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&fn(e.requestedQuantity,6)>=fn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),So=te.z.object({id:te.z.uuid(),internal_feature_id:te.z.uuid(),kind:te.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:te.z.uuid().nullable(),quantity:de,requestedQuantity:de.optional(),overageBehavior:qa.optional(),accepted:te.z.boolean(),reason:te.z.enum([...Ua.options,"expired"]).nullable(),createdAt:te.z.iso.datetime({offset:!0}),reservationStatus:te.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:te.z.iso.datetime({offset:!0}).nullable(),allocations:te.z.array(om).max(500)}).strict().refine(e=>bo(()=>e.accepted?e.reason===null&&im(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>bo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&fn(e.requestedQuantity,6)>=fn(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");var Ne=require("zod");var Hr=Ne.z.iso.datetime({offset:!0}),sm=de.refine(e=>/[1-9]/.test(e)),cm=Ne.z.strictObject({interval:tm.exclude(["lifetime"]),count:nm}),ax=Ne.z.strictObject({action:Ne.z.literal("create"),requestId:Ne.z.uuid(),internal_feature_id:Ne.z.uuid(),entityId:Ne.z.uuid().nullable(),amount:sm.nullable(),expiresAt:Hr.nullable(),reset:cm.nullable(),rollover:Ma.nullable(),nextResetAt:Hr.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"),um=Ne.z.discriminatedUnion("action",[ax,Ne.z.strictObject({action:Ne.z.literal("update"),requestId:Ne.z.uuid(),grantId:Ne.z.uuid(),revision:Ne.z.number().int().nonnegative(),amount:sm.nullable(),expiresAt:Hr.nullable(),rollover:Ma.nullable(),nextResetAt:Hr.nullable()}),Ne.z.strictObject({action:Ne.z.enum(["add","subtract","set_remaining"]),requestId:Ne.z.uuid(),grantId:Ne.z.uuid(),revision:Ne.z.number().int().nonnegative(),amount:de}),Ne.z.strictObject({action:Ne.z.literal("revoke"),requestId:Ne.z.uuid(),grantId:Ne.z.uuid(),revision:Ne.z.number().int().nonnegative()})]),Vc=Ne.z.strictObject({id:Ne.z.uuid(),internal_feature_id:Ne.z.uuid(),entityId:Ne.z.uuid().nullable(),amount:de.nullable(),reset:cm.nullable(),rollover:Ma.nullable(),nextResetAt:Hr.nullable(),startsAt:Hr,expiresAt:Hr.nullable(),revision:Ne.z.number().int().nonnegative(),revoked:Ne.z.boolean(),available:tn,held:tn,spent:tn}),lm=Ne.z.strictObject({customerId:Ne.z.uuid(),after:Ne.z.uuid().nullable(),limit:Ne.z.number().int().min(1).max(100)}),dm=Ne.z.strictObject({rows:Ne.z.array(Vc).max(100),nextCursor:Ne.z.uuid().nullable()});var ie=require("zod");var Bn=ie.z.iso.datetime({offset:!0}),pm=ie.z.strictObject({invoiceId:ie.z.uuid(),after:ie.z.string().min(1).max(180).nullable(),limit:ie.z.number().int().min(1).max(100)}),sx=ie.z.strictObject({kind:ie.z.literal("product"),key:ie.z.string(),productVersionId:ie.z.uuid(),productName:ie.z.string(),itemKey:ie.z.string(),entityId:ie.z.uuid().nullable(),quantity:ie.z.number().positive(),subtotalMinor:ie.z.string().regex(/^-?\d+$/),discountMinor:ie.z.string().regex(/^\d+$/),taxMinor:ie.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.z.string().regex(/^-?\d+$/),startsAt:Bn.nullable(),endsAt:Bn.nullable(),providerLineId:ie.z.string().nullable(),providerItemId:ie.z.string()}),mm=ie.z.strictObject({invoice:yo,items:ie.z.array(ie.z.discriminatedUnion("kind",[sx,ie.z.strictObject({kind:ie.z.literal("invoice_credit"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),units:de,reserved:de,amountMinor:vi,grossAmountMinor:vi,creditsAppliedMinor:vi,properties:_t,cashPrice:go,providerItemId:ie.z.string().nullable(),creditProviderItemId:ie.z.string().nullable()}),ie.z.strictObject({kind:ie.z.literal("usage"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),name:ie.z.string(),units:de,reserved:de,amountMinor:vi,cashPrice:go})])).max(100),nextCursor:ie.z.string().min(1).max(180).nullable()}),cx=ie.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Lc=ie.z.strictObject({from:Bn,to:Bn,entityId:ie.z.uuid().optional(),snapshotAt:Bn.nullable(),after:ie.z.strictObject({at:Bn,id:ie.z.uuid(),position:ie.z.number().int().nonnegative()}).nullable(),limit:ie.z.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"),fm=ie.z.strictObject({customerId:ie.z.uuid(),entityId:ie.z.uuid().nullable(),from:Bn,to:Bn,snapshotAt:Bn,totals:ie.z.array(ie.z.strictObject({internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),consumed:tn,refunded:tn,net:cx})).max(1e3),rows:ie.z.array(ie.z.strictObject({operationId:ie.z.uuid(),position:ie.z.number().int().nonnegative(),kind:ie.z.enum(["consume","confirm","refund"]),originalId:ie.z.uuid().nullable(),occurredAt:Bn,internal_feature_id:ie.z.uuid(),entitlementName:ie.z.string(),sourceId:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),creditName:ie.z.string(),units:Kr,amount:tn,pricing:ie.z.array(Bc).max(12),properties:_t})).max(100),nextCursor:Lc.shape.after});var D=require("zod");var Sn=require("zod");var ux=Sn.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),lx=Sn.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Ba=Sn.z.strictObject({internal_feature_id:Sn.z.uuid(),entityId:Sn.z.uuid().nullable()}),hm=Ba.extend({quantity:de,expectedRevision:Sn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:Sn.z.string().min(1).max(120),properties:_t.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Io=Ba.extend({operationId:Sn.z.uuid().nullable(),usage:de,capacity:ux.nullable(),remaining:lx.nullable(),withinLimit:Sn.z.boolean(),revision:Sn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Sn.z.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 Wt=D.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Rn=D.z.iso.datetime({offset:!0}),dx=D.z.enum(["access","metered","credit"]),vo={internal_feature_id:D.z.uuid(),key:qr,name:D.z.string().min(1).max(120),kind:dx},gm=D.z.object({customerId:D.z.uuid(),snapshotAt:Rn,memberships:D.z.array(D.z.object({id:D.z.uuid(),productId:D.z.string().min(1).max(255),productVersionId:D.z.uuid(),billingProductVersionId:D.z.uuid(),version:D.z.number().int().positive(),key:D.z.string().min(1).max(64),name:D.z.string().min(1).max(120),groupId:D.z.string().max(255).nullable(),membershipType:D.z.enum(["main","addon"]),status:D.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.z.boolean(),accessEnabled:D.z.boolean(),renewalChange:D.z.object({productVersionId:D.z.uuid(),name:D.z.string().min(1).max(120),version:D.z.number().int().positive(),effectiveAt:Rn,benefitsAppliedAt:Rn.nullable(),timing:D.z.enum(["immediate","renewal"]),changeKind:D.z.enum(["plan","seats","quantity"]),feature:D.z.strictObject({internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(80),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).optional(),seat:D.z.object({key:D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).strict().nullable(),status:D.z.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.z.object({phase:D.z.enum(["paid","trial"]),startsAt:Rn,endsAt:Rn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.z.boolean(),balances:D.z.array(D.z.object({...vo,usageType:D.z.enum(["consumable","non_consumable"]).nullable(),accessible:D.z.boolean(),unlimited:D.z.boolean(),available:Wt,held:Wt,debt:Wt,nextExpiresAt:Rn.nullable(),usage:Io.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.z.boolean()}).strict(),ym=D.z.enum(["source","usage","transaction","invoice","debt","settlement"]),Va=D.z.object({at:Rn,id:D.z.uuid(),type:ym}).strict(),Am=D.z.object({type:ym.nullable(),resourceKey:qr.optional(),kind:D.z.enum(["purchase","refund"]).optional(),topup:D.z.boolean().optional(),from:D.z.iso.date().nullable(),to:D.z.iso.date().nullable(),after:Va.nullable(),limit:D.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Oi={id:D.z.uuid(),occurredAt:Rn},px=D.z.discriminatedUnion("type",[D.z.strictObject({...Oi,type:D.z.literal("invoice"),status:D.z.string().min(1).max(80),paid:Wt,refunded:Wt,currency:Ie,externalId:D.z.string().nullable()}),D.z.object({...Oi,...vo,type:D.z.literal("source"),reason:D.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Wt,unlimited:D.z.boolean(),status:D.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Rn,expiresAt:Rn.nullable(),orderId:D.z.uuid().nullable(),parentSourceId:D.z.uuid().nullable()}).strict(),D.z.object({...Oi,type:D.z.literal("usage"),internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(120),kind:D.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.z.uuid().nullable(),quantity:de,accepted:D.z.boolean(),reason:D.z.enum([...Ua.options,"expired"]).nullable(),properties:_t,reservationStatus:D.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Rn.nullable(),charges:D.z.array(D.z.discriminatedUnion("funding",[D.z.strictObject({funding:D.z.literal("balance"),sourceId:D.z.uuid(),rolloverId:D.z.uuid().nullable(),units:Kr,amount:Wt}),D.z.strictObject({funding:D.z.literal("unbilled"),units:Kr}),D.z.object({...vo,funding:D.z.literal("prepaid"),amount:Wt}).strict(),D.z.object({funding:D.z.literal("postpaid"),invoiceId:D.z.uuid(),invoiceLineId:D.z.uuid(),authorizationId:D.z.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.z.object({...Oi,type:D.z.literal("transaction"),purpose:D.z.enum(["product","invoice"]),productVersionId:D.z.uuid().nullable(),productName:D.z.string().min(1).max(120).nullable(),productVersion:D.z.number().int().positive().nullable(),invoiceId:D.z.uuid().nullable(),orderId:D.z.uuid(),originalId:D.z.uuid().nullable(),kind:D.z.enum(["purchase","refund"]),amountMinor:D.z.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.z.object({...Oi,...vo,type:D.z.literal("debt"),sourceId:D.z.uuid(),transactionId:D.z.uuid(),amount:Wt}).strict(),D.z.object({...Oi,...vo,type:D.z.literal("settlement"),sourceId:D.z.uuid(),debtId:D.z.uuid(),kind:D.z.enum(["payment","usage_refund","payment_return"]),amount:Wt}).strict()]),bm=D.z.object({customerId:D.z.uuid(),rows:D.z.array(px).max(50),nextCursor:Va.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");var he=require("zod"),Sm=he.z.object({customerId:he.z.uuid()}).strict(),Im=he.z.discriminatedUnion("action",[he.z.object({customerId:he.z.uuid(),requestId:he.z.uuid(),action:he.z.literal("assign"),poolId:he.z.uuid(),memberCustomerId:he.z.uuid()}).strict(),he.z.strictObject({customerId:he.z.uuid(),requestId:he.z.uuid(),action:he.z.literal("assign_entity"),poolId:he.z.uuid(),entityId:he.z.uuid()}),he.z.object({customerId:he.z.uuid(),requestId:he.z.uuid(),action:he.z.literal("release"),poolId:he.z.uuid(),slotId:he.z.uuid()}).strict()]),wo=he.z.number().int().nonnegative(),zc=he.z.iso.datetime({offset:!0}),$c=he.z.strictObject({internalId:he.z.uuid(),id:he.z.string(),name:he.z.string().nullable(),version:he.z.number().int().positive()}),xm=he.z.enum(["active","past_due"]),Gc=he.z.strictObject({customerId:he.z.uuid(),licenses:he.z.array(he.z.strictObject({id:he.z.uuid(),linkId:he.z.uuid(),parent:he.z.strictObject({customerProductId:he.z.uuid(),status:xm,product:$c}),product:$c,planLicense:he.z.strictObject({id:he.z.uuid(),prepaidOnly:he.z.boolean(),isCustom:he.z.boolean()}).nullable(),granted:wo,included:wo,paidQuantity:wo,usage:wo,remaining:wo,createdAt:zc}).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.z.array(he.z.strictObject({id:he.z.uuid(),linkId:he.z.uuid(),status:xm,product:$c,entity:he.z.strictObject({internalId:he.z.uuid(),id:he.z.string().nullable(),name:he.z.string().nullable()}).nullable(),beneficiary:he.z.strictObject({internalId:he.z.uuid(),id:he.z.string().nullable(),name:he.z.string().nullable()}).nullable(),startedAt:zc.nullable(),endedAt:zc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:he.z.boolean()});var pe=require("zod"),Oo=pe.z.enum(["email","sms","voice","push"]),EC=pe.z.enum(["resend","twilio","fcm","apns"]);var RC=pe.z.string().regex(/^\+[1-9]\d{1,14}$/),mx=pe.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var fx=pe.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),hx=pe.z.strictObject({subject:fx,html:pe.z.string().min(1).max(131072).optional(),text:pe.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),gx=pe.z.strictObject({body:pe.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),yx=pe.z.strictObject({text:pe.z.string().trim().min(1).max(4e3),language:pe.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:pe.z.number().int().min(1).max(900)}),Ax=pe.z.record(pe.z.string().min(1).max(64),pe.z.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"),bx=pe.z.strictObject({title:pe.z.string().trim().min(1).max(200),body:pe.z.string().trim().min(1).max(2e3),url:pe.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:Ax.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),vm=pe.z.discriminatedUnion("channel",[pe.z.strictObject({channel:pe.z.literal("email"),content:hx}),pe.z.strictObject({channel:pe.z.literal("sms"),content:gx}),pe.z.strictObject({channel:pe.z.literal("voice"),content:yx}),pe.z.strictObject({channel:pe.z.literal("push"),content:bx})]),wm=pe.z.strictObject({requestId:pe.z.uuid(),customerId:pe.z.uuid(),connectionId:pe.z.uuid().optional(),message:vm,expiresAt:pe.z.iso.datetime({offset:!0})}),xx=pe.z.array(pe.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Sx=pe.z.discriminatedUnion("kind",[pe.z.strictObject({kind:pe.z.literal("all")}),pe.z.strictObject({kind:pe.z.literal("customers"),customerIds:xx})]),kC=pe.z.strictObject({name:pe.z.string().trim().min(1).max(120),connectionId:pe.z.uuid().optional(),message:vm,audience:Sx,frequencyLimit:pe.z.number().int().min(1).max(100)}),Om=pe.z.strictObject({requestId:pe.z.uuid(),channel:Oo,state:pe.z.enum(["allowed","denied"]),expectedRevision:pe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Pm=pe.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Cm=pe.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),jC=pe.z.strictObject({meter:mx,estimatedUnits:pe.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:pe.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Oe=require("zod");var re=require("zod");var Qr=require("zod");var Po=Qr.z.strictObject({internalFeatureId:Qr.z.uuid(),name:Qr.z.string().min(1).max(120),includedAmount:Qr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Qr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:Qr.z.number().int().min(1).max(100),terms:Ca});var za=re.z.object({plan:re.z.string().min(1).max(200).optional(),coupon:re.z.uuid().optional(),promotionCode:re.z.uuid().optional(),picker:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),La=re.z.object({text:re.z.string().optional(),label:re.z.string().optional(),alt:re.z.string().optional(),html:re.z.string().max(32768).optional(),price:re.z.object({current:re.z.string(),original:re.z.string().nullable(),period:re.z.string()}).optional(),code:re.z.string().optional(),countdownAt:re.z.iso.datetime().optional(),planId:re.z.string().min(1).max(200).optional(),planVersionId:re.z.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.z.uuid().optional(),offerId:re.z.uuid().optional(),unavailable:re.z.boolean().optional(),unavailableReason:re.z.string().optional(),missing:re.z.array(re.z.string()).optional()}).strict(),Pi=re.z.object({paywall:ur.optional(),nodes:re.z.record(re.z.string(),re.z.object({base:La,picker:re.z.string().optional(),byPlan:re.z.record(re.z.string(),La).optional()}).strict()),plans:re.z.record(re.z.string(),re.z.object({id:re.z.string().min(1).max(200),versionId:re.z.string().min(1).max(200),available:re.z.boolean(),name:re.z.string(),price:re.z.string(),period:re.z.string(),currency:Ie.optional(),amountMinor:re.z.number().int().nonnegative().optional(),interval:re.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.z.number().int().positive().optional(),prepaid:re.z.array(Po).max(100).optional()}).strict()),pickers:re.z.record(re.z.string(),re.z.object({options:re.z.array(re.z.string().min(1).max(200)).max(20),selected:re.z.string().min(1).max(200).nullable()}).strict()),quantities:re.z.record(re.z.string(),re.z.strictObject({minimum:re.z.number().int().nonnegative(),maximum:re.z.number().int().nonnegative(),step:re.z.number().int().positive(),value:re.z.number().int().nonnegative(),label:re.z.string(),available:re.z.boolean()})).optional(),diagnostics:re.z.array(re.z.object({nodeId:re.z.string(),message:re.z.string()}).strict())}).strict();function _m(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var I=require("zod");function Ix(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Em(e){let t={};function n(r){var i;if(Ix(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}var Vn=require("zod"),Rm=Vn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),$a=Vn.z.strictObject({tiers:Vn.z.array(Vn.z.strictObject({id:Rm,name:Vn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Vn.z.array(Vn.z.strictObject({productVersionId:Vn.z.string().min(1).max(200),tierId:Rm,period:Vn.z.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 Ga(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var ce=require("zod");var vx=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],km=ce.z.enum(vx),jm=ce.z.object({source:km,layout:ce.z.enum(["full","compact"]),resourceKey:qr.optional(),pageSize:ce.z.number().int().min(1).max(50),showSources:ce.z.boolean(),allowPurchase:ce.z.boolean(),outputs:ce.z.object({billing_adjustment:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.z.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"})}),Dt=ce.z.string().max(2e3),Tm=ce.z.object({id:ce.z.string().max(100),label:Dt,detail:ce.z.array(Dt).max(12),value:Dt.optional(),status:Dt.optional(),facts:ce.z.array(ce.z.object({label:Dt,value:Dt}).strict()).max(1e3),purchaseId:ce.z.uuid().optional(),invoiceUrl:ce.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.z.array(ce.z.strictObject({action:ce.z.literal("invoice_open"),label:Dt})).max(1).optional(),membershipActions:ce.z.array(ce.z.object({value:ce.z.string().max(100),label:Dt}).strict()).max(3).optional()}).strict(),wx=ce.z.object({key:qr,name:Dt,spendable:Dt,reserved:Dt,available:Dt,expiry:Dt.nullable(),sources:ce.z.array(Tm).max(50),sourceCount:ce.z.number().int().nonnegative(),sourcePage:ce.z.number().int().positive(),hasNextSources:ce.z.boolean(),hasPreviousSources:ce.z.boolean()}).strict(),Ox=ce.z.object({source:km,status:ce.z.enum(["idle","loading","ready","error"]),stale:ce.z.boolean(),preview:ce.z.boolean(),errorCode:ce.z.string().max(80).optional(),errorMessage:Dt.optional(),resources:ce.z.array(wx).max(500),rows:ce.z.array(Tm).max(50),hasNext:ce.z.boolean(),hasPrevious:ce.z.boolean(),page:ce.z.number().int().positive(),filter:ce.z.string().max(40),updatedAt:ce.z.iso.datetime().optional(),buyingId:ce.z.uuid().optional(),membershipBusy:ce.z.boolean().optional(),billingBusy:ce.z.boolean().optional(),membershipReview:ce.z.object({title:Dt,note:Dt,facts:ce.z.array(ce.z.object({label:Dt,value:Dt}).strict()).max(100)}).strict().optional(),membershipResult:Dt.optional()}).strict(),Nm=ce.z.object({nodes:ce.z.record(ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ox)}).strict(),zC=ce.z.object({nodeId:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.z.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.z.string().max(100).optional()}).strict();var K=require("zod"),vt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Fm=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Vt=K.z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Fm.has(e),"Reserved UI identifier"),Kc=K.z.union([K.z.string().max(2e3),K.z.number().finite(),K.z.boolean(),K.z.null()]),Px=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("enum"),values:K.z.array(Kc).min(1).max(vt.enumValues),default:Kc}),K.z.strictObject({type:K.z.literal("number"),min:K.z.number().finite(),max:K.z.number().finite(),step:K.z.number().finite().positive(),default:K.z.number().finite()}),K.z.strictObject({type:K.z.literal("text"),maxLength:K.z.number().int().min(0).max(2e3),default:K.z.string().max(2e3).nullable()}),K.z.strictObject({type:K.z.literal("boolean"),default:K.z.boolean()})]);function Qc(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 Cx=Px.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"}),Qc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),_x=["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 Ex(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 Zr=K.z.lazy(()=>K.z.union([Kc,K.z.strictObject({ref:Vt}),K.z.strictObject({op:K.z.enum(_x),args:K.z.array(Zr).max(vt.expressionNodes)}).superRefine((e,t)=>{Ex(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function kn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Jr(e,t,n){if(!e||typeof e!="object")return!0;if(!kn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Fm.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 Ci(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(!Jr(a.value,t,a.path))return;if(kn(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 GC=K.z.unknown().superRefine((e,t)=>{Ci(e,t,[],{nodes:0})}).pipe(Zr),Hc=K.z.record(Vt,Zr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=vt.state,"UI assignments need 1\u201332 state keys"),Rx=K.z.strictObject({target:Vt,property:K.z.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Zr,className:Vt.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"})}),kx=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("scroll_latch"),target:Vt,state:Vt}),K.z.strictObject({type:K.z.literal("input"),target:Vt,state:Vt,set:Hc.optional()}),K.z.strictObject({type:K.z.literal("action"),target:Vt,set:Hc}),K.z.strictObject({type:K.z.literal("carousel"),target:Vt,state:Vt,initialIndex:K.z.number().int().nonnegative().optional(),maxWidth:K.z.number().int().min(1).max(1e4).optional(),previousTarget:Vt.optional(),nextTarget:Vt.optional(),inactiveTargets:K.z.array(Vt).max(20).optional(),inactiveMaxWidth:K.z.number().int().min(1).max(1e4).optional()})]),jx=K.z.strictObject({afterMs:K.z.number().int().min(0).max(6e4),set:Hc}),Tx=K.z.strictObject({type:K.z.literal("mosaic_waves"),target:Vt,color:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Zr.optional(),speed:K.z.number().min(0).max(4).optional(),pitch:K.z.number().min(.05).max(4).optional(),fill:K.z.number().min(.05).max(1).optional(),feather:K.z.number().min(0).max(1).optional(),warp:K.z.number().min(0).max(4).optional(),warpScale:K.z.number().min(0).max(32).optional(),detailScale:K.z.number().min(0).max(32).optional(),waveScale:K.z.number().min(0).max(32).optional(),falloff:K.z.number().min(.1).max(32).optional(),brightness:K.z.number().min(0).max(32).optional(),ambient:K.z.number().min(0).max(1).optional(),gamma:K.z.number().min(.05).max(8).optional(),vignette:K.z.number().min(0).max(1).optional(),opacity:K.z.number().min(0).max(1).optional()}),Nx=K.z.strictObject({type:K.z.literal("number_counter"),target:Vt,value:Zr,prefix:K.z.string().max(20).optional(),format:K.z.enum(["number","short"]).optional()}),Dx=K.z.strictObject({state:K.z.record(Vt,Cx).refine(e=>Object.keys(e).length<=vt.state,"Too many UI state keys").optional(),derived:K.z.record(Vt,Zr).refine(e=>Object.keys(e).length<=vt.derived,"Too many UI derived keys").optional(),bindings:K.z.array(Rx).max(vt.bindings).optional(),controls:K.z.array(kx).max(vt.controls).optional(),timers:K.z.array(jx).max(vt.timers).optional(),effects:K.z.array(K.z.discriminatedUnion("type",[Tx,Nx])).max(vt.effects).optional(),clock:K.z.boolean().optional()});function Fx(e,t){if(!Jr(e,t,[])||!kn(e))return;for(let[r,i]of[["state",vt.state],["derived",vt.derived]]){let a=e[r];if(!Jr(a,t,[r]))return;if(kn(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(!Jr(i,t,["effects",r]))return}if(kn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Jr(i,t,["state",r]))return;if(kn(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(kn(e.derived))for(let[r,i]of Object.entries(e.derived))Ci(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(!(!Jr(o,t,[r,a])||!kn(o))){if(r==="bindings")Ci(o.expression,t,[r,a,"expression"],n);else if(Jr(o.set,t,[r,a,"set"])&&kn(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))Ci(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())kn(i)&&i.type==="number_counter"?Ci(i.value,t,["effects",r,"value"],n):kn(i)&&i.enabled!==void 0&&Ci(i.enabled,t,["effects",r,"enabled"],n)}function Dm(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 Mm=K.z.unknown().superRefine(Fx).pipe(Dx).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 Dm(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 Dm(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&&!Qc(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"])});var st=require("zod"),Mx=st.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ka=st.z.discriminatedUnion("type",[st.z.object({type:st.z.literal("fixed"),productVersionId:st.z.string().min(1).max(200)}).strict(),st.z.object({type:st.z.literal("picker"),pickerId:Mx,allowedProductVersionIds:st.z.array(st.z.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")]),qx=st.z.strictObject({min:st.z.number().finite().min(1).max(1800),max:st.z.number().finite().min(1).max(1800),viewport:st.z.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),qm={desktopWidth:qx.optional(),mobile:st.z.enum(["sheet","fullscreen"]).optional(),backdrop:st.z.enum(["none","scrim","dim","strong-dim","blur"]).optional()},jn=st.z.discriminatedUnion("type",[st.z.strictObject({type:st.z.literal("modal"),size:st.z.enum(["sm","md","lg"]),...qm}),st.z.strictObject({type:st.z.literal("sheet"),size:st.z.enum(["sm","md","lg"]),...qm}),st.z.strictObject({type:st.z.literal("fullscreen")}),st.z.strictObject({type:st.z.literal("inline")})]);var Bx=4,Nn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},_o=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ve=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vx=I.z.enum(["none","xs","sm","md","lg","xl"]),Lx=I.z.enum(["none","sm","md","lg","full"]),Jc=I.z.string().regex(/^#[0-9a-fA-F]{6}$/),Wc=I.z.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"),Zc=I.z.union([Wc,I.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Um=I.z.object({primary:Jc,background:Jc,text:Jc,radius:Lx,font:I.z.enum(["system","serif","rounded","mono"]),fontAssets:I.z.object({family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.z.array(I.z.object({url:Wc,weight:I.z.number().int().min(100).max(900).multipleOf(100),family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),Eo=I.z.union([I.z.enum(["primary","text","muted","background","surface"]),I.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ue=(e,t)=>I.z.number().int().min(e).max(t),Bm=I.z.union([I.z.enum(["fit","fill"]),Ue(1,1200)]),zx=I.z.object({top:Ue(0,200),right:Ue(0,200),bottom:Ue(0,200),left:Ue(0,200)}).strict(),$x=I.z.object({top:Ue(-100,200),right:Ue(-100,200),bottom:Ue(-100,200),left:Ue(-100,200)}).strict(),Vm=I.z.object({x:Ue(0,100),y:Ue(0,100)}).strict(),Gx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("color"),color:Eo}).strict(),I.z.object({type:I.z.literal("linear"),angle:Ue(0,360),stops:I.z.array(I.z.object({color:Eo,at:Ue(0,100)}).strict()).min(2).max(4)}).strict(),I.z.object({type:I.z.literal("image"),src:Zc,fit:I.z.enum(["cover","contain"]),position:Vm.optional()}).strict()]),Kx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("rect"),radius:I.z.union([Ue(0,200),I.z.object({topLeft:Ue(0,200),topRight:Ue(0,200),bottomRight:Ue(0,200),bottomLeft:Ue(0,200)}).strict()])}).strict(),I.z.object({type:I.z.literal("pill")}).strict()]),Hx=I.z.object({width:Ue(0,12),color:Eo,style:I.z.enum(["solid","dashed"])}).strict(),Qx=I.z.object({x:Ue(-40,40),y:Ue(-40,40),blur:Ue(0,80),spread:Ue(-20,40),color:Eo}).strict(),Jx=I.z.object({font:I.z.enum(["system","serif","rounded","mono"]),size:Ue(8,96),weight:I.z.number().int().min(100).max(900).multipleOf(100),lineHeight:I.z.number().min(.8).max(3),letterSpacing:I.z.number().min(-5).max(20),color:Eo,align:I.z.enum(["start","center","end"]),italic:I.z.boolean(),decoration:I.z.enum(["none","underline","line-through"]),transform:I.z.enum(["none","uppercase"])}).strict().partial(),Wr=I.z.object({width:Bm,height:Bm,padding:zx,margin:$x,gap:Ue(0,120),grow:I.z.union([I.z.boolean(),I.z.number().min(0).max(12)]),background:Gx,opacity:I.z.number().min(0).max(1),clipContent:I.z.boolean(),shape:Kx,border:Hx,shadow:Qx,text:Jx}).strict().partial(),an={id:_o,name:I.z.string().trim().min(1).max(60).optional(),hidden:I.z.boolean().optional(),style:Wr.optional(),fallback:Ve.optional()},Zx=I.z.object({...an,type:I.z.literal("text"),productField:I.z.enum(["name","price","trial","period"]).optional(),feature:I.z.object({id:I.z.uuid(),field:I.z.enum(["name","allowance"])}).strict().optional(),text:Ve,variant:I.z.enum(["title","heading","body","caption"])}).strict(),Wx=I.z.object({...an,type:I.z.literal("image"),src:Zc,localizedSrc:I.z.record(En,Zc).optional(),alt:Ve,aspect:I.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.z.enum(["cover","contain"]),position:Vm.optional()}).strict(),Yx=I.z.object({...an,type:I.z.literal("button"),label:Ve,variant:I.z.enum(["primary","secondary","link"]),action:Ve,purpose:I.z.enum(["purchase","navigation","close"]).optional(),bind:za.optional()}).strict(),Xx=I.z.object({...an,type:I.z.literal("divider")}).strict(),eS=I.z.object({...an,type:I.z.literal("customer_data"),title:Ve,data:jm}).strict(),tS=I.z.object({...an,type:I.z.literal("spacer"),size:Vx}).strict(),nS=I.z.object({...an,type:I.z.literal("custom_html"),html:I.z.record(En,I.z.string().max(Nn.customHtml)),css:I.z.string().max(Nn.customCss),ui:Mm.optional()}).strict(),rS=I.z.object({...an,type:I.z.literal("price"),fallback:Ve,parts:I.z.object({current:Wr.optional(),original:Wr.optional(),period:Wr.optional()}).strict().optional()}).strict(),iS=I.z.object({...an,type:I.z.literal("coupon_code"),label:Ve,fallback:Ve}).strict(),oS=I.z.object({...an,type:I.z.literal("countdown"),source:I.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.z.iso.datetime().optional(),granularity:I.z.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"),aS=I.z.object({...an,type:I.z.literal("plan_picker"),label:Ve,fallback:Ve,planIds:I.z.array(I.z.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.z.string().min(1).max(200).optional(),grouping:$a.safeExtend({monthLabel:Ve,yearLabel:Ve,unavailableLabel:Ve}).optional(),states:I.z.object({selected:Wr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ga(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),sS=I.z.object({...an,type:I.z.literal("quantity_picker"),bind:za.optional(),label:Ve,fallback:Ve,internalFeatureId:I.z.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"),cS=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("input"),label:Ve,keyboard:I.z.enum(["text","email","tel","url"]),maxLength:Ue(1,500)}).strict(),I.z.object({type:I.z.literal("multiselect"),label:Ve,min:Ue(0,50),max:Ue(1,50)}).strict(),I.z.object({type:I.z.literal("select"),label:Ve,defaultIndex:Ue(0,49),purpose:I.z.enum(["option","product","tier"]).optional(),pickerId:_o.optional(),selectedStyle:Wr.optional()}).strict(),I.z.object({type:I.z.literal("tabs"),label:Ve,defaultIndex:Ue(0,49),purpose:I.z.literal("tier").optional()}).strict(),I.z.object({type:I.z.literal("toggle"),label:Ve,defaultEnabled:I.z.boolean()}).strict(),I.z.object({type:I.z.literal("carousel"),label:Ve}).strict()]),Tn={...an,type:I.z.literal("stack"),direction:I.z.enum(["vertical","horizontal","overlay"]),align:I.z.enum(["start","center","end","stretch"]),justify:I.z.enum(["start","center","end","between"]),productSlot:I.z.object({index:Ue(0,19),period:I.z.enum(["month","year"]).optional(),requireBinding:I.z.boolean().optional()}).strict().optional(),interaction:cS.optional(),states:I.z.object({selected:Wr.optional()}).strict().optional(),purpose:I.z.literal("benefits").optional(),purchaseAction:Ve.optional(),buttonVariant:I.z.enum(["primary","secondary","link"]).optional(),bind:za.optional()},Lm=I.z.lazy(()=>I.z.object({...an,type:Tn.type,direction:Tn.direction,align:Tn.align,justify:Tn.justify,children:I.z.array(uS).max(Nn.children),productSlot:Tn.productSlot,interaction:Tn.interaction,states:Tn.states,purpose:Tn.purpose,purchaseAction:Tn.purchaseAction,buttonVariant:Tn.buttonVariant,bind:Tn.bind}).strict()),uS=I.z.lazy(()=>I.z.union([Lm,Zx,Wx,Yx,Xx,tS,nS,rS,iS,oS,aS,sS,eS])),lS=I.z.union([I.z.string().max(500),I.z.number().finite(),I.z.boolean(),I.z.null()]),Co={id:Ve,event:Ve,properties:I.z.record(Ve,lS).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},dS=I.z.discriminatedUnion("type",[I.z.object({...Co,type:I.z.literal("navigate"),close:I.z.literal(!1),pageId:_o}).strict(),I.z.object({...Co,type:I.z.literal("event"),close:I.z.boolean()}).strict(),I.z.object({...Co,type:I.z.literal("close"),close:I.z.literal(!0)}).strict(),I.z.object({...Co,type:I.z.literal("open_url"),close:I.z.boolean(),url:Wc}).strict(),I.z.object({...Co,type:I.z.literal("claim_offer"),close:I.z.boolean(),couponId:I.z.uuid()}).strict()]),pS=I.z.object({defaultLocale:En,locales:I.z.record(En,I.z.record(Ve,I.z.string().max(Nn.stringLength)))}).strict(),mS=I.z.enum(["popup","paywall","onboarding","page","banner"]);var fS=I.z.object({kind:I.z.literal("screen"),schemaVersion:I.z.literal(Bx),name:I.z.string().trim().min(1).max(80),surface:mS,initialPageId:_o.optional(),presentation:jn,theme:Um,pages:I.z.array(I.z.object({id:_o,name:I.z.string().trim().min(1).max(60),root:Lm,theme:Um.optional(),editorPosition:I.z.object({x:I.z.number().finite().min(-1e5).max(1e5),y:I.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Nn.pages),strings:pS,actions:I.z.array(dS).max(Nn.actions)}).strict();function Yt(e,t){for(let n of e.pages)nr(n.root,t)}var hn=fS.superRefine((e,t)=>{let n=Nn;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>Nn.locales&&r(`\u6700\u591A ${Nn.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;Yt(e,(l,p)=>{if(c++,p>Nn.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 ${Nn.depth} \u5C42`)});function nr(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)nr(i,t,n+1,e)}function Ha(e){let t=[],n=new Set;return Yt(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 hS(e,t,n){if(t.field==="html"){let r;return Yt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Ro(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 fr(e){let t=Ha(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=>!hS(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 gS(e,t){let n=null;return nr(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Ro(e,t){for(let n of e.pages){let r=gS(n.root,t);if(r)return r}return null}var Lt=require("zod"),wt=Lt.z.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"),Yc=Lt.z.strictObject({type:Lt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Lt.z.boolean(),enum:Lt.z.array(Lt.z.string().max(255)).min(1).max(100).optional()}),_i=Yc.extend({type:Lt.z.enum([...Yc.shape.type.options,"array"]),items:Yc.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"})}),Ei=_i.safeExtend({source:Lt.z.discriminatedUnion("type",[Lt.z.strictObject({type:Lt.z.literal("input")}),Lt.z.strictObject({type:Lt.z.literal("node")}),Lt.z.strictObject({type:Lt.z.enum(["parameter","attribute"]),key:wt})])}),r_=Lt.z.record(wt,Ei),Xc=Lt.z.record(wt,wt).refine(e=>Object.keys(e).length<=20);function In(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=>In(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&&Lt.z.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 eu(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&&eu(e.items,t.items)}function Qa(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(!In(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Ri(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 zm(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"||!In(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")}var hr=require("zod");var Dn=hr.z.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"),Ln=hr.z.discriminatedUnion("source",[hr.z.strictObject({source:hr.z.literal("literal"),value:ve}),hr.z.strictObject({source:hr.z.literal("variable"),key:hr.z.string().min(1).max(255),path:Dn.optional()})]);function $m(e,t){if(!t)return e;for(let n of Dn.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 tu(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Qa(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse($m(n[e.key],e.path)))}function nu(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&&!Dn.safeParse(r).success?null:{key:n,path:r}}function ru(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Yt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(_m))]}function Ja(e){return ru(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function gn(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 gr=Oe.z.enum(["page","popup","banner"]),yS=3e5,Gm=Oe.z.strictObject({type:Oe.z.enum(["string","number","boolean","strings","json"]),nullable:Oe.z.boolean()}),AS=Oe.z.strictObject({inputs:Oe.z.record(Ve,Gm.extend({required:Oe.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Oe.z.record(Ve,Gm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),bS=Oe.z.strictObject({kind:gr,schemaVersion:Oe.z.literal(1),name:Oe.z.string().trim().min(1).max(80),screen:hn,contract:AS}),Za=bS.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"]),gn(e)>yS&&n("Content document exceeds its byte budget",[])});function xS(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 SS=Za.superRefine((e,t)=>{for(let n of Ja(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&&!xS(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}fr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Km=Oe.z.strictObject({id:Oe.z.uuid(),kind:gr,projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),name:Oe.z.string(),revision:Oe.z.number().int().nonnegative(),status:Oe.z.enum(["draft","published","archived"]),publishedVersionId:Oe.z.uuid().nullable(),createdAt:Oe.z.iso.datetime({offset:!0}),updatedAt:Oe.z.iso.datetime({offset:!0})}),y_=Km.extend({draft:Za}),A_=Oe.z.strictObject({rows:Oe.z.array(Km).max(200),nextCursor:Oe.z.uuid().nullable()}),iu=Oe.z.strictObject({id:Oe.z.uuid(),kind:gr,resourceId:Oe.z.uuid(),projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),version:Oe.z.number().int().positive(),sourceRevision:Oe.z.number().int().nonnegative(),document:SS,createdAt:Oe.z.iso.datetime({offset:!0})}),b_=iu.omit({document:!0}),x_=Oe.z.discriminatedUnion("action",[Oe.z.strictObject({action:Oe.z.literal("create"),kind:gr,id:Oe.z.uuid(),document:Za}),Oe.z.strictObject({action:Oe.z.literal("save"),kind:gr,id:Oe.z.uuid(),revision:Oe.z.number().int().nonnegative(),document:Za}),Oe.z.strictObject({action:Oe.z.enum(["publish","archive"]),kind:gr,id:Oe.z.uuid(),revision:Oe.z.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"})});var ou=require("zod"),ki={funnelId:ou.z.uuid().optional(),funnelVersionId:ou.z.uuid().optional()};var ko=require("zod"),Wa=ko.z.strictObject({runId:ko.z.uuid(),bindingId:ko.z.uuid(),receiptId:ko.z.uuid()});var ct=require("zod");var Le=require("zod");var nt=require("zod"),w_=nt.z.discriminatedUnion("action",[nt.z.strictObject({action:nt.z.literal("create"),couponId:nt.z.uuid(),productBindingId:nt.z.uuid(),storeOfferId:nt.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:nt.z.enum(["introductory","promotional"])}),nt.z.strictObject({action:nt.z.literal("set_enabled"),id:nt.z.uuid(),revision:nt.z.number().int().nonnegative(),enabled:nt.z.boolean()})]),O_=nt.z.array(nt.z.strictObject({id:nt.z.uuid(),couponId:nt.z.uuid(),productBindingId:nt.z.uuid(),storeOfferId:nt.z.string().min(1).max(255).nullable(),storeOfferType:nt.z.enum(["introductory","promotional"]),enabled:nt.z.boolean(),revision:nt.z.number().int().nonnegative()})).max(500),ji=nt.z.strictObject({offerKind:nt.z.enum(["none","introductory","promotional"]),offerId:nt.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:nt.z.number().int().min(0).max(1e8),trialDays:nt.z.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"})}),P_=nt.z.record(nt.z.uuid(),ji).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var au=Le.z.object({type:Le.z.literal("native_purchase"),receiptId:Le.z.uuid(),orderId:Le.z.uuid(),productVersionId:Le.z.uuid(),provider:Le.z.enum(["apple","google"]),productId:Le.z.string().min(1).max(255),productKind:Ld,replacement:Le.z.strictObject({sourceOrderId:Le.z.uuid(),sourceProductId:Le.z.string().min(1).max(255),policy:Le.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:Le.z.array(Le.z.uuid()).max(50)}).nullable(),appAccountToken:Le.z.uuid().optional(),obfuscatedAccountId:Le.z.string().min(1).max(64).optional(),obfuscatedProfileId:Le.z.uuid().optional(),basePlanId:Le.z.string().min(1).max(255).optional(),offerId:Le.z.string().min(1).max(255).optional(),offerKind:Le.z.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Le.z.number().int().nonnegative().max(1e8),discountMinor:Le.z.number().int().nonnegative().max(1e8),trialDays:Le.z.number().int().min(1).max(730).nullable(),seatBundle:Le.z.array(Le.z.strictObject({key:Le.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Le.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Le.z.strictObject({offerId:Le.z.string().min(1).max(255),keyId:Le.z.string().min(1).max(255),nonce:Le.z.uuid(),signature:Le.z.string().min(1).max(1024),timestamp:Le.z.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"})});var f=require("zod");var _e=require("zod/v4"),Hm=require("zod/v4"),IS=Hm.z.registry(),{BillingInterval:Qm}=(()=>{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:vS}=(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.z),{withSpecDefault:wS}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(IS),{COMMON:Jm}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:OS}={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:PS}=(e=>({COMMON_SET:new Set(e)}))(Jm),{hasNoDuplicateCurrencies:Zm}={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:Wm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:CS}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e.z),{Infinite:_S}={Infinite:"inf"},{TierBehavior:ES}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Ym}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:RS}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:kS}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jS}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:TS}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e.z),{ApiCreditTierSchema:Xm}=(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.z),{VIOLATION_MESSAGES:NS}={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:ef}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e.z),{ModelMarkupsSchema:DS}=((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.z,ef),{InvoiceUsageEntrySchema:FS}=(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.z),{AttachDiscountSchema:tf}=(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.z),{CustomLineItemSchema:MS}=(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.z),{UnixMsTimestampSchema:qS}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e.z),{CreateInvoicePreviewLineSchema:US}=(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.z),{ReissueInvoiceParamsSchema:nf}=(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.z),{InvoiceModeParamsSchema:Yr}=(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.z),{InvoiceTemplateSchema:BS}=(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.z),{BasePriceSchema:VS}=((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.z,Qm,vS),{CURRENCY_CODES:LS}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Jm,OS,PS),{ApiPriceProcessorsSchema:rf}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e.z,CS),{AllocatedBillingFieldSchema:zS}=((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.z,RS),{CreditDimensionNameSchema:$S}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e.z,kS,jS),{ApiCreditMatchSchema:of}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(TS),{findCreditTierViolations:GS}=(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}}))(NS),{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.z,of),{ProviderMarkupsSchema:HS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e.z,ef),{InvoiceFeatureQuantitySchema:af}=((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.z,Ym,FS),{CreateInvoicePreviewSchema:su}=((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.z,US),{SUPPORTED_SET:QS}=(e=>({SUPPORTED_SET:new Set(e)}))(LS),{ApiCreditDimensionBaseSchema:JS}=((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.z,of),{refineGraduatedTiers:sf}=(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"]})}}))(GS),{ApiFeatureMarkupsOverrideSchema:ZS}=((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.z,HS,DS),{isValidCurrencyCode:WS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(QS),{ApiCreditDimensionSchema:YS}=((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.z,JS,Xm,sf),{CurrencyCodeSchema:cf}=((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.z,WS),{AdditionalCurrencyTierSchema:XS}=((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.z,cf),{ApiCreditSchemaItemBaseSchema:uf}=((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.z,$S,YS,KS),{ApiFlatCreditSchemaItemSchema:e0}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(uf,_e.z),{AdditionalCurrencyPriceSchema:t0}=((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.z,cf),{AdditionalCurrencyTierArraySchema:n0}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,XS,Zm,Wm),{ApiGraduatedCreditSchemaItemSchema:r0}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(uf,_e.z,Xm,sf),{AdditionalCurrencyPriceArraySchema:lf}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,t0,Zm,Wm),{ApiUsageTierWithCurrenciesSchema:i0}=((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.z,_S,n0),{ApiCreditSchemaItemSchema:o0}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e.z,r0,e0),{BasePriceParamsSchema:a0}=((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."})}))(VS,wS,_e.z,lf),{PlanItemPriceParamsSchema:s0}=((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.z,lf,i0,ES,Qm,Ym,zS),{ApiFeatureOverrideSchema:c0}=((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.z,o0,ZS),{InvoiceBasePriceParamsSchema:df}=((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()}))(a0,rf),{InvoiceItemPriceParamsSchema:u0}=((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()}))(s0,rf),{InvoiceLicenseQuantitySchema:l0}=((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.z,df,af),{InvoiceCustomizeItemSchema:d0}=((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.z,u0,c0),{InvoiceCustomizeSchema:p0}=((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.z,df,d0),{InvoicePlanParamsSchema:m0}=((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.z,p0,af,l0,tf),{CreateInvoiceParamsSchema:Ti}=((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.z,m0,MS,tf,qS);var ff=f.z.strictObject({requestId:f.z.uuid(),predecessorOperationId:f.z.uuid().optional(),invoiceMode:Yr.optional(),entityId:f.z.uuid().optional(),billingSubscriptionId:f.z.uuid().optional(),newBillingSubscription:f.z.literal(!0).optional(),offerId:f.z.uuid().optional(),nativeOffer:ji.optional(),plans:f.z.array(f.z.strictObject({productVersionId:f.z.uuid(),seatQuantities:f.z.record(Ia,f.z.number().int().min(0).max(1e4)).optional(),featureQuantities:f.z.record(f.z.uuid(),f.z.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.z.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"),ei=f.z.strictObject({operationId:f.z.uuid()}),zt=f.z.number().int().min(0).max(1e8),f0=f.z.strictObject({lineId:f.z.uuid(),productVersionId:f.z.uuid(),productName:f.z.string().min(1).max(80),interval:f.z.enum(["free","week","month","year","one_time"]),intervalCount:f.z.number().int().min(1).max(156).optional(),baseAmountMinor:zt,seats:f.z.array(f.z.strictObject({key:Ia,quantity:f.z.number().int().min(0).max(1e4),includedQuantity:f.z.number().int().min(0).max(1e4),maximumQuantity:f.z.number().int().min(0).max(1e4),unitAmountMinor:zt})).max(20),prepaid:f.z.array(rm).max(100).optional(),catalogAmountMinor:zt,trial:ro.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+Pa({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"),hf=f.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),h0=f.z.strictObject({id:hf,name:f.z.string().min(1).max(40),percent_off:f.z.number().gt(0).max(100).optional(),amount_off:f.z.number().int().positive().optional(),currency:f.z.string().regex(/^[a-z]{3}$/).optional(),duration:f.z.enum(["once","repeating","forever"]),duration_in_months:f.z.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"),g0=f.z.strictObject({subscriptionId:f.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.z.array(f.z.strictObject({id:f.z.string(),price_id:f.z.string(),quantity:f.z.number().int().nonnegative(),discounts:f.z.array(f.z.strictObject({id:f.z.string(),coupon:f.z.string(),start:f.z.number(),end:f.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.z.number().int().nonnegative(),amountMinor:f.z.number().int().positive(),periodStartMs:f.z.number(),periodEndMs:f.z.number()}),gf=f.z.strictObject({invoiceMode:Yr.optional(),append:g0.optional(),provider:f.z.literal("stripe"),executor:f.z.enum(["indiana","merchant"]),accountId:f.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.z.enum(["payment","subscription"]),lineItems:f.z.array(f.z.strictObject({price:f.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.z.number().int().min(1).max(1e4),priceId:f.z.uuid(),productName:f.z.string().min(1).max(80),amountMinor:f.z.number().int().min(0).max(1e8),currency:f.z.string().regex(/^[a-z]{3}$/),interval:f.z.enum(["week","month","year","one_off"]),intervalCount:f.z.number().int().min(1).max(52),slot:f.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.z.strictObject({mode:f.z.enum(["graduated","volume"]),tiers:f.z.array(f.z.strictObject({upTo:f.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.z.number().int().min(0).max(1e8),flatAmountMinor:f.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.z.array(f.z.strictObject({coupon:hf,terms:h0})).max(1),trialPeriodDays:f.z.number().int().min(1).max(730).nullable(),metadata:f.z.strictObject({grooveCheckoutId:f.z.uuid(),grooveCustomerId:f.z.uuid()}),expiresAt:f.z.iso.datetime({offset:!0})}),Ni=f.z.strictObject({operationId:f.z.uuid(),merchantTerms:xi.optional(),entityId:f.z.uuid().nullable(),billingSubscriptionId:f.z.uuid().nullable(),discount:f.z.strictObject({offerId:f.z.uuid(),couponId:f.z.uuid(),discount:mr,duration:mn,amountMinor:zt,allocations:f.z.array(f.z.strictObject({productVersionId:f.z.uuid(),amountMinor:zt})).min(1).max(20),expiresAt:f.z.iso.datetime({offset:!0})}).nullable(),charge:f.z.strictObject({effectiveAt:f.z.iso.datetime({offset:!0}),periodEndsAt:f.z.iso.datetime({offset:!0}),debitMinor:zt,discountMinor:zt,taxMinor:zt,totalMinor:zt}).nullable(),expiresAt:f.z.iso.datetime({offset:!0}),provider:f.z.enum(["stripe","apple","google","merchant"]),nativeOffer:ji.optional(),currency:Ie,lines:f.z.array(f0).min(1).max(20),catalogAmountMinor:zt,automaticTax:f.z.boolean(),execution:f.z.union([gf,la]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&ba(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"),Di=f.z.strictObject({operationId:f.z.uuid(),orderId:f.z.uuid(),append:f.z.boolean().optional(),invoiceMode:f.z.boolean().optional(),status:f.z.enum(["pending","complete","cancelled","failed"]),executor:f.z.enum(["indiana","merchant"]),checkoutUrl:f.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:f.z.union([gf,la]).nullable(),currency:Ie,catalogAmountMinor:zt,taxMinor:zt,totalMinor:f.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.z.boolean(),nativePurchase:au.nullable(),confirmedAt:f.z.iso.datetime({offset:!0}).nullable().optional(),quote:Ni.optional(),merchantExecution:Fr.nullable().optional(),problem:to.nullable().optional(),authority:Sa.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"),Xa=f.z.strictObject({enabled:f.z.literal(!0),featureIds:f.z.array(f.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),yf=f.z.strictObject({requestId:f.z.uuid(),invoiceMode:Yr.optional(),membershipId:f.z.uuid(),carryOverBalances:Xa.optional(),carryOverUsages:Xa.optional(),membershipIds:f.z.array(f.z.uuid()).min(1).max(20).optional(),prorationBehavior:f.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.z.enum(["immediate","renewal","store"]),change:f.z.discriminatedUnion("type",[f.z.strictObject({type:f.z.literal("plan"),productVersionId:f.z.uuid()}),f.z.strictObject({type:f.z.literal("seats"),licenseKey:Ia,quantity:f.z.number().int().min(0).max(1e4)}),f.z.strictObject({type:f.z.literal("quantity"),internal_feature_id:f.z.uuid(),quantity:f.z.number().int().min(0).max(1e4)}),f.z.strictObject({type:f.z.literal("cancel")}),f.z.strictObject({type:f.z.literal("uncancel")}),f.z.strictObject({type:f.z.literal("billing_cycle"),billingCycleAnchor:f.z.union([f.z.literal("now"),f.z.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"),Ya=f.z.string().regex(/^price_[A-Za-z0-9]+$/),pf=f.z.strictObject({grooveUpdateId:f.z.uuid(),grooveCustomerId:f.z.uuid()}),mf=f.z.strictObject({price:Ya.nullable(),priceId:f.z.uuid().optional(),quantity:f.z.number().int().min(0).max(1e4)}),Af=f.z.strictObject({provider:f.z.literal("stripe"),invoiceMode:Yr.optional(),executor:f.z.enum(["indiana","merchant"]),accountId:f.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.z.enum(["update","cancel","schedule","release"]),update:f.z.strictObject({items:f.z.array(mf).max(20),remove:f.z.array(Ya).max(20),restoreItems:f.z.array(f.z.strictObject({price:Ya,quantity:f.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.z.number().int().positive().optional(),paymentBehavior:f.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.z.boolean().optional(),clearCancelAt:f.z.literal(!0).optional(),billingCycleAnchorNow:f.z.literal(!0).optional(),metadata:pf}).nullable(),cancel:f.z.strictObject({prorate:f.z.literal(!1),invoiceNow:f.z.literal(!1)}).nullable(),schedule:f.z.strictObject({currentItems:f.z.array(f.z.strictObject({price:Ya,quantity:f.z.number().int().min(0).max(1e4)})).max(20),nextItems:f.z.array(mf).min(1).max(20),switchAt:f.z.number().int().positive(),interval:f.z.enum(["week","month","year"]),intervalCount:f.z.number().int().min(1).max(52),resetBillingCycleAnchor:f.z.literal(!0).optional(),metadata:pf}).nullable(),release:f.z.strictObject({schedule:f.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.z.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"),es=f.z.strictObject({merchantTerms:xi.optional(),carryOverBalances:Xa.optional(),carryOverUsages:Xa.optional(),operationId:f.z.uuid(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),timing:f.z.enum(["immediate","renewal"]),effectiveAt:f.z.iso.datetime({offset:!0}),expiresAt:f.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:zt,debitMinor:zt,discountMinor:zt,taxMinor:zt,totalMinor:zt,retainedProductVersionIds:f.z.array(f.z.uuid()).max(19),execution:f.z.union([Af,rr])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&ba(e.merchantTerms,e.operationId,"subscription_change",e.currency)),y0=f.z.strictObject({operationId:f.z.uuid(),invoiceMode:f.z.boolean().optional(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),status:f.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.z.enum(["immediate","renewal"]),effectiveAt:f.z.iso.datetime({offset:!0}),checkoutUrl:f.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.z.enum(["indiana","merchant"]),execution:f.z.union([Af,rr]).nullable(),confirmedAt:f.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Fr.nullable().optional(),problem:to.nullable().optional(),quote:es.optional(),authority:Sa.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),A0=f.z.strictObject({operationId:f.z.uuid(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),timing:f.z.literal("store"),effectiveAt:f.z.null(),expiresAt:f.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:f.z.null(),debitMinor:f.z.null(),discountMinor:f.z.null(),taxMinor:f.z.null(),totalMinor:f.z.null(),retainedProductVersionIds:f.z.array(f.z.uuid()).max(19),store:f.z.strictObject({provider:f.z.enum(["apple","google"]),productId:f.z.string().min(1).max(255),catalogAmountMinor:zt,policy:f.z.enum(["apple_store","google_full_price"])})}),b0=f.z.strictObject({operationId:f.z.uuid(),membershipId:f.z.uuid(),productVersionId:f.z.uuid(),status:f.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.z.literal("store"),effectiveAt:f.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.z.null(),nativePurchase:au.nullable()}),bf=f.z.union([es,A0]),cu=f.z.union([y0,b0]),uu=fc,Xr=ga,xf=f.z.strictObject({requestId:f.z.uuid(),invoiceId:f.z.uuid(),...Ur.shape}).refine(io,"A partial refund states amountMinor; a full refund refunds the remaining amount"),Sf=f.z.strictObject({provider:f.z.literal("stripe"),executor:f.z.enum(["indiana","merchant"]),accountId:f.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uu,currency:f.z.string().regex(/^[a-z]{3}$/),metadata:f.z.strictObject({indianaRefundId:f.z.uuid()}),idempotencyKey:f.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.z.array(f.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),lu=f.z.strictObject({operationId:f.z.uuid(),merchantTerms:xi.optional(),invoiceId:f.z.uuid(),providerInvoiceId:f.z.string().min(1).max(200),currency:Ie,paidMinor:Xr,refundedMinor:Xr,pendingMinor:Xr,amountMinor:uu,mode:f.z.enum(["full","partial"]),entitlementAction:f.z.enum(["retain","revoke"]),revokes:f.z.strictObject({customerProductIds:f.z.array(f.z.uuid()).max(100),subscriptionIds:f.z.array(f.z.string().min(1).max(200)).max(20)}),execution:f.z.union([Sf,da]),expiresAt:f.z.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&ba(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"),ts=f.z.strictObject({operationId:f.z.uuid(),invoiceId:f.z.uuid(),providerInvoiceId:f.z.string().min(1).max(200),status:f.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.z.enum(["indiana","merchant"]),currency:Ie,amountMinor:uu,mode:f.z.enum(["full","partial"]),entitlementAction:f.z.enum(["retain","revoke"]),refundId:f.z.string().min(1).max(200).nullable(),quote:lu.optional(),execution:f.z.union([Sf,da]).nullable(),confirmedAt:f.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Fr.nullable().optional(),problem:to.nullable().optional(),authority:Sa.optional(),failureReason:f.z.string().min(1).max(200).nullable(),createdAt:f.z.iso.datetime({offset:!0}),completedAt:f.z.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"),G_=f.z.strictObject({invoiceId:f.z.uuid(),currency:Ie,paidMinor:Xr,refundedMinor:Xr,pendingMinor:Xr,refundableMinor:Xr,executor:f.z.enum(["indiana","merchant"]).nullable(),canRefund:f.z.boolean(),operations:f.z.array(ts).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),K_=f.z.strictObject({requestId:f.z.uuid(),...Ur.shape}).refine(io,"A partial refund states amountMinor; a full refund refunds the remaining amount");var If=ct.z.strictObject({requestId:ct.z.uuid(),targets:ct.z.array(ct.z.strictObject({membershipId:ct.z.uuid(),action:ct.z.enum(["cancel","uncancel"]),timing:ct.z.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"),ns=ct.z.strictObject({batchId:ct.z.uuid()}),x0=ct.z.strictObject({operationId:ct.z.uuid(),membershipIds:ct.z.array(ct.z.uuid()).min(1).max(20),provider:ct.z.enum(["stripe","apple","google"]),action:ct.z.enum(["cancel","uncancel"]),timing:ct.z.enum(["immediate","renewal"]),status:ct.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:es.nullable(),managementUrl:ct.z.url().nullable(),failureCode:ct.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),jo=ct.z.strictObject({batchId:ct.z.uuid(),ready:ct.z.boolean(),status:ct.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ct.z.iso.datetime({offset:!0}),acceptedAt:ct.z.iso.datetime({offset:!0}).nullable(),groups:ct.z.array(x0).min(1).max(100)});var Te=require("zod"),S0=Te.z.string().trim().min(1).max(240),du={requestId:Te.z.uuid(),reason:S0},rs=Te.z.discriminatedUnion("action",[Te.z.strictObject({...du,action:Te.z.literal("start"),productVersionId:Te.z.uuid(),entityId:Te.z.uuid().optional(),days:Te.z.number().int().min(1).max(730).optional()}),Te.z.strictObject({...du,action:Te.z.literal("extend"),membershipId:Te.z.uuid(),days:Te.z.number().int().min(1).max(730)}),Te.z.strictObject({...du,action:Te.z.literal("end"),membershipId:Te.z.uuid()})]),vf=Te.z.strictObject({operationId:Te.z.uuid()}),wf=Te.z.iso.datetime({offset:!0}),I0=Te.z.strictObject({provider:Te.z.literal("stripe"),executor:Te.z.enum(["indiana","merchant"]),accountId:Te.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Te.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Te.z.union([Te.z.literal("now"),wf]),prorationBehavior:Te.z.literal("none")}),pu=Te.z.strictObject({operationId:Te.z.uuid(),action:Te.z.enum(["start","extend","end"]),status:Te.z.enum(["pending","effective"]),managedBy:Te.z.enum(["indiana","stripe"]),membershipIds:Te.z.array(Te.z.uuid()).min(1).max(20),endsAt:wf.nullable(),execution:I0.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"),Z_=Te.z.strictObject({groupId:Te.z.uuid(),productVersionId:Te.z.uuid(),enabled:Te.z.boolean()});var Ye=require("zod");var Of=Ye.z.strictObject({requestId:Ye.z.uuid(),currency:Ie,makeDefault:Ye.z.boolean()}),Pf=Ye.z.strictObject({setupId:Ye.z.uuid()}),v0=Ye.z.strictObject({provider:Ye.z.literal("stripe"),executor:Ye.z.literal("merchant"),accountId:Ye.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ye.z.literal("setup"),currency:Ye.z.string().regex(/^[a-z]{3}$/),customer:Ye.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ye.z.uuid(),metadata:Ye.z.strictObject({grooveProjectId:Ye.z.uuid(),grooveEnvironmentId:Ye.z.uuid(),grooveCustomerId:Ye.z.uuid(),groovePaymentSetupId:Ye.z.uuid()}),setDefaultPaymentMethod:Ye.z.boolean(),expiresAt:Ye.z.iso.datetime({offset:!0})}),mu=Ye.z.strictObject({id:Ye.z.uuid(),provider:Ye.z.literal("stripe"),status:Ye.z.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:Ye.z.boolean(),url:Ye.z.url().nullable(),createdAt:Ye.z.iso.datetime({offset:!0}),expiresAt:Ye.z.iso.datetime({offset:!0}),completedAt:Ye.z.iso.datetime({offset:!0}).nullable(),execution:v0.nullable()});var Ft=require("zod"),Cf=Ft.z.union([Ft.z.string(),Ft.z.number(),Ft.z.boolean(),Ft.z.null()]),_f=Ft.z.strictObject({customerId:Ft.z.uuid()}),Ef=Ft.z.strictObject({customerId:Ft.z.uuid(),provider:Ft.z.literal("stripe"),checkedAt:Ft.z.iso.datetime({offset:!0}),status:Ft.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.z.number().int().nonnegative(),differences:Ft.z.array(Ft.z.strictObject({subscriptionId:Ft.z.string().startsWith("sub_"),itemId:Ft.z.string().nullable(),field:Ft.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Cf,actual:Cf})).max(1e4)});var we=require("zod");var is=we.z.iso.datetime({offset:!0}),os=we.z.strictObject({createdAt:is,id:we.z.uuid()}),as=we.z.strictObject({customerId:we.z.uuid().optional(),entityId:we.z.uuid().optional(),productId:we.z.string().min(1).max(256).optional(),provider:we.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:os.optional(),limit:we.z.number().int().min(1).max(100).optional()}),fu={id:we.z.uuid(),customerId:we.z.uuid(),entityId:we.z.uuid().nullable(),productId:we.z.string().min(1).max(256),productVersionId:we.z.uuid(),name:we.z.string().min(1).max(120),provider:we.z.enum(["stripe","apple","google","merchant","free"]),createdAt:is},w0=we.z.strictObject({...fu,status:we.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.z.boolean(),billingSubscriptionId:we.z.uuid().nullable()}),O0=we.z.strictObject({...fu,status:we.z.enum(["active","ended","refunded"]),orderId:we.z.uuid().nullable(),transactionId:we.z.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),P0=we.z.strictObject({...fu,status:we.z.enum(["blocked","resolved"]),conflict:we.z.strictObject({detectedAt:is,blockingMembershipIds:we.z.array(we.z.uuid()).min(1).max(100),transactionId:we.z.uuid()}),resolvedAt:is.nullable()}),Rf=as.extend({status:we.z.enum(["blocked","resolved"]).optional()}),kf=we.z.strictObject({customerId:we.z.uuid(),orderId:we.z.uuid()}),jf=we.z.strictObject({orderId:we.z.uuid(),status:we.z.enum(["blocked","resolved"])}),Tf=we.z.strictObject({items:we.z.array(w0).max(100),nextCursor:os.nullable()}),Nf=we.z.strictObject({items:we.z.array(O0).max(100),nextCursor:os.nullable()}),Df=we.z.strictObject({items:we.z.array(P0).max(100),nextCursor:os.nullable()});var it=require("zod");var Ff=it.z.union([it.z.strictObject({intent:it.z.literal("read"),requestId:it.z.uuid(),purchaseIntentId:it.z.uuid()}),it.z.strictObject({requestId:it.z.uuid(),provider:it.z.literal("apple"),purchaseIntentId:it.z.uuid(),productId:it.z.string().min(1).max(255).optional(),signedTransaction:it.z.string().min(1).max(131072)}),it.z.strictObject({requestId:it.z.uuid(),provider:it.z.literal("google"),purchaseIntentId:it.z.uuid(),productId:it.z.string().min(1).max(255).optional(),purchaseToken:it.z.string().min(1).max(16384)})]),Mf=it.z.strictObject({requestId:it.z.uuid(),orderId:it.z.uuid(),purchaseIntentId:it.z.uuid(),status:it.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:it.z.boolean(),completion:it.z.strictObject({transactionIds:it.z.array(it.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:it.z.boolean()}).nullable()});var L=require("zod"),gu=L.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),C0=L.z.record(L.z.string(),L.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),_0=3,To=20,E0=_0*To,hu=L.z.strictObject({type:L.z.literal("product"),productId:gu}),qf={type:L.z.literal("group"),key:L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.z.string().trim().min(1).max(80)},R0=L.z.discriminatedUnion("type",[hu,L.z.strictObject({...qf,items:L.z.array(hu).max(To)})]),k0=L.z.discriminatedUnion("type",[hu,L.z.strictObject({...qf,items:L.z.array(R0).max(To)})]),j0=L.z.array(k0).max(To).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>To||i>E0)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function yu(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:yu(t))}var Fi=L.z.strictObject({lookupKey:L.z.string().trim().min(1).max(200),displayName:L.z.string().trim().min(1).max(1500),items:j0,metadata:C0}),T0=L.z.strictObject({product:L.z.record(L.z.string(),L.z.json()),prices:L.z.array(L.z.record(L.z.string(),L.z.json())),entitlements:L.z.array(L.z.record(L.z.string(),L.z.json())),freeTrials:L.z.array(L.z.record(L.z.string(),L.z.json())),licenses:L.z.array(L.z.record(L.z.string(),L.z.json()))}),Uf=Fi.extend({id:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),state:L.z.enum(["active","archived"]),isCurrent:L.z.boolean(),revision:L.z.number().int().nonnegative(),publishedVersionId:L.z.uuid().nullable(),createdAt:L.z.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"})}),Bf=L.z.strictObject({id:L.z.uuid(),offeringId:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),version:L.z.number().int().positive(),document:Fi,productEvidence:L.z.record(gu,T0),createdAt:L.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=yu(e.document);(!n.length||F0(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"})}),N0=L.z.strictObject({rows:L.z.array(Uf).max(200),versions:L.z.array(Bf).max(500)}),o1=L.z.discriminatedUnion("action",[L.z.strictObject({action:L.z.literal("create"),document:Fi}),L.z.strictObject({action:L.z.literal("save"),id:L.z.uuid(),revision:L.z.number().int().nonnegative(),document:Fi}),L.z.strictObject({action:L.z.enum(["publish","set_current","archive","restore"]),id:L.z.uuid(),revision:L.z.number().int().nonnegative()})]),a1=L.z.strictObject({record:Uf,version:Bf.nullable()}),Vf=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("current")}),L.z.strictObject({type:L.z.literal("id"),id:L.z.uuid()}),L.z.strictObject({type:L.z.literal("lookup_key"),lookupKey:L.z.string().min(1).max(200)}),L.z.strictObject({type:L.z.literal("version"),versionId:L.z.uuid()})]),D0=L.z.strictObject({internalId:gu,id:L.z.string(),name:L.z.string().nullable(),version:L.z.number().int().positive(),archived:L.z.boolean()}),s1=N0.extend({products:L.z.array(D0).max(500),pagination:L.z.strictObject({rows:L.z.string().nullable(),versions:L.z.string().nullable(),products:L.z.string().nullable()}).optional()});function F0(e){let t=[];yu(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}var No=require("zod");var Lf=No.z.strictObject({id:No.z.uuid(),offeringId:No.z.uuid(),version:No.z.number().int().positive(),document:Fi});var Ot=require("zod");var Ae=require("zod");var ti=require("zod");var ss=ti.z.strictObject({items:ti.z.array(ti.z.strictObject({productVersionId:ti.z.string().min(1).max(200),label:ti.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:ti.z.string().min(1).max(200).nullable(),grouping:$a.optional()});function zf(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 Au=Ae.z.discriminatedUnion("type",[Ae.z.strictObject({type:Ae.z.literal("event"),event:Ae.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),Ae.z.strictObject({type:Ae.z.literal("open_url"),url:Ae.z.url().refine(e=>new URL(e).protocol==="https:")})]),M0=hn,q0=Ae.z.discriminatedUnion("type",[Ae.z.object({type:Ae.z.literal("checkout"),product:Ka}).strict(),Ae.z.object({type:Ae.z.literal("close")}).strict(),Ae.z.object({type:Ae.z.literal("action"),action:Au}).strict()]),Mi=Ae.z.object({schemaVersion:Ae.z.literal(3),kind:Ae.z.literal("paywall"),name:Ae.z.string().trim().min(1).max(80),presentation:jn,requirement:_n.optional(),products:ss,offeringVersionId:Ae.z.uuid().nullable(),offeringId:Ae.z.uuid(),screen:M0,buttons:Ae.z.record(Ae.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),q0)}).strict(),b1=Mi.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 B0(e))t.addIssue({code:"custom",message:r});for(let r of U0(e))t.addIssue({code:"custom",message:r});fr(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 U0(e){let t=e.products.items.map(a=>a.productVersionId),n=Em(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&&(!Ga(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")),Yt(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"),Yt(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 B0(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),nr(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 $f=Ae.z.object({id:Ae.z.uuid(),projectId:Ae.z.uuid(),environmentId:Ae.z.uuid(),revision:Ae.z.number().int().nonnegative(),state:Ae.z.enum(["active","archived"]),publishedVersionId:Ae.z.uuid().nullable(),updatedAt:Ae.z.iso.datetime({offset:!0}),draft:Mi}).strict(),x1=Ae.z.object({rows:Ae.z.array($f).max(200),nextCursor:Ae.z.uuid().nullable()}).strict(),S1=$f.omit({draft:!0}).extend({name:Ae.z.string(),productCount:Ae.z.number().int().nonnegative()}).strict(),I1=Ae.z.discriminatedUnion("action",[Ae.z.object({action:Ae.z.literal("save"),id:Ae.z.uuid().nullable(),revision:Ae.z.number().int().nonnegative(),document:Mi}).strict(),Ae.z.object({action:Ae.z.enum(["publish","archive"]),id:Ae.z.uuid(),revision:Ae.z.number().int().nonnegative()}).strict()]),v1=Ae.z.object({paywalls:Ae.z.array(Ae.z.object({id:Ae.z.uuid(),paywallId:Ae.z.uuid(),version:Ae.z.number().int().positive(),name:Ae.z.string().min(1).max(80),presentation:jn,buttons:Mi.shape.buttons}).strict()).max(500),limited:Ae.z.boolean()}).strict();var Re=require("zod");var Kt=require("zod");var qi=Kt.z.string().regex(/^[a-f0-9]{64}$/),V0=La.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Gf=Kt.z.strictObject({couponDigests:Kt.z.record(Kt.z.uuid(),qi),variables:Kt.z.record(En,Kt.z.record(Kt.z.uuid(),Kt.z.partialRecord(Kt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.z.string()))),locales:Kt.z.record(En,Pi.extend({nodes:Kt.z.record(Kt.z.string(),Kt.z.strictObject({base:V0})),plans:Kt.z.object({}).strict(),pickers:Kt.z.object({}).strict()}).omit({paywall:!0}))});var ze=require("zod");var Do=require("zod"),bu=Do.z.strictObject({eventsEnabled:Do.z.boolean(),experimentViewsEnabled:Do.z.boolean(),featureUsageEnabled:Do.z.boolean()}),_1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Kf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var xu=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),L0=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(xu).max(100)}),z0=$.z.strictObject({id:$.z.string().min(1).max(255),condition:nn,gate:$.z.boolean().optional()}),$0=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),Hf={condition:nn.optional(),parentConditions:$.z.array(z0).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(L0).max(100).optional(),ranges:$.z.array(xu).max(20).optional(),meta:$.z.array($0).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},Ui=$.z.strictObject({...Hf,key:$.z.string().min(1).max(255),variations:$.z.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Su=$.z.strictObject({value:ve,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),G0=$.z.strictObject({...Hf,id:$.z.string().max(255).optional(),force:ve.optional(),variations:$.z.array(ve).min(2).max(20).optional(),key:$.z.string().optional(),range:xu.optional(),tracks:$.z.array($.z.strictObject({experiment:Ui,result:Su})).max(100).optional()}),K0=$.z.strictObject({defaultValue:ve.optional(),rules:$.z.array(G0).max(500).optional()}),Fo=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:nn})])),vn=$.z.strictObject({scope:Me,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),K0),savedGroups:Fo,experiments:$.z.record($.z.uuid(),Ui)});var Mo=vn.extend({analyticsConfig:bu,remoteFeatures:ze.z.array(ze.z.string().min(1).max(255)).max(500)}),Iu=Mo.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"})}),Qf=ze.z.strictObject({attributes:Et,features:ze.z.array(ze.z.string().min(1).max(255)).max(500).optional(),customerId:ze.z.uuid().optional()}),H0=ze.z.strictObject({value:ve,source:ze.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ze.z.boolean(),off:ze.z.boolean(),ruleId:ze.z.string(),experimentResult:Su.optional()}),cs=ze.z.strictObject({generation:vn.shape.generation,evaluatedAt:vn.shape.evaluatedAt,expiresAt:vn.shape.expiresAt,features:ze.z.record(ze.z.string(),H0),merchandiseContext:ze.z.strictObject({merchandiseId:ze.z.uuid(),merchandise:Et}).optional()}),Jf=ze.z.strictObject({customerId:ze.z.uuid().optional(),events:ze.z.array(ze.z.strictObject({eventUuid:ze.z.uuid(),timestamp:ze.z.iso.datetime({offset:!0}),name:ze.z.string().min(1).max(255),merchandise:kp.optional(),properties:ze.z.record(ze.z.string(),ve).default({}),deviceId:ze.z.string().min(1).max(255).optional(),sessionId:ze.z.string().min(1).max(255).optional()})).min(1).max(100)}),Zf=ze.z.strictObject({inserted:ze.z.number().int().nonnegative(),duplicates:ze.z.number().int().nonnegative(),rejected:ze.z.number().int().nonnegative(),skipped:ze.z.number().int().nonnegative(),analyticsConfig:bu});var z=require("zod");var Wf=require("zod"),Yf=Wf.z.enum(["funnel-run/1","funnel-process/1"]),Xf="funnel-process/1";function vu(e,t=[]){let n=[];Yt(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(Ha(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 eh(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>eh(t)??[])}}function Q0(e){let t=e.pages.map(i=>{let a=eh(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(Ha({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 th(e,t=[]){let n=hn.parse(structuredClone(Q0(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=vu(n,t);if(i.length)throw new Error(i.join("; "));return n}var Q=require("zod");var M=require("zod");var ft=require("zod"),us=ft.z.strictObject({schemaVersion:ft.z.literal(1),renderKey:ft.z.string().min(1).max(256),routeTemplate:ft.z.string().startsWith("/").max(2048),selectors:ft.z.array(ft.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ft.z.array(ft.z.number().int().min(0)).min(1),absent:ft.z.array(ft.z.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"})}),nh=ft.z.strictObject({renderKey:ft.z.string().min(1).max(256),routeKey:ft.z.string().min(1).max(256),stateKey:ft.z.string().min(1).max(256),documentKey:ft.z.string().min(1).max(256),documentHash:ft.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:ft.z.string().min(1).max(256),entryMode:ft.z.enum(["hard","soft"]),match:ft.z.strictObject({present:ft.z.array(ft.z.number().int().min(0)),absent:ft.z.array(ft.z.number().int().min(0))})});var yr=require("zod"),J0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],wu="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Z0=yr.z.string().regex(new RegExp(`^${wu}/${wu}/${wu}/manifest\\.json$`)),rh=yr.z.strictObject({kind:yr.z.literal("gcs-resumable"),url:yr.z.url(),bucket:yr.z.enum(J0),objectKey:Z0,byteLength:yr.z.number().int().positive(),expiresAt:yr.z.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 St=M.z.string().min(1).max(256),yn=M.z.string().regex(/^[a-f0-9]{64}$/),ls=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:yn,sourceGraphDigest:yn,pageKey:St,stateKey:St,documentKey:St,documentHash:yn,elementKey:St.optional(),nodeId:St.optional(),contentHash:yn.optional(),renderKey:St.optional()}),ih=M.z.strictObject({pageKey:St,documentKey:St,expectedDocumentHash:yn,renderKey:St.optional(),nodeId:St,elementKey:St,expectedContentHash:yn,property:M.z.enum(["text","fontSize","color"]),value:M.z.union([M.z.string().max(4e3),M.z.number().finite()])}),oh=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:yn,sourceGraphDigest:yn,pageKey:St,stateKey:St,documentKey:St,documentHash:yn,renderKey:St.optional(),patches:M.z.array(ih.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),W0=/^[a-z][a-z0-9-]{0,39}$/,qo=M.z.string().regex(W0),Pu=M.z.enum(["web","ios","android"]),G1=M.z.discriminatedUnion("action",[M.z.strictObject({action:M.z.literal("register"),requestId:M.z.uuid(),client:qo,platform:Pu,label:M.z.string().trim().min(1).max(100),sha256:yn,bytes:M.z.number().int().min(1),transferBytes:M.z.number().int().min(1)}),M.z.strictObject({action:M.z.literal("complete"),versionId:M.z.uuid()}),M.z.strictObject({action:M.z.literal("current"),versionId:M.z.uuid(),expectedCurrent:M.z.uuid().nullable()}),M.z.strictObject({action:M.z.literal("delivery"),enabled:M.z.boolean()}),M.z.strictObject({action:M.z.literal("changes"),versionId:M.z.uuid(),experimentId:M.z.uuid(),variationId:St,changesetId:M.z.uuid().nullable(),expectedRevision:yn.nullable(),editorUrl:M.z.string().url().max(2048),patches:M.z.array(ih).max(200)})]),Cu=M.z.strictObject({id:M.z.uuid(),projectId:M.z.uuid(),environmentId:M.z.uuid(),clientKey:qo,platform:Pu,label:M.z.string(),sha256:yn,bytes:M.z.number().int().positive(),objectKey:M.z.string(),state:M.z.enum(["uploading","ready","rejected"]),isCurrent:M.z.boolean(),revision:M.z.number().int().nonnegative(),createdAt:M.z.string(),expiresAt:M.z.string(),readyAt:M.z.string().nullable(),summary:M.z.record(M.z.string(),M.z.json()),routeTree:M.z.json().nullable(),validation:M.z.record(M.z.string(),M.z.json())}),Y0=M.z.strictObject({key:qo,platform:Pu,currentId:M.z.uuid().nullable()}),K1=M.z.strictObject({rows:M.z.array(Cu).max(100),nextCursor:M.z.uuid().nullable(),clients:M.z.array(Y0).max(20)}),Ou=M.z.strictObject({storedBytes:M.z.number().int().nonnegative(),reservedBytes:M.z.number().int().nonnegative(),chargedBytes:M.z.number().int().nonnegative(),versions:M.z.number().int().nonnegative(),objects:M.z.number().int().nonnegative(),orphanObjects:M.z.number().int().nonnegative(),missingReadyObjects:M.z.number().int().nonnegative(),unknownObjectSizes:M.z.number().int().nonnegative(),byteLimit:M.z.number().int().positive(),versionLimit:M.z.number().int().positive(),remainingBytes:M.z.number().int().nonnegative()}),H1=M.z.strictObject({asOf:M.z.iso.datetime({offset:!0}),reclamation:M.z.literal("manual-review-required"),buckets:M.z.strictObject({source:Ou,runtime:Ou,previews:Ou})}),Q1=M.z.strictObject({version:Cu,actorId:M.z.uuid(),claims:M.z.record(M.z.string(),M.z.json())}),J1=M.z.strictObject({version:Cu,upload:rh.nullable()}),Z1=M.z.object({format:M.z.literal("indiana-route-state-index"),schemaVersion:M.z.literal(3),routes:M.z.array(M.z.object({routeKey:St,path:M.z.string(),documentKey:St,documentHash:yn,initialStateKey:St,initialRenderKey:St})),renders:M.z.array(nh)}).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"})}),W1=M.z.strictObject({rows:M.z.array(M.z.object({id:M.z.uuid(),name:M.z.string(),status:M.z.string(),variations:M.z.array(M.z.object({id:St,key:St,name:M.z.string().optional()}).loose())}).loose()),limited:M.z.boolean()}),Y1=M.z.strictObject({enabled:M.z.boolean(),allowedOrigins:M.z.array(M.z.string())});var ni=require("zod");var ah=ni.z.strictObject({id:ni.z.uuid(),name:ni.z.string().trim().min(1).max(80),client:qo,source:ls,event:ni.z.enum(["screen_enter","button_click"]),cooldownSeconds:ni.z.number().int().min(0).max(2592e3),behavior:ni.z.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"})});var Ke=require("zod");var _u=ve,X0=["parameters","answers","results","variables"];function Eu(e){return X0.some(t=>e===t||e.startsWith(t+"."))}function Ru(e){let t={};for(let[r,i]of Object.entries(Qa(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])=>!Eu(r))),variables:t}}var gt=require("zod");var ds=gt.z.discriminatedUnion("kind",[gt.z.object({kind:gt.z.literal("ledger"),cursor:Va}).strict(),gt.z.object({kind:gt.z.literal("billing"),cursor:gt.z.uuid()}).strict()]),eI=gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ar=gt.z.record(gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gt.z.union([gt.z.string().max(500),gt.z.boolean(),gt.z.array(gt.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),tI=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function ku(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>ku(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||tI.test(n)||ku(r,t+1)))}var nI=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,br=gt.z.record(eI,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!ku(e)&&!nI.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var sh=gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ps=gt.z.array(gt.z.object({variable:sh,componentId:sh,required:gt.z.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"),cE=gt.z.object({bindings:ps,answers:Ar,values:gt.z.record(gt.z.string(),ve).optional()}).strict();var ch=require("zod"),ms=ch.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var ju=Ke.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),uh=Ke.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),lh=br.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Tu=Ke.z.record(ju,Ke.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),rI=Ln,dh=Ke.z.strictObject({type:Ke.z.literal("external_task"),endpointId:Ke.z.uuid(),taskKey:ju,inputs:Ke.z.record(ju,rI).refine(e=>Object.keys(e).length<=20),outputs:Tu}),ph=Ke.z.strictObject({maxAttempts:Ke.z.number().int().min(1).max(5),retryDelaySeconds:Ke.z.number().int().min(1).max(30),backoff:Ke.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Ke.z.number().int().min(1).max(10),timeoutSeconds:Ke.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var gE=Ke.z.strictObject({outcome:Ke.z.enum(["success","failure"]),data:lh});var yE=Ke.z.discriminatedUnion("operation",[Ke.z.strictObject({operation:Ke.z.literal("signal"),runId:Ke.z.uuid(),nodeId:uh,eventName:ms,eventId:Ke.z.uuid(),data:lh}),Ke.z.strictObject({operation:Ke.z.literal("read_results"),runId:Ke.z.uuid()})]),AE=Ke.z.strictObject({scope:Me,runId:Ke.z.uuid(),eventId:Ke.z.uuid(),accepted:Ke.z.boolean()}),iI=Ke.z.record(uh,_u),bE=Ke.z.strictObject({scope:Me,runId:Ke.z.uuid(),results:iI});var Fn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},mh="00000000-0000-0000-0000-000000000000";var J=require("zod");var Xe=require("zod");var wE=Xe.z.enum(["local","remote"]),Nu=Xe.z.strictObject({port:Xe.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Xe.z.array(Xe.z.strictObject({expected:mo.nullable(),next:mo})).max(100),exposures:Xe.z.array(ve).max(100),features:Xe.z.array(ve).max(100)}),fh=Xe.z.strictObject({type:Xe.z.literal("evaluate"),receiptId:Xe.z.uuid(),environmentId:Xe.z.uuid(),policyRevision:Xe.z.number().int().nonnegative(),attributes:Et,sticky:Xe.z.record(Xe.z.string(),mo)}),hh=fh.extend({runId:Xe.z.uuid(),versionId:Xe.z.uuid(),nodeId:Xe.z.string().min(1).max(64),visit:Xe.z.number().int().nonnegative(),revision:Xe.z.number().int().nonnegative()}),Du=fh.omit({type:!0,receiptId:!0}).extend({type:Xe.z.literal("evaluate_segment")}),gh=Xe.z.strictObject({nodeId:Xe.z.string().min(1).max(64),result:Nu}),yh=Du.extend({runId:Xe.z.uuid(),versionId:Xe.z.uuid(),nodeId:Xe.z.string().min(1).max(64),visit:Xe.z.number().int().nonnegative(),revision:Xe.z.number().int().nonnegative(),parameters:br,answers:Ar,variables:Xe.z.record(Xe.z.string(),ve)});var ue=require("zod");var Fu=ue.z.array(ue.z.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"),fs=ue.z.intersection(Et,ue.z.looseObject({tags:Fu.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),hs=ue.z.string().trim().max(80),gs=ue.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ys=ue.z.union([ue.z.email().max(254),ue.z.literal("")]),As=ue.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Ah=ue.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),bh=ue.z.object({externalUserId:Ah.optional(),name:hs.default(""),email:ys.default(""),phone:gs.optional(),attributes:fs.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ri=ue.z.discriminatedUnion("type",[ue.z.strictObject({type:ue.z.literal("id"),value:ue.z.uuid()}),ue.z.strictObject({type:ue.z.literal("externalUserId"),value:Ah})]),Bi=ue.z.strictObject({name:hs.optional(),email:ys.optional(),phone:gs.optional(),attributes:fs.optional(),fingerprint:As.optional()}),bs=e=>!e.customerData||e.customer?.type==="externalUserId",xs="customerData requires an externalUserId customer",Vi=ue.z.object({id:ue.z.uuid(),externalUserId:ue.z.string().min(1).max(255).nullable(),name:hs,email:ys,phone:gs.optional(),attributes:fs,createdAt:ue.z.iso.datetime()}).strict(),xh=ue.z.object({customer:Vi,changed:ue.z.boolean(),replayed:ue.z.boolean()}).strict(),oI=ue.z.discriminatedUnion("type",[ue.z.object({type:ue.z.literal("id"),value:ue.z.uuid()}).strict(),ue.z.object({type:ue.z.literal("externalUserId"),value:ue.z.string().trim().min(1).max(255)}).strict()]),aI=ue.z.object({name:hs.optional(),email:ys.optional(),phone:gs.optional(),attributes:fs.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.z.array(ue.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.z.strictObject({add:Fu,remove:Fu}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Mu=ue.z.object({lookup:oI}).strict(),Sh=Mu.extend({requestId:ue.z.uuid(),patch:aI}).strict(),Ih=ue.z.object({search:ue.z.string().trim().max(200).default(""),tag:ue.z.string().trim().max(40).default(""),planId:ue.z.string().max(200).default(""),versionId:ue.z.string().max(200).default(""),holdingStatus:ue.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),createdUntil:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),offset:ue.z.coerce.number().int().min(0).max(1e5).default(0),limit:ue.z.coerce.number().int().min(1).max(100).default(50)}).strict(),vh=ue.z.object({customers:Vi.array(),hasMore:ue.z.boolean(),total:ue.z.number().int().nonnegative().nullable(),evaluatedAt:ue.z.iso.datetime()}).strict();var Uo=J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("literal"),value:ve}),J.z.strictObject({type:J.z.literal("variable"),key:wt,path:Dn.optional()}),J.z.strictObject({type:J.z.literal("feature"),featureKey:J.z.string().min(1).max(128)})]),sI=J.z.strictObject({requestId:J.z.uuid(),decisionId:J.z.uuid(),customerId:J.z.uuid(),externalUserId:J.z.string().min(1).max(255).nullable(),versionId:J.z.uuid(),receiptId:J.z.uuid(),value:ve}),cI={funnelId:J.z.uuid(),requestId:J.z.uuid(),customer:ri,customerData:Bi.optional(),attributes:Et.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},NE=J.z.discriminatedUnion("operation",[J.z.strictObject({operation:J.z.literal("decide"),...cI}).refine(bs,xs),J.z.strictObject({operation:J.z.literal("read_decision"),decisionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("evaluate_decision"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),receiptId:J.z.uuid(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),result:Nu}),J.z.strictObject({operation:J.z.literal("feature_config"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("commit_decision_segment"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),steps:J.z.array(gh).max(32),boundary:J.z.strictObject({nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative()}).optional()}),J.z.strictObject({operation:J.z.literal("segment_configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid().optional()}),J.z.strictObject({operation:J.z.literal("local_configuration"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("report_used"),decisionId:J.z.uuid(),eventId:J.z.uuid(),occurredAt:J.z.iso.datetime({offset:!0}),reference:J.z.string().min(1).max(128).optional()})]),DE=J.z.strictObject({scope:Me,decisionId:J.z.uuid(),requestId:J.z.uuid(),status:J.z.enum(["pending","completed","failed"]),decision:sI.nullable(),evaluation:J.z.discriminatedUnion("type",[hh,yh]).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"),FE=J.z.strictObject({scope:Me,decisionId:J.z.uuid(),eventId:J.z.uuid(),source:J.z.literal("caller_reported")});var Mt=require("zod");var wh=Mt.z.strictObject({type:Mt.z.literal("bundle"),paywall:Ln.optional(),offering:Ln.optional(),coupons:Ln,data:Ln}),uI=e=>Mt.z.strictObject({type:Mt.z.literal(e),id:Mt.z.uuid()}),VE=Mt.z.strictObject({type:Mt.z.literal("bundle"),paywallVersionId:Mt.z.uuid().optional(),offeringVersionId:Mt.z.uuid().optional(),couponIds:Mt.z.array(Mt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var LE=Mt.z.strictObject({type:Mt.z.literal("bundle"),offering:uI("offering_version").nullable(),paywall:Mt.z.strictObject({versionId:Mt.z.uuid(),paywallId:Mt.z.uuid(),offeringVersionId:Mt.z.uuid()}).nullable(),coupons:Mt.z.array(fo).max(20),data:ve});var wn=require("zod");var An=require("zod");var Oh=An.z.union([An.z.string(),An.z.number().finite(),An.z.boolean(),An.z.null()]),lI=An.z.union([Oh,An.z.array(Oh).min(1).max(20)]),dI=An.z.record(Dn,lI).refine(e=>Object.keys(e).length<=10),Ph=An.z.strictObject({path:Dn,type:An.z.enum(["string","number","boolean","strings"]),nullable:An.z.boolean().optional(),aggregation:An.z.enum(["count","exists"]).optional(),where:dI.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 pI=["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"],Ch=wn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),mI=Ln,_h=wn.z.discriminatedUnion("type",[dh,wn.z.strictObject({type:wn.z.literal("claim_offer"),coupon:Ln}),wn.z.strictObject({type:wn.z.literal("event"),event:Ch}),wn.z.strictObject({type:wn.z.literal("api"),operation:wn.z.enum(pI),inputs:wn.z.record(Dn,mI).refine(e=>Object.keys(e).length<=40),outputs:wn.z.record(Ch,Ph).refine(e=>Object.keys(e).length<=20)})]);var mt=ms,fI=Q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),bn={id:mt,name:Q.z.string().trim().min(1).max(80),position:Q.z.strictObject({x:Q.z.number().finite(),y:Q.z.number().finite()}).optional()},hI={success:mt,cancel:mt,unavailable:mt,failure:mt},qu=Q.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Uu=Q.z.enum(["same_window","new_window"]),gI=Q.z.discriminatedUnion("type",[Q.z.strictObject({...bn,type:Q.z.literal("entry"),next:mt,triggers:Q.z.array(ah).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.z.strictObject({...bn,type:Q.z.literal("screen"),screenId:mt,presentation:jn,outputs:Q.z.record(mt,mt),offering:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("variable"),key:wt}),Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()})]).optional()}),Q.z.strictObject({...bn,type:Q.z.literal("offering"),configuration:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()}),Q.z.strictObject({source:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("coupon"),couponId:Q.z.uuid(),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("coupons"),couponIds:Q.z.array(Q.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("output"),value:Q.z.discriminatedUnion("type",[...Uo.options,wh,Q.z.strictObject({type:Q.z.literal("selection"),screenId:mt,offeringKey:wt})])}),Q.z.strictObject({...bn,type:Q.z.literal("condition"),cases:Q.z.array(Q.z.strictObject({condition:nn,target:mt})).min(1).max(50),default:mt}),Q.z.strictObject({...bn,type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128),writes:Q.z.strictObject({value:wt}),next:mt}),Q.z.strictObject({...bn,type:Q.z.literal("split"),experimentId:Q.z.uuid(),applyPageExperiment:Q.z.literal(!0).optional(),routes:Q.z.record(fI,mt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:mt}),Q.z.strictObject({...bn,type:Q.z.literal("action"),...hI,execution:ph,action:_h,writes:Xc.optional()}),Q.z.strictObject({...bn,type:Q.z.literal("external_page"),appManifest:ls.optional(),url:qu,openIn:Uu,opened:mt,failed:mt}),Q.z.strictObject({...bn,type:Q.z.literal("end"),outcome:Q.z.enum(["completed","closed","ineligible","failed"]),output:Uo.optional()}),Q.z.strictObject({...bn,type:Q.z.literal("wait"),writes:Xc.optional(),wait:Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("duration"),delaySeconds:Q.z.number().int().min(1).max(2592e3),elapsed:mt}),Q.z.strictObject({type:Q.z.literal("event"),eventName:mt,outputs:Tu,timeoutSeconds:Q.z.number().int().min(1).max(2592e3),received:mt,timeout:mt})])})]),Bu=Q.z.strictObject({version:Q.z.literal(5),entry:mt,nodes:Q.z.array(gI).min(1).max(Fn.flowNodes)}),Vu=Bu.superRefine((e,t)=>{yI(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ss(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 yI(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>Fn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Fn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let p of Ss(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 Ss(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 Lu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Eh(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 pr(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]}var q=require("zod");var Li=q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Is=e=>q.z.record(q.z.string(),ve).refine(t=>gn(t)<=e,"Funnel evidence exceeds its byte budget"),hR=q.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),$u=q.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Gu=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("flag"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("experiment"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("saved_group"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("config"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("constant"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("paywall_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("offering_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("reward"),id:q.z.uuid()})]),Bo=q.z.strictObject({schemaVersion:q.z.literal(1),kind:$u,selector:Gu.nullable(),context:Is(131072),contract:q.z.strictObject({version:q.z.number().int().positive(),evaluator:q.z.string().min(1).max(128),policyRevision:q.z.number().int().nonnegative()})}).refine(e=>gn(e)<=131072,"Node input exceeds its byte budget"),Rh=q.z.strictObject({schemaVersion:q.z.literal(1),kind:$u,outcome:q.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Is(131072),route:q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Is(131072)}).refine(e=>gn(e)<=131072,"Node result exceeds its byte budget"),gR=q.z.strictObject({schemaVersion:q.z.literal(1),operations:q.z.record(Li,q.z.strictObject({attempts:q.z.number().int().nonnegative(),maxAttempts:q.z.number().int().min(1).max(5),deadlineAt:q.z.iso.datetime({offset:!0}),retryAt:q.z.iso.datetime({offset:!0}).nullable(),error:q.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.z.strictObject({type:Li,id:q.z.uuid()}).nullable()}))}).refine(e=>gn(e)<=65536,"Execution state exceeds its byte budget"),ii={receiptId:q.z.uuid()},zu=q.z.iso.datetime({offset:!0}),yR=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("node_entered"),details:q.z.strictObject({kind:$u})}),q.z.strictObject({type:q.z.literal("presentation_shown"),details:q.z.strictObject({...ii,source:q.z.literal("client"),occurredAt:zu.optional()})}),q.z.strictObject({type:q.z.literal("decision_accepted"),details:q.z.strictObject(ii)}),q.z.strictObject({type:q.z.literal("signal_received"),details:q.z.strictObject({signalId:q.z.uuid(),nodeId:Li,eventName:Li,data:Is(8192),source:q.z.literal("server"),occurredAt:zu})}),q.z.strictObject({type:q.z.literal("signal_consumed"),details:q.z.strictObject({...ii,signalId:q.z.uuid()})}),q.z.strictObject({type:q.z.literal("wait_elapsed"),details:q.z.strictObject(ii)}),q.z.strictObject({type:q.z.literal("wait_timeout"),details:q.z.strictObject(ii)}),q.z.strictObject({type:q.z.literal("operation_completed"),details:q.z.strictObject({...ii,operation:Li,reference:q.z.strictObject({type:Li,id:q.z.uuid()}).nullable()})}),q.z.strictObject({type:q.z.literal("execution_recovered"),details:q.z.strictObject({generation:q.z.number().int().positive(),reason:q.z.enum(["interrupted","expired_lease","delivery_failed"])})}),q.z.strictObject({type:q.z.literal("execution_failed"),details:q.z.strictObject({generation:q.z.number().int().positive(),code:q.z.string().regex(/^[a-z_]{1,64}$/)})}),q.z.strictObject({type:q.z.literal("run_completed"),details:q.z.strictObject({outcome:q.z.enum(["completed","ineligible","failed"])})}),q.z.strictObject({type:q.z.literal("run_closed"),details:q.z.strictObject({source:q.z.enum(["client","server","expiry"])})}),q.z.strictObject({type:q.z.literal("treatment_used"),details:q.z.strictObject({...ii,source:q.z.enum(["client","server"]),occurredAt:zu,reference:q.z.string().min(1).max(128).optional()})})]);var On=z.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),AI=z.z.discriminatedUnion("type",[z.z.strictObject({id:On,type:z.z.literal("owned"),publicData:Gf.optional(),document:hn.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.z.strictObject({id:On,type:z.z.literal("paywall"),paywallVersionId:z.z.uuid()})]),Ku={executionContract:Yf.optional(),kind:z.z.literal("funnel"),schemaVersion:z.z.literal(4),screens:z.z.array(AI).max(Fn.pages),references:z.z.record(On,Gu).refine(e=>Object.keys(e).length<=500),inputs:z.z.array(z.z.strictObject({variable:On,screenId:On,componentId:On,required:z.z.boolean()})).max(Fn.questions),variables:z.z.record(wt,Ei).refine(e=>Object.keys(e).length<=Fn.logicNodes),outputSchema:_i,execution:z.z.strictObject({runTimeoutSeconds:z.z.number().int().min(1).max(Lu.runTimeoutSeconds),maxTransitions:z.z.number().int().min(1).max(Lu.maxTransitions)})},FR=z.z.strictObject({...Ku,graph:Bu});function bI(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 ws(e){return Array.isArray(e)?e.some(ws):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===mh:ws(n))}function xI(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=th(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&&!Ro(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}),bI(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"&&ws(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ws(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function kh(e,t){for(let{message:n,reason:r,path:i}of xI(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function jh(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}fr(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),nr(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"&&!In(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",g),d.type==="output"&&d.value.type==="literal"&&!In(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&&!eu(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 ru(v.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!nu(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 Xn(v.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let C of pr(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=>!In({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=[...Eh(d,c),...g?.type==="owned"?Ja(g.document).map(y=>nu(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]:[]:Ss(_)).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"?Ro(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)nr(d.root,()=>{l++});p+=h.document.actions.length}(l>Fn.components||p>Fn.actions||gn(e)>Fn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var SI=z.z.strictObject({...Ku,graph:Vu}).superRefine(jh),zi=z.z.strictObject({...Ku,graph:Vu,displayName:z.z.string().trim().min(1).max(80)}).superRefine(jh),MR=zi.superRefine(kh),qR=SI.superRefine(kh),vs=z.z.string().regex(Ut),Vo={requestId:z.z.uuid(),nodeId:On,visit:z.z.number().int().nonnegative(),revision:z.z.number().int().nonnegative(),customerToken:vs.optional()},II=z.z.discriminatedUnion("type",[z.z.strictObject({type:z.z.literal("screen"),output:On,answers:Ar,selection:z.z.record(On,z.z.union([z.z.string().max(200),z.z.boolean(),z.z.number().int().min(0).max(1e4)])).optional()}),z.z.strictObject({type:z.z.literal("paywall_quote"),featureQuantities:z.z.record(z.z.uuid(),z.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:On,productVersionId:z.z.uuid(),offerId:z.z.uuid().optional(),nativeOffer:ji.optional(),predecessor:z.z.strictObject({operationId:z.z.uuid().nullable(),generation:z.z.number().int().positive()}).optional()}),z.z.strictObject({type:z.z.literal("paywall_confirm"),operationId:z.z.uuid()}),z.z.strictObject({type:z.z.literal("paywall_cancel"),operationId:z.z.uuid()}),z.z.strictObject({type:z.z.literal("client_action"),receiptId:z.z.uuid(),outcome:z.z.enum(["success","cancel","failure","opened","failed"])})]),vI=z.z.object({nodeId:On,visit:z.z.number().int().nonnegative(),revision:z.z.number().int().nonnegative(),components:z.z.record(On,z.z.object({resourceKey:z.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.z.number().int().min(1).max(1e5),after:ds.nullable(),filter:z.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Rt=z.z.discriminatedUnion("operation",[z.z.strictObject({operation:z.z.literal("start"),funnelId:z.z.uuid(),requestId:z.z.uuid(),customer:ri.optional(),customerData:Bi.optional(),locale:z.z.string().min(1).max(35),parameters:br}).refine(bs,xs),z.z.strictObject({operation:z.z.literal("get"),settlementRequestId:z.z.uuid().optional(),data:vI.optional(),purchase:z.z.strictObject({receiptId:z.z.uuid(),operationId:z.z.uuid()}).optional(),customerToken:vs.optional()}),z.z.strictObject({operation:z.z.literal("resume"),requestId:z.z.uuid(),customerToken:vs.optional()}),z.z.strictObject({operation:z.z.literal("submit"),...Vo,input:II}),z.z.strictObject({operation:z.z.literal("back"),...Vo}),z.z.strictObject({operation:z.z.literal("shown"),...Vo}),z.z.strictObject({operation:z.z.literal("close"),...Vo}),z.z.strictObject({operation:z.z.literal("commit_segment"),...Vo,policyRevision:z.z.number().int().nonnegative(),generation:z.z.string().min(1).max(256)}),z.z.strictObject({operation:z.z.literal("review"),receiptId:z.z.uuid().optional(),customerToken:vs.optional()})]);function Os(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 Xn(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&&Eu(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)}}var ae=require("zod");function Th(e,t){let n=[],r={};Yt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Yt(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 Nh(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Yt(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}var $i=require("zod");var Dh=$i.z.object({defaultLocale:En,locales:$i.z.record(En,$i.z.object({name:$i.z.string().max(80),description:$i.z.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 wI=["customer_data","coupon_code"],Fh=ae.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),OI=ae.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ps=(e,t)=>new Set(e.map(t)).size===e.length,PI=ae.z.strictObject({currency:Ie,amountMinor:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),CI=ae.z.strictObject({featureId:ae.z.uuid(),name:ae.z.string().trim().min(1).max(120),allowance:ae.z.string().max(40).nullable(),access:ae.z.boolean()}),_I=ae.z.strictObject({stripe:ae.z.strictObject({prices:ae.z.array(PI).min(1).max(50)}).optional(),apple:ae.z.strictObject({productIds:ae.z.array(Fh).min(1).max(10)}).optional(),google:ae.z.strictObject({products:ae.z.array(ae.z.strictObject({productId:Fh,basePlanId:OI.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Ps(e.stripe.prices,n=>n.currency)||e.apple&&!Ps(e.apple.productIds,n=>n)||e.google&&!Ps(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),EI=ae.z.strictObject({name:ae.z.string().trim().min(1).max(80),interval:ae.z.enum(["free","week","month","year","one_time"]),intervalCount:ae.z.number().int().min(1).max(100),trial:ae.z.strictObject({days:ae.z.number().int().min(1).max(730),cardRequired:ae.z.boolean()}).nullable(),benefits:ae.z.array(CI).max(50).refine(e=>Ps(e,t=>t.featureId),"Duplicate benefit"),channels:_I,prepaid:ae.z.array(Po).max(100).optional()}),RI=ae.z.strictObject({digest:qi,content:ae.z.strictObject({discount:mr,duration:mn,appliesTo:Mc,displayCopy:Dh.nullable(),firstPurchaseOnly:ae.z.boolean(),qualificationRequired:ae.z.boolean(),startsAt:ae.z.iso.datetime().nullable(),endsAt:ae.z.iso.datetime().nullable(),grantWindowHours:ae.z.number().int().positive(),perCustomerLimit:ae.z.number().int().positive()})}),kI=ae.z.discriminatedUnion("type",[ae.z.strictObject({type:ae.z.literal("checkout"),product:Ka}),ae.z.strictObject({type:ae.z.literal("close")}),ae.z.strictObject({type:ae.z.literal("action"),action:Au})]),Cs=ae.z.strictObject({kind:ae.z.literal("paywall"),formatVersion:ae.z.literal(1),name:ae.z.string().trim().min(1).max(80),offeringVersionId:ae.z.uuid(),presentation:jn,screen:hn,products:ss,catalog:ae.z.record(ae.z.uuid(),EI),buttons:ae.z.record(Ve,kI),coupons:ae.z.record(ae.z.uuid(),RI)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Th(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),vu(r,wI).forEach(n),fr(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Yt(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")}),Mh=ae.z.strictObject({state:ae.z.enum(["published","archived"]),controlRevision:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.z.uuid(),versions:ae.z.record(ae.z.uuid(),ae.z.strictObject({version:ae.z.number().int().positive(),artifact:ae.z.string().min(1),sourceDigest:ae.z.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},Hu=Re.z.string().regex(/^[a-f0-9]{64}$/),Qu=Re.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Zu=Me.extend({environmentId:Re.z.uuid()}),qh=Re.z.strictObject({features:Re.z.array(Re.z.string()).max(500),experiments:Re.z.record(Re.z.uuid(),Re.z.array(Re.z.string()).max(20)),savedGroups:Re.z.array(Re.z.string()).max(1e3)}),Wu=Re.z.strictObject({kind:Re.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.z.number().int().positive(),url:Re.z.string().min(1).max(2048),sha256:Hu,byteLength:Re.z.number().int().positive().max(sn.maxArtifactBytes),generation:Hu.optional()}),jI=Re.z.strictObject({state:Re.z.enum(["active","paused","archived"]),controlRevision:Qu,evaluationMode:Re.z.enum(["local","remote"]),evaluationRevision:Qu,currentVersionId:Re.z.uuid(),versions:Re.z.record(Re.z.uuid(),Re.z.strictObject({artifact:Re.z.string(),dependencies:qh,definitionDigest:qi.optional(),couponDigests:Re.z.record(Re.z.uuid(),qi).optional()}))}),Yu=Re.z.strictObject({kind:Re.z.literal("sdk_configuration"),schemaVersion:Re.z.literal(1),scope:Zu,revision:Qu,generation:Hu,policy:Re.z.strictObject({refreshIntervalSeconds:Re.z.number().positive().max(15),maxControlAgeSeconds:Re.z.number().positive().max(60)}),gb:Re.z.strictObject({features:Re.z.string().nullable(),pageExperiments:Re.z.string().nullable()}),artifacts:Re.z.record(Re.z.string(),Wu),funnels:Re.z.record(Re.z.uuid(),jI),paywalls:Re.z.record(Re.z.uuid(),Mh).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 kt(e){if(Array.isArray(e))return`[${e.map(kt).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)}:${kt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Xu(e){return ir(ar(typeof e=="string"?new TextEncoder().encode(e):e))}function Uh(e){return Xu(kt(e))}var Ju=class extends Error{constructor(n,r){super(n);Be(this,"dependency",r)}};function Bh(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 Ju(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=Os(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||!In(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 Xn(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 qh.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 Vh(e){return zi.parse(e)}var Lh=Ot.z.strictObject({processContext:Wa.optional(),...ki,selector:Ot.z.discriminatedUnion("type",[Ot.z.strictObject({type:Ot.z.literal("paywall"),paywallId:Ot.z.uuid()}),Ot.z.strictObject({type:Ot.z.literal("version"),versionId:Ot.z.uuid()})]),customerId:Ot.z.uuid().optional(),commerce:Si,locale:Ot.z.string().min(1).max(35),requirement:_n.optional()}),Lo=Ot.z.strictObject({id:Ot.z.uuid(),paywallId:Ot.z.uuid(),version:Ot.z.number().int().positive(),document:Mi.omit({requirement:!0,offeringId:!0}),offering:Ot.z.strictObject({id:Ot.z.uuid()}),content:Ot.z.strictObject({environmentId:Ot.z.uuid(),offeringVersionId:Ot.z.uuid(),artifact:Wu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Pi,check:ur.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"})}),oi=Ot.z.strictObject(Lo.shape).omit({document:!0,offering:!0}).extend({content:Lo.shape.content.unwrap()});function zh(e,t){let n=Cs.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 Lo.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}})}var Ht=require("zod");var $h={requestId:Ht.z.uuid(),sourceId:Ht.z.uuid(),expectedAvailable:Wt},Gh=Ht.z.discriminatedUnion("action",[Ht.z.strictObject({...$h,action:Ht.z.enum(["add","subtract","set_remaining"]),amount:de}),Ht.z.strictObject({...$h,action:Ht.z.literal("edit"),granted:de,expiresAt:Ht.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.z.number().int().nonnegative()})]),el=Ht.z.strictObject({sourceId:Ht.z.uuid(),available:Wt,held:Wt,spent:Wt,adjustmentGrantId:Ht.z.uuid().nullable()}),Kh=el.extend({granted:Wt,expiresAt:Ht.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.z.iso.datetime({offset:!0}).nullable(),revision:Ht.z.number().int().nonnegative()});var cn=require("zod"),Hh=cn.z.discriminatedUnion("action",[cn.z.object({action:cn.z.literal("upsert"),externalId:cn.z.string().min(1).max(128),name:cn.z.string().trim().min(1).max(80)}).strict(),cn.z.object({action:cn.z.literal("archive"),entityId:cn.z.uuid()}).strict()]),Qh=cn.z.object({id:cn.z.uuid(),externalId:cn.z.string().min(1).max(128),name:cn.z.string().min(1).max(80),archived:cn.z.boolean()}).strict();var $t=require("zod");var xr=require("zod"),Zh=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Jh=xr.z.string().regex(/.+\/.+/),tl=xr.z.number().min(-100),ai=xr.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),TI=xr.z.strictObject({input:ai,output:ai,cache_read:ai.optional(),cache_write:ai.optional(),reasoning:ai.optional(),input_audio:ai.optional(),output_audio:ai.optional()}),nl=(e,t)=>xr.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),Rk=xr.z.strictObject({defaultMarkup:tl,providerMarkups:nl(xr.z.string().min(1),tl),modelMarkups:nl(Jh,tl),customModels:nl(Jh,TI.partial())});var xe=require("zod"),si=xe.z.iso.datetime({offset:!0}),Sr=xe.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),NI=xe.z.discriminatedUnion("kind",[xe.z.object({kind:xe.z.literal("absolute"),from:si,to:si}).strict(),xe.z.object({kind:xe.z.literal("last_days"),days:xe.z.union([xe.z.literal(1),xe.z.literal(7),xe.z.literal(30),xe.z.literal(90)])}).strict(),xe.z.object({kind:xe.z.literal("billing_cycles"),membershipId:xe.z.uuid(),count:xe.z.number().int().min(1).max(12),includeCurrent:xe.z.boolean()}).strict()]),Wh=xe.z.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"),DI=xe.z.object({key:xe.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:xe.z.array(xe.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ci=xe.z.object({range:NI,timezone:Wh,filterBy:xe.z.array(DI).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:xe.z.enum(["hour","day","week","month"]),internal_feature_id:xe.z.uuid().nullable(),entityId:xe.z.uuid().nullable(),topN:xe.z.number().int().min(1).max(50).nullable(),groupBy:xe.z.union([xe.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),xe.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:xe.z.object({bucket:si,group:xe.z.string().max(240),isOther:xe.z.boolean(),internal_feature_id:xe.z.uuid(),resourceId:xe.z.uuid()}).strict().nullable(),limit:xe.z.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)"})}),Yh=xe.z.object({from:si,to:si,interval:xe.z.enum(["hour","day","week","month"]),timezone:Wh,rows:xe.z.array(xe.z.object({bucket:si,group:xe.z.string().max(240),isOther:xe.z.boolean(),internal_feature_id:xe.z.uuid(),resourceId:xe.z.uuid(),consumedUnits:Sr,refundedUnits:Sr,reservedUnits:Sr,charged:Sr,refunded:Sr,reserved:Sr,netUnits:Sr,netCharged:Sr}).strict()).max(100),nextCursor:xe.z.object({bucket:si,group:xe.z.string().max(240),isOther:xe.z.boolean(),internal_feature_id:xe.z.uuid(),resourceId:xe.z.uuid()}).strict().nullable()}).strict();var Gi=$t.z.string().regex(/^(0|[1-9]\d{0,29})$/),Xh=$t.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),rl=$t.z.strictObject({bucket:$t.z.iso.datetime({offset:!0}),group:$t.z.string().max(240),isOther:$t.z.boolean(),internal_feature_id:$t.z.uuid()}),eg=$t.z.strictObject({...ci.shape,groupBy:$t.z.union([$t.z.enum(["customer","entity","entitlement"]),$t.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:rl.nullable()}).superRefine((e,t)=>{let n=ci.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),tg=$t.z.strictObject({from:$t.z.iso.datetime({offset:!0}),to:$t.z.iso.datetime({offset:!0}),interval:ci.shape.interval,timezone:ci.shape.timezone,rows:$t.z.array($t.z.strictObject({...rl.shape,eventCount:Gi,units:Xh,tokenEventCount:Gi,tokens:$t.z.strictObject(Object.fromEntries(Zh.map(e=>[e,Gi]))),totalTokens:Gi,providerCostEventCount:Gi,providerCostUsd:Xh,invalidTelemetryEventCount:Gi})).max(100),nextCursor:rl.nullable()});var yt=require("zod");var ng=yt.z.object({requestId:yt.z.uuid(),items:yt.z.array(yt.z.object({customerId:yt.z.uuid(),command:xo.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"),rg=yt.z.object({batchId:yt.z.uuid(),after:yt.z.number().int().min(-1).max(999),limit:yt.z.number().int().min(1).max(100)}).strict(),ig=yt.z.object({batchId:yt.z.uuid(),status:yt.z.enum(["queued","complete"]),total:yt.z.number().int().min(1).max(1e3),processed:yt.z.number().int().min(0).max(1e3),items:yt.z.array(yt.z.object({position:yt.z.number().int().min(0).max(999),customerId:yt.z.uuid(),idempotencyKey:yt.z.string().min(1).max(120),status:yt.z.enum(["queued","accepted","rejected","failed"]),receipt:So.nullable(),errorCode:yt.z.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:yt.z.number().int().min(0).max(999).nullable()}).strict();var k=require("zod");var FI=k.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),og=k.z.enum(["draft","active","paused","archived"]),ag=k.z.string().min(1).max(256),sg=k.z.array(ag).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),MI=k.z.strictObject({duration:k.z.enum(["day","week","month","year"]),length:k.z.number().int().min(1).max(3660)}),qI=k.z.strictObject({internal_feature_id:k.z.uuid(),allowance:k.z.number().nonnegative().max(1e15).nullable(),expiry:MI.nullable()}),UI=k.z.discriminatedUnion("type",[k.z.strictObject({type:k.z.literal("feature_grant"),grants:k.z.array(qI).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.z.strictObject({type:k.z.literal("free_product"),productId:ag,duration:mn}),k.z.strictObject({type:k.z.literal("invoice_credits"),amount:k.z.number().positive().max(1e8),duration:mn,rollover:k.z.boolean(),productIds:sg})]),BI=k.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),cg=k.z.object({key:BI,name:k.z.string().trim().min(1).max(80),configuration:UI}).strict(),ug=k.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),il=k.z.object({code:ug,maxUses:k.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.z.boolean()}).strict(),lg=k.z.object({key:k.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.z.string().trim().min(1).max(80),rewardId:k.z.uuid(),redeemOn:k.z.enum(["customer_creation","checkout"]),receivedBy:k.z.enum(["referrer","all"]),maxRedemptions:k.z.number().int().min(1).max(1e6).nullable(),productIds:sg,excludeTrial:k.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),dg={id:k.z.uuid(),projectId:k.z.uuid(),environmentId:k.z.uuid(),revision:k.z.number().int().nonnegative(),status:og,createdAt:k.z.iso.datetime({offset:!0}),updatedAt:k.z.iso.datetime({offset:!0})},VI=cg.extend(dg).strict(),LI=lg.safeExtend(dg).strict(),Bk=k.z.strictObject({id:k.z.uuid(),key:k.z.string(),name:k.z.string(),type:FI,status:og}),Vk=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:cg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),Lk=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:lg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),pg=k.z.object({id:k.z.uuid(),rewardId:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid(),referrerId:k.z.uuid().nullable(),status:k.z.enum(["pending","applied","unavailable"]),result:k.z.record(k.z.string(),k.z.unknown()).nullable(),createdAt:k.z.iso.datetime({offset:!0})}).strict(),mg=k.z.object({code:ug,requestId:k.z.uuid()}).strict(),fg=k.z.strictObject({redemptionId:k.z.uuid(),currency:Ie,requestId:k.z.uuid(),accepted:k.z.literal(!0)}),zI=k.z.strictObject({type:k.z.literal("checkout"),orderId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:mn,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.z.url().nullable()}),hg=k.z.discriminatedUnion("type",[zI,k.z.strictObject({type:k.z.literal("subscription"),operationId:k.z.uuid(),membershipId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:mn,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["pending","running","applied","failed"])})]),gg=k.z.object({programId:k.z.uuid(),requestId:k.z.uuid()}).strict(),yg=k.z.object({id:k.z.uuid(),programId:k.z.uuid(),code:il.shape.code,createdAt:k.z.iso.datetime({offset:!0})}).strict(),zk=k.z.object({rows:k.z.array(VI).max(100),nextCursor:k.z.uuid().nullable()}).strict(),$k=k.z.object({rows:k.z.array(LI).max(100),nextCursor:k.z.uuid().nullable()}).strict(),$I=il.extend({id:k.z.uuid(),redemptions:k.z.number().int().nonnegative()}).strict(),GI=k.z.strictObject({id:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid().nullable(),referrerId:k.z.uuid().nullable(),code:k.z.string().nullable(),status:k.z.enum(["pending","triggered","applied"]),createdAt:k.z.iso.datetime({offset:!0})}),Gk=k.z.object({codes:k.z.array($I).max(100),redemptions:k.z.array(GI).max(100),customers:k.z.record(k.z.uuid(),k.z.string()),codesCursor:k.z.uuid().nullable(),redemptionsCursor:k.z.uuid().nullable()}).strict(),Kk=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("create"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),input:il}).strict(),k.z.object({action:k.z.literal("remove"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),codeId:k.z.uuid()}).strict()]);var w=require("zod");var Z=require("zod"),zn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},zo=e=>new Set(e).size===e.length,ol=Z.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),KI=Z.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),$o=Z.z.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"))),HI=Z.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ag=Z.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var bg=Z.z.strictObject({id:Z.z.uuid(),repo:KI,platform:Z.z.enum(["github","gitlab","bitbucket"]),branches:Z.z.array($o).min(1).max(4).refine(zo),workflow:Z.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.z.array(Z.z.uuid()).min(1).max(4).refine(zo),include:Z.z.array(Ag).min(1).max(16),exclude:Z.z.array(Ag).max(16),methods:Z.z.array(Z.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(zo),maxAgeHours:Z.z.number().int().min(1).max(720)}),xg=bg.extend({revision:Z.z.number().int().positive()}),Qk=Z.z.strictObject({repository:bg,expectedRevision:Z.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Sg=Z.z.strictObject({repositoryId:Z.z.uuid(),branch:$o}),QI=Z.z.array(ol).max(zn.keys).refine(zo),Ig=Z.z.strictObject({repository:xg.omit({keyIds:!0}),branch:$o,keys:QI,keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/)}),JI=Z.z.strictObject({filePath:HI,startingLineNumber:Z.z.number().int().min(1).max(1e7)}),al=Z.z.strictObject({protocol:Z.z.literal(1),repositoryId:Z.z.uuid(),branch:$o,workflow:Z.z.string().max(200),configurationRevision:Z.z.number().int().positive(),keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/),commit:Z.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.z.uuid(),runNumber:Z.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.z.number().int().min(1).max(1e4),scannerVersion:Z.z.literal("1"),scannedAt:Z.z.iso.datetime({offset:!0}),coverage:Z.z.strictObject({complete:Z.z.literal(!0),files:Z.z.number().int().min(0).max(zn.files),sourceBytes:Z.z.number().int().min(0).max(zn.sourceBytes),unresolvedCalls:Z.z.number().int().min(0).max(1e6),unsupportedFiles:Z.z.number().int().min(0).max(zn.files)}),features:Z.z.array(Z.z.strictObject({key:ol,refs:Z.z.array(JI).max(zn.referencesPerKey)})).max(zn.keys)}).superRefine((e,t)=>{zo(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)>zn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),sl=Z.z.strictObject({scanId:Z.z.uuid(),commit:Z.z.string(),receivedAt:Z.z.string(),references:Z.z.number().int().nonnegative(),removedReferences:Z.z.number().int().nonnegative()}),ZI=sl.extend({repositoryId:Z.z.uuid(),branch:$o,workflow:Z.z.string(),digest:Z.z.string(),configurationRevision:Z.z.number().int().positive(),runNumber:Z.z.number().int().positive(),runAttempt:Z.z.number().int().positive(),scannedAt:Z.z.string(),keySetHash:Z.z.string(),coverage:al.shape.coverage}),WI=Z.z.strictObject({repositories:Z.z.array(xg).max(zn.repositories),scans:Z.z.array(ZI).max(zn.repositories*zn.branches)}),YI=Z.z.strictObject({key:ol,references:Z.z.number().int().nonnegative(),coveredTargets:Z.z.number().int().nonnegative(),expiredTargets:Z.z.number().int().nonnegative(),uncertainTargets:Z.z.number().int().nonnegative()}),Jk=Z.z.strictObject({available:Z.z.boolean().default(!0),settings:WI,expectedTargets:Z.z.number().int().min(0).max(80),features:Z.z.array(YI).max(2001),truncated:Z.z.boolean()});var Ee=require("zod");var un=Ee.z.string().min(1).max(200),_s=Ee.z.iso.datetime({offset:!0}),Go=Ee.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),cl=Ee.z.number().int().min(0).max(1e12),Og=Ee.z.number().int().min(1).max(1e12),vg={...Jt,type:Ee.z.literal("coupon.redeemed"),grantId:Ee.z.uuid()},wg={...Jt,type:Ee.z.literal("usage.observed"),merchantTransactionId:un,resource:un,unit:un,quantity:Og},XI=Ee.z.strictObject({...Jt,type:Ee.z.literal("fulfillment.updated"),operationId:Ee.z.uuid(),merchantFulfillmentId:un,status:Ee.z.enum(["pending","applied","failed"])}),ev=Ee.z.strictObject({...Jt,type:Ee.z.literal("benefit.claimed"),merchantBenefitId:un,resource:un,unit:un,quantity:Og,expiresAt:_s.nullable(),revision:Go}),tv=Ee.z.strictObject({...Jt,type:Ee.z.literal("benefit.closed"),merchantBenefitId:un,status:Ee.z.enum(["failed","expired","canceled"]),revision:Go}),nv=Ee.z.strictObject({...Jt,type:Ee.z.literal("benefit.updated"),merchantBenefitId:un,status:Ee.z.enum(["active","expired","revoked"]),remainingQuantity:cl.nullable(),expiresAt:_s.nullable(),revision:Go}),rv=Ee.z.strictObject({...Jt,type:Ee.z.literal("authorization.updated"),merchantAuthorizationId:un,kind:Ee.z.literal("auto_topup"),status:Ee.z.enum(["pending","effective","revoked","failed"]),termsReference:un.nullable(),revision:Go}),iv=Ee.z.strictObject({...Jt,type:Ee.z.literal("balance.observed"),resource:un,unit:un,availableQuantity:cl,reservedQuantity:cl,periodStartsAt:_s.nullable(),periodEndsAt:_s.nullable(),revision:Go}),Pg=Ee.z.union([Ee.z.discriminatedUnion("type",[...md,XI,ev,tv,nv,rv,iv]),Ee.z.strictObject({...vg,productVersionId:Ee.z.uuid(),subscriptionId:Ee.z.string().trim().min(1).max(255)}),Ee.z.strictObject({...vg,merchandiseId:Ee.z.uuid()}),Ee.z.strictObject({...wg,operation:Ee.z.literal("consume")}),Ee.z.strictObject({...wg,operation:Ee.z.literal("reverse"),reversalOf:un})]),Cg=Ee.z.strictObject({id:Ee.z.uuid(),eventId:Ee.z.string().min(1).max(200),source:Ee.z.literal("merchant"),providerVerified:Ee.z.literal(!1),outcome:Ee.z.string().min(1).max(100)});var oe=require("zod");var _g=nf,ov=_g.extend({invoice_id:_g.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ul=oe.z.strictObject({name:oe.z.string().trim().min(1).max(255),memo:oe.z.string().max(1e4).nullable().optional(),footer:oe.z.string().max(1e4).nullable().optional(),net_terms_days:oe.z.number().int().positive().nullable().optional()}),av=ul.extend({id:oe.z.string().min(1).max(255),created_at:oe.z.number().nullable()}),Eg=oe.z.strictObject({items:oe.z.array(av).max(50),nextCursor:oe.z.uuid().nullable()}),ej=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),values:ul}),oe.z.strictObject({action:oe.z.literal("update"),id:oe.z.string().min(1).max(255),values:ul}),oe.z.strictObject({action:oe.z.literal("delete"),id:oe.z.string().min(1).max(255)})]),Rg=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),params:Ti}),oe.z.strictObject({action:oe.z.enum(["finalize","send","pay","void"]),requestId:oe.z.uuid(),invoiceId:oe.z.uuid()}),oe.z.strictObject({action:oe.z.literal("reissue"),requestId:oe.z.uuid(),invoiceId:oe.z.uuid(),params:ov})]),ll=oe.z.strictObject({id:oe.z.uuid(),customerId:oe.z.uuid(),providerInvoiceId:oe.z.string().nullable(),status:oe.z.enum(["draft","open","paid","void","uncollectible"]),currency:oe.z.string(),totalMinor:oe.z.string().regex(/^-?\d+$/),paidMinor:oe.z.string().regex(/^\d+$/),refundedMinor:oe.z.string().regex(/^\d+$/),hostedInvoiceUrl:oe.z.url().nullable(),createdAt:oe.z.number(),collectionMethod:oe.z.enum(["send_invoice","charge_automatically"]).nullable()}),kg=ll.extend({lines:oe.z.array(oe.z.strictObject({id:oe.z.uuid(),description:oe.z.string(),amountMinor:oe.z.string().regex(/^-?\d+$/),netAmountMinor:oe.z.string().regex(/^-?\d+$/),quantity:oe.z.number().nullable(),periodStart:oe.z.number().nullable(),periodEnd:oe.z.number().nullable()})).max(1e3)}),Ki=oe.z.strictObject({taskId:oe.z.uuid(),status:oe.z.enum(["ready","running","done","dead"]),invoice:ll.nullable(),errorCode:oe.z.string().nullable()}),jg=oe.z.strictObject({items:oe.z.array(ll).max(50),nextCursor:oe.z.uuid().nullable(),operations:oe.z.array(Ki).max(50),operationsLimited:oe.z.boolean()});var sv=w.z.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"]),Tg={scope:Me,permissions:w.z.array(sv),expiresAt:w.z.iso.datetime().nullable()},Kj=w.z.discriminatedUnion("kind",[w.z.object({...Tg,kind:w.z.literal("server"),keyId:w.z.string().min(1)}),w.z.object({...Tg,kind:w.z.literal("customer"),customerId:w.z.string().min(1),identityKind:w.z.enum(["identified","guest"]),expiresAt:w.z.iso.datetime()})]),V=w.z.object({requestId:w.z.uuid(),scope:Me}).strict(),cv=bh.safeExtend({fingerprint:As.optional()}).strict(),uv=V.extend({customer:Vi,created:w.z.boolean()});function Ng(){return V.extend({offer:fo.nullable(),reason:Np.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:wm,response:V.extend({message:w.z.object({messageId:w.z.uuid(),channel:Oo,acceptedAt:w.z.iso.datetime({offset:!0}),status:w.z.enum(["accepted","sending","completed","canceled"]),replayed:w.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.z.strictObject({messageId:w.z.uuid()}),response:V.extend({message:w.z.object({id:w.z.uuid(),channel:Oo,status:w.z.enum(["accepted","sending","completed","canceled"]),deliveries:w.z.array(w.z.object({id:w.z.uuid(),status:Pm,attempts:w.z.number().int().nonnegative(),receipts:w.z.array(w.z.object({kind:Cm,occurredAt:w.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Wl,response:V.extend({installation:Dr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Yl,response:V.extend({installation:Dr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:sa,response:V.extend({installation:Dr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.z.strictObject({channel:Oo}),response:V.extend({preference:Ys})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Om,response:V.extend({preference:Ys})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.z.strictObject({cursor:w.z.uuid().optional()}),response:V.extend({templates:Eg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),params:Ti}),response:V.extend({preview:su})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),requestId:w.z.uuid(),params:Ti}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:Ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Rg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:Ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),taskId:w.z.uuid()}),response:V.extend({operation:Ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),cursor:w.z.uuid().optional()}),response:V.extend({invoices:jg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),invoiceId:w.z.uuid()}),response:V.extend({invoice:kg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Sg,response:V.extend({config:Ig})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:al,response:V.extend({receipt:sl})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.z.strictObject({}),response:V.extend({payload:Mo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Qf,response:V.merge(cs)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Jf,response:V.merge(Zf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sourceId:w.z.uuid()}),response:V.extend({balance:Kh})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Gh}),response:V.extend({balance:el})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.z.strictObject({internal_feature_id:w.z.uuid(),customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.z.uuid(),config:wc,model_markups:Oa})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),query:Ba}),response:V.extend({usage:Io})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:hm}),response:V.extend({usage:Io})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:um}),response:V.extend({grant:Vc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:lm,response:V.extend({grants:dm})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.z.union(Ff.options.map(e=>e.extend({customerId:w.z.uuid().optional(),customerToken:w.z.string().regex(Ut).optional()}))),response:V.extend({operation:Mf})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Of.extend({customerId:w.z.uuid().optional()}),response:V.extend({setup:mu})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Pf.extend({customerId:w.z.uuid().optional()}),response:V.extend({setup:mu})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:If.safeExtend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ns.extend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ns.extend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ns.extend({customerId:w.z.uuid()}),response:V.extend({batch:jo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.z.discriminatedUnion("action",[rs.options[0].extend({customerId:w.z.uuid()}),rs.options[1].extend({customerId:w.z.uuid()}),rs.options[2].extend({customerId:w.z.uuid()})]),response:V.extend({trial:pu})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:vf.extend({customerId:w.z.uuid()}),response:V.extend({trial:pu})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:as,response:V.extend({subscriptions:Tf})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:as,response:V.extend({purchases:Nf})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Rf,response:V.extend({conflicts:Df})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:kf,response:V.extend({resolution:jf})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:_f,response:V.extend({verification:Ef})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ff.safeExtend({...ki,customerId:w.z.uuid().optional()}),response:V.extend({quote:Ni})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Pg,response:V.extend({record:Cg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional(),merchantConfirmation:so.optional()}),response:V.extend({operation:Di})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional()}),response:V.extend({operation:Di})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:yf.safeExtend({customerId:w.z.uuid().optional()}),response:V.extend({quote:bf})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional(),merchantConfirmation:so.optional()}),response:V.extend({operation:cu})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:ei.extend({customerId:w.z.uuid().optional()}),response:V.extend({operation:cu})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:xf.safeExtend({customerId:w.z.uuid()}),response:V.extend({quote:lu})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:ei.extend({customerId:w.z.uuid(),merchantConfirmation:so.optional()}),response:V.extend({operation:ts})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:ei.extend({customerId:w.z.uuid()}),response:V.extend({operation:ts})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Qp,response:V.extend({controls:Uc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Vp,response:V.extend({prepared:zp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:$p,response:V.extend({authorization:Fa})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Xp,response:V.extend({coupons:em})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Gp,response:V.extend({authorization:Fa})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Wp,response:V.extend({invoices:Yp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Zp.extend({customerId:w.z.uuid()}),response:V.extend({operation:Ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Jp,response:V.extend({invoice:yo})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:Hp}).strict(),response:V.extend({controls:Uc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:Hh}).strict(),response:V.extend({entity:Qh})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid().nullable(),query:eg}),response:V.extend({analytics:tg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.z.object({customerId:w.z.uuid().nullable(),query:ci}).strict(),response:V.extend({analytics:Yh})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:ng,response:V.extend({batchId:w.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:rg,response:V.extend({batch:ig})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:$d.extend({customerId:w.z.string().min(1).optional()}),response:V.extend({check:ur})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.z.strictObject({kind:gr,selector:w.z.discriminatedUnion("type",[w.z.strictObject({type:w.z.literal("resource"),id:w.z.uuid()}),w.z.strictObject({type:w.z.literal("version"),id:w.z.uuid()})]),customerId:w.z.string().min(1).optional()}),response:V.extend({content:iu})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lh,response:V.extend({paywall:oi})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.z.strictObject({processContext:Wa.optional(),...ki,selector:Vf,customerId:w.z.string().min(1).optional(),commerce:Si,requirement:_n.optional()}),response:V.extend({offering:Lf,candidates:w.z.array(Sc).max(20),availability:w.z.array(w.z.strictObject({productVersionId:w.z.uuid(),available:w.z.boolean(),reason:w.z.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:ur.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).strict(),response:V.extend({holdings:gm})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),query:Am}).strict(),response:V.extend({ledger:bm})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:pm.extend({customerId:w.z.uuid().optional()}),response:V.extend({detail:mm})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Lc.safeExtend({customerId:w.z.uuid().optional()}),response:V.extend({statement:fm})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),command:xo.options[0]}).strict(),response:V.extend({quote:am})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:w.z.union([w.z.strictObject({eventName:w.z.string().min(1),quantity:de.optional(),properties:_t.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)}),w.z.strictObject({internal_feature_id:w.z.uuid(),quantity:de.optional(),properties:_t.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)})])}),response:V.extend({receipts:w.z.array(So).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:xo.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:So})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:mg,response:V.extend({redemption:pg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:gg,response:V.extend({referralCode:yg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:fg,response:V.extend({checkout:hg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Sm,response:V.extend({seats:Gc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Im,response:V.extend({seats:Gc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:cv,response:uv},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Mu,response:V.extend({customer:Vi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Ih,response:V.extend(vh.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Sh,response:V.extend(xh.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.z.object({customerId:w.z.uuid()}).strict(),response:V.extend(cr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.z.strictObject({}),response:V.extend(cr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sessionId:w.z.uuid().optional()}),response:V.extend({revoked:w.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:As.optional()}),response:V.extend({customerId:w.z.uuid(),guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(cr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.z.uuid()}),response:V.extend({customer:Vi,switched:w.z.boolean(),replayed:w.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.z.strictObject({code:w.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.z.uuid()}),response:Ng()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.z.object({}).strict(),response:V.extend({offers:w.z.array(fo)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:Nd,response:V.extend({operation:yc})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:Dd,response:V.extend({operation:yc})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.z.object({customerId:w.z.string().min(1).max(255).optional(),couponId:w.z.uuid(),...ki,requestId:w.z.uuid(),couponContentDigest:w.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Ng()}},Hj={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};var Es=require("zod");var Ko=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function dl(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 Ko("Required GB Feature is unavailable");i=Yn(e.featureKey,t),o=i.value,Object.assign(r,Ri(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Ko("Required GB Experiment is unavailable");if(a=Na(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 Ko("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Yn(e.configuration.featureKey,t).value;o={type:"offering_version",id:Es.z.uuid().parse(u)},Object.assign(r,Ri(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,Ri(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 Dg(e,t,n){Es.z.uuid().parse(e),Es.z.number().int().nonnegative().parse(t);let r=ir(ar(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)}`}var H=require("zod");var Ir=H.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),lv=H.z.enum(["running","waiting","completed","closed","ineligible","failed"]),pl=H.z.discriminatedUnion("type",[Du,H.z.strictObject({type:H.z.literal("wait"),receiptId:H.z.uuid(),kind:H.z.enum(["timer","event","operation"]),deadline:H.z.iso.datetime({offset:!0}).nullable(),eventName:Ir.optional()}),H.z.strictObject({type:H.z.literal("open_url"),receiptId:H.z.uuid(),url:qu,openIn:Uu}),H.z.strictObject({type:H.z.literal("event"),receiptId:H.z.uuid(),event:Ir})]),Rs=H.z.strictObject({type:H.z.literal("funnel"),id:H.z.uuid(),versionId:H.z.uuid()}),dv={id:Ir,presentation:jn,outputs:H.z.array(Ir).max(250),inputs:ps,values:H.z.record(H.z.string(),ve).optional(),offeringKey:wt.optional(),capabilities:Pi,customerData:Nm,dataCursors:H.z.record(Ir,ds.nullable())},pv=H.z.strictObject({...dv,content:H.z.strictObject({type:H.z.literal("document"),document:hn})}),Ho=H.z.strictObject({id:H.z.uuid(),source:Rs,revision:H.z.number().int().nonnegative(),visit:H.z.number().int().nonnegative(),nodeId:Ir,nodeType:H.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:lv,stopped:H.z.boolean(),canBack:H.z.boolean(),authenticated:H.z.boolean(),locale:H.z.string().min(1).max(35),answers:Ar,parameters:br,variables:H.z.record(H.z.string(),ve),output:ve.nullable(),screen:pv.nullable(),paywall:H.z.strictObject({receiptId:H.z.uuid(),resolution:H.z.union([Lo,oi]),quote:Ni.nullable(),operation:Di.nullable(),purchaseRequestId:H.z.uuid().nullable(),selectionGeneration:H.z.number().int().nonnegative().optional(),canReselect:H.z.boolean().optional()}).nullable(),instruction:pl.nullable(),pendingRequest:H.z.strictObject({requestId:H.z.uuid(),authenticationRequired:H.z.boolean()}).nullable(),runExpiresAt:H.z.iso.datetime({offset:!0}),credentialExpiresAt:H.z.iso.datetime({offset:!0}).nullable()}),ks=H.z.strictObject({scope:Me,run:Ho,settlement:H.z.strictObject({requestId:H.z.uuid(),state:H.z.enum(["pending","unknown","settled"]),operationId:H.z.uuid().nullable(),receiptId:H.z.uuid().nullable().optional()}).optional(),purchase:H.z.strictObject({receiptId:H.z.uuid(),quote:Ni.nullable(),operation:Di.nullable(),canReselect:H.z.boolean().optional()}).optional(),review:H.z.strictObject({activeOperationId:H.z.uuid().nullable(),pages:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),nodeId:Ir,visit:H.z.number().int().nonnegative()})).max(100),page:H.z.strictObject({receiptId:H.z.uuid(),nodeId:Ir,visit:H.z.number().int().nonnegative(),document:hn,answers:Ar,inputs:ps,values:H.z.record(H.z.string(),ve).optional()}).nullable(),coupons:H.z.array(H.z.strictObject({grantId:H.z.uuid(),status:H.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.z.string().nullable()})).max(100),purchases:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),operationId:H.z.uuid(),status:H.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.z.uuid().optional()}),Fg=ks.extend({run:Ho.extend({paywall:Ho.shape.paywall.unwrap().extend({resolution:oi}).nullable()})});var Mg="X-Indiana-Server-Key";var se=require("zod");var be=require("zod");var Pt=require("zod");var mv=Pt.z.strictObject({selector:Pt.z.string().min(1).max(2048),action:Pt.z.enum(["set","append","remove"]),attribute:Pt.z.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:Pt.z.string().max(5e4).optional(),parentSelector:Pt.z.string().max(2048).optional(),insertBeforeSelector:Pt.z.string().max(2048).optional()}),fv=Pt.z.strictObject({variation:Pt.z.string().min(1).max(128),description:Pt.z.string().max(2e3).default(""),css:Pt.z.string().max(1e5).default(""),js:Pt.z.string().max(1e5).default(""),domMutations:Pt.z.array(mv).max(200).default([]),iam:oh.optional(),renderGuard:us.optional()}),ml=fv.omit({variation:!0,description:!0,iam:!0}),hv=Ui.omit({variations:!0,active:!0}).extend({changeId:Pt.z.string().regex(/^[a-f0-9]{64}$/),variations:Pt.z.tuple([ml,ml]).rest(ml).refine(e=>e.length<=20)}),qg=Pt.z.strictObject({trackExposures:Pt.z.boolean(),environmentId:Pt.z.uuid(),generation:Pt.z.string().regex(/^[a-f0-9]{64}$/),experiments:Pt.z.array(hv).max(100),savedGroups:Fo});var Qo=be.z.string().regex(/^[a-f0-9]{64}$/),vT=be.z.strictObject({iam:Qo,executionContracts:be.z.union([be.z.tuple([be.z.literal("funnel-run/1")]),be.z.tuple([be.z.literal("funnel-process/1")])]).default(["funnel-run/1"])}),gv=be.z.strictObject({release:Qo,render:us,button:be.z.strictObject({selector:be.z.string().min(1).max(512),elementKey:be.z.string().min(1).max(256),tag:be.z.enum(["button","a","input"])}).nullable()}),wT=be.z.strictObject({scope:Me.extend({environmentId:be.z.uuid()}),release:Qo,validatedAt:be.z.iso.datetime({offset:!0}),validUntil:be.z.iso.datetime({offset:!0}),entries:be.z.array(be.z.strictObject({id:be.z.uuid(),funnelId:be.z.uuid(),versionId:be.z.uuid(),event:be.z.enum(["screen_enter","button_click"]),target:gv})).max(4e3)}),Ug=be.z.strictObject({operation:be.z.literal("entry_start"),funnelId:be.z.uuid(),versionId:be.z.uuid(),entryId:be.z.uuid(),release:Qo,requestId:be.z.uuid(),locale:be.z.string().min(1).max(35).default("en")}),Bg=be.z.strictObject({scope:Me,suppressed:be.z.literal(!0),reason:be.z.enum(["frequency","in_progress"]),retryAt:be.z.iso.datetime({offset:!0}).nullable()}),OT=be.z.strictObject({experimentId:be.z.uuid(),splitNodeId:be.z.string().min(1).max(128)}),yv=be.z.strictObject({experimentId:be.z.uuid(),experimentKey:be.z.string().min(1).max(128),variationKey:be.z.string().min(1).max(128),inExperiment:be.z.boolean(),generation:be.z.string().min(1).max(256)}),Jo=be.z.strictObject({operation:be.z.literal("page_experiments"),release:Qo,usedReceiptIds:be.z.array(be.z.uuid()).max(20).default([]),customerToken:be.z.string().regex(Ut).optional()}),Vg=be.z.strictObject({scope:Me,runId:be.z.uuid(),assignments:be.z.array(yv.extend({receiptId:be.z.uuid()})).max(100),payload:qg});var Mn=se.z.literal(Xf),Av=se.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),fl=se.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Lg=se.z.discriminatedUnion("type",[se.z.strictObject({type:se.z.literal("guest"),guestToken:fl}),se.z.strictObject({type:se.z.literal("customer"),customer:ri,customerData:Bi.optional()})]),hl=se.z.strictObject({id:se.z.uuid(),runId:se.z.uuid(),customerId:se.z.uuid(),requestId:se.z.uuid(),acceptedAt:se.z.iso.datetime({offset:!0})}),bv=se.z.strictObject({participantId:se.z.uuid(),startedAs:se.z.enum(["guest","identified"]),binding:hl.omit({runId:!0,requestId:!0}).nullable()}),xv=se.z.union([pl,se.z.strictObject({type:se.z.literal("authentication_required"),reason:se.z.enum(["customer_required","customer_experiment_required"]),nodeId:se.z.string().min(1).max(64),visit:se.z.number().int().nonnegative()})]),Sv=Ho.omit({authenticated:!0}).extend({identity:bv,instruction:xv.nullable()}),Iv=se.z.discriminatedUnion("operation",[Rt.options[2].omit({customerToken:!0}),Rt.options[3].omit({customerToken:!0}),Rt.options[4].omit({customerToken:!0}),Rt.options[5].omit({customerToken:!0}),Rt.options[6].omit({customerToken:!0}),Rt.options[7].omit({customerToken:!0})]),js={contract:Mn,customerToken:se.z.string().regex(Ut)},zg={contract:Mn,requestId:se.z.uuid(),runToken:Av,externalUserId:ri.options[1].shape.value},$g=se.z.discriminatedUnion("operation",[se.z.strictObject({contract:Mn,operation:se.z.literal("describe")}),se.z.strictObject({contract:Mn,operation:se.z.literal("start"),source:Lg,funnelId:Rt.options[0].shape.funnelId,requestId:se.z.uuid(),locale:Rt.options[0].shape.locale,parameters:Rt.options[0].shape.parameters}),Ug.omit({operation:!0}).extend({contract:Mn,operation:se.z.literal("entry_start"),source:Lg}),se.z.strictObject({...zg,operation:se.z.literal("bind_customer"),guestToken:fl,claimRequestId:se.z.uuid(),expectedBindingId:se.z.null()}),se.z.strictObject({...zg,operation:se.z.literal("binding_status"),guestToken:fl.optional()}),Rt.options[1].omit({operation:!0,customerToken:!0}).extend({...js,operation:se.z.literal("get"),settlementBindingId:se.z.uuid().nullable().optional()}),Rt.options[8].omit({operation:!0,customerToken:!0}).extend({...js,operation:se.z.literal("review")}),Jo.omit({customerToken:!0}).extend(js),se.z.strictObject({...js,operation:se.z.literal("command"),identity:se.z.strictObject({bindingId:se.z.uuid().nullable()}),command:Iv})]),gl=ks.omit({run:!0}).extend({contract:Mn,run:Sv,settlement:ks.shape.settlement.unwrap().extend({accepted:se.z.boolean().nullable().optional()}).optional()}),NT=Bg.extend({contract:Mn}),DT=se.z.discriminatedUnion("operation",[$g.options[1].omit({contract:!0,source:!0,requestId:!0}),$g.options[2].omit({contract:!0,source:!0,requestId:!0})]),FT=gl.extend({binding:hl,outcome:se.z.enum(["bound","already_bound"]),replayed:se.z.boolean()}),MT=se.z.discriminatedUnion("state",[se.z.strictObject({contract:Mn,scope:Me,state:se.z.literal("not_accepted")}),se.z.strictObject({contract:Mn,scope:Me,state:se.z.literal("conflict")}),se.z.strictObject({contract:Mn,scope:Me,state:se.z.literal("bound"),binding:hl})]),qT=se.z.strictObject({contract:Mn,scope:Me,keyId:se.z.uuid(),operations:se.z.array(se.z.string()).max(20)});var De=require("zod");var Hi=De.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Kg=De.z.strictObject({entry:Hi,nodes:De.z.array(De.z.strictObject({id:Hi,type:De.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:De.z.record(De.z.string(),Hi),writes:De.z.record(wt,wt),resources:De.z.strictObject({screenId:Hi.optional(),paywallVersionId:De.z.uuid().optional(),couponId:De.z.uuid().optional(),couponIds:De.z.array(De.z.uuid()).max(20).optional(),experimentId:De.z.uuid().optional(),featureKey:De.z.string().optional(),offeringVersionId:De.z.uuid().optional()})})).min(1).max(500)}),Gg={scope:Me,funnelId:De.z.uuid(),versionId:De.z.uuid(),evaluationRevision:De.z.number().int().nonnegative(),expiresAt:De.z.iso.datetime({offset:!0}).nullable(),topology:Kg},Ts=De.z.discriminatedUnion("evaluationMode",[De.z.strictObject({...Gg,evaluationMode:De.z.literal("local"),growth:vn,conditions:De.z.record(Hi,De.z.array(De.z.strictObject({condition:nn,port:De.z.string()})))}),De.z.strictObject({...Gg,evaluationMode:De.z.literal("remote")})]),vv=Ts.options[0].extend({evaluation:De.z.strictObject({maxTransitions:De.z.number().int().min(1).max(1e4),variables:De.z.record(wt,Ei),outputSchema:_i,terminals:De.z.record(Hi,De.z.strictObject({outcome:De.z.enum(["completed","closed","ineligible","failed"]),output:Uo.nullable()}))})});function wv(e){return Kg.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=De.z.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 yl(e){let t=zi.parse(e.document),n=e.evaluationMode==="local"?vn.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:wv(t)};return Ts.parse(e.evaluationMode==="remote"?r:{...r,growth:Os(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 Hg(e){let t=yl(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=zi.parse(e.document);return vv.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}]]}))}})}var ot=require("zod");var Qg=ot.z.string().regex(/^[a-f0-9]{64}$/),Ov=Ui.omit({variations:!0,active:!0}).extend({changeId:Qg,variations:ot.z.array(ot.z.strictObject({urlRedirect:ot.z.string().max(2048)})).min(2).max(20)}),Jg=ot.z.strictObject({environmentId:ot.z.uuid(),trackExposures:ot.z.boolean(),generation:Qg,experiments:ot.z.array(Ov).max(100),savedGroups:Fo}),Pv=ot.z.strictObject({eventUuid:ot.z.uuid(),timestamp:ot.z.iso.datetime({offset:!0}).optional(),deviceId:ot.z.string().min(1).max(128),sessionId:ot.z.string().min(1).max(128).optional(),url:ot.z.url().max(2048),pageTitle:ot.z.string().max(512).optional(),experimentKey:ot.z.string().min(1).max(255),variationKey:ot.z.string().min(1).max(64)}),JT=ot.z.strictObject({events:ot.z.array(Pv).min(1).max(20)}),ZT=ot.z.strictObject({inserted:ot.z.number().int().nonnegative(),duplicates:ot.z.number().int().nonnegative(),skipped:ot.z.number().int().nonnegative(),rejected:ot.z.array(ot.z.strictObject({index:ot.z.number().int().nonnegative(),reason:ot.z.string()}))});var lt=require("zod");var bl=32,Cv=522240;function xl(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 _v=lt.z.strictObject({nodeId:lt.z.string().min(1).max(64),visit:lt.z.number().int().nonnegative(),revision:lt.z.number().int().nonnegative()}),Al=lt.z.record(lt.z.string(),ve),Ev=lt.z.strictObject({id:lt.z.uuid(),nodeId:lt.z.string().min(1).max(64),visit:lt.z.number().int().nonnegative(),input:lt.z.strictObject({schemaVersion:Bo.shape.schemaVersion,kind:Bo.shape.kind,selector:Bo.shape.selector,contract:Bo.shape.contract}),context:Al,removed:lt.z.array(lt.z.string()).max(100),attributes:Al,removedAttributes:lt.z.array(lt.z.string()).max(100),result:Rh,offeringVersionId:lt.z.uuid().nullable(),events:lt.z.strictObject({entered:lt.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:lt.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),tN=lt.z.strictObject({schemaVersion:lt.z.literal(1),mode:lt.z.enum(["local","remote"]),versionId:lt.z.uuid(),generation:lt.z.number().int().positive(),base:_v,context:Al,steps:lt.z.array(Ev).min(1).max(bl)}).refine(e=>gn(e)<=Cv,"Segment exceeds its byte budget");var Rv=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Zo(e){return Array.isArray(e)?e.some(Zo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Zo(n):!Rv.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=>Zo(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"||Zo(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"||Zo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Sl=class extends Error{constructor(n,r){super(r);Be(this,"code",n);this.name="FunnelLocalCalculationError"}},Wg=(e,t)=>new Sl(e,t),kv=e=>({experiments:e.experiments,features:e.features});function jv(e,t=Wg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Ii(e.growth.savedGroups),i=kv(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Yn(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=dl({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=dl({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 Tv(e,t){let n=Ts.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=jv(n,t);return(o,s)=>(i(),Nv(a,o,s))}function Nv(e,t,n){let r=Et.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 Dv(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 Yg(e,t,n,r=Wg){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=Tv(e,r)),Dv(m,R,{attributes:Ru({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<bl;R++){let y=a.get(u);if(!y||!xl(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"?tu({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||!In(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(gn({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=Ri(y,{value:C});zm(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&&(!xl(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=ca(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 Wo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},Fv=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 $n(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 Xg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Me.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 Fv(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=Dr.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(nd(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=$n(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,xt=Xl.parse(await h("detach",{sequence:Se,platform:x.platform}));try{let et=await t.request("push/installations/detach",{...x.scope,...xt},"POST",{installationDetach:!0});if(!et||typeof et!="object"||!("installation"in et))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Fe=m(et.installation);if(Fe.bound||Fe.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(et){if(et instanceof b&&et.status===404)_=et;else if(!(et instanceof b)||et.status!==412)throw et}_||$n(x,et=>({...et,detachSeq:et.detachSeq===Se?null:et.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&&$n(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=$n(j,Fe=>C?Fe:{...Fe,addressSeq:Wo(Fe.addressSeq)}),Se=await h(C?"recovery_confirm":"recovery_request",{...x,sequence:ye.addressSeq,credentialDigest:await p(le),...C?{challenge:C}:{}}),xt=C?td.parse(Se):ed.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let et=await d(`push/installations/recovery/${C?"confirm":"request"}`,xt,le);if(l(_),X!==a||$n(j,Fe=>Fe).addressSeq!==ye.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Fe=O.updatePushAddress.response.parse(et),at=m(Fe.installation);if(!at.bound||at.identitySeq!==o||at.addressSeq!==ye.addressSeq||at.connectionId!==x.connectionId||at.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return at}if(!et||typeof et!="object"||!("recovery"in et))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ws.parse(et.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Ws.parse(await A(v,x))},async confirm(v,C){return Dr.parse(await A(C,x,v))}}},identify(x){if(!e)return;o=$n(e,C=>({...C,identitySeq:Wo(C.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{$n(e,x=>{let v=Wo(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=$n(x,X=>{if(X.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Wo(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=$n(j,Se=>({...Se,addressSeq:Wo(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||$n(j,Se=>Se).addressSeq!==X.addressSeq?null:m(le.response.parse(ke).installation)}}}}var ty=require("zod");function ey(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof ty.ZodError?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=ey(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):ey(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 ny(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 ry={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 qv=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Uv(e){return e.replace(qv,"$1\uFFFD")}function Ol(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 py(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 iy(e){let t;if(Array.isArray(e)){let n=e.map(We);if(n.length===2)return n}else if((t=py(e))!=null){let n=Ol(t.next()),r=Ol(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 oy="0123456789ABCDEF",Bv=/(?:%[0-9A-Fa-f]{2})+/g;function Gn(e){return`%${oy[e>>4&15]}${oy[15&e]}`}function my(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Gn(e):String.fromCharCode(e):e<=2047?Gn(192|e>>6)+Gn(128|63&e):e<=65535?Gn(224|e>>12)+Gn(128|e>>6&63)+Gn(128|63&e):Gn(240|e>>18)+Gn(128|e>>12&63)+Gn(128|e>>6&63)+Gn(128|63&e)}function Pl(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Cl(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(Bv,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function ea(e){return e<=31||e>126}function Vv(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return ea(e)}}function Nl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return ea(e)}}function Lv(e){return Nl(e)||e===39}function _l(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Nl(e)}}function qs(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 _l(e)}}function ay(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 qs(n)}})(e)}}function fy(e,t){return my(e=e||0,t)}function Kn(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+=my(o,t,n)}return i}function Dl(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([Cl(i.slice(0,a),!0),Cl(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function El(e){let t="";for(let n=0;n<e.length;n++){let r=Kn(e[n][0],ay,!0),i=Kn(e[n][1],ay,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var zv=[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],$v=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Gv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Kv=[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 Hv(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[Qv,Jv,Zv,sy]=[[[],"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 Wv(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 hy(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Yo(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 Yv(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&&hy(Kv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Yo(sy,t[i]);)i--;let a=n+1;for(;a<t.length&&Yo(sy,t[a]);)a++;if(!(i>=0&&a<t.length&&Yo(Jv,t[i])&&Yo(Zv,t[a])))return!1}return!0}var Xv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,ew=/\p{Script=Latin}/u;function tw(e){return!Xv.test(e)||!ew.test(e)}var vr=36,Ds=1,Rl=26,nw=38,rw=700,iw=72,ow=128,aw=2147483647;function cy(e){return String.fromCharCode(e+22+75*+(e<26))}function sw(e,t,n){let r=0;for(e=n?Math.floor(e/rw):e>>1,e+=Math.floor(e/t);e>(vr-Ds)*Rl>>1;r+=vr)e=Math.floor(e/(vr-Ds));return Math.floor(r+(vr-Ds+1)*e/(e+nw))}function cw(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=ow,o=0,s=iw;for(;r<t.length;){let c=aw;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=vr;;m+=vr){let h=m<=s?Ds:m>=s+Rl?Rl:m-s;if(p<h)break;n+=cy(h+(p-h)%(vr-h)),p=Math.floor((p-h)/(vr-h))}n+=cy(p),s=sw(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Il(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=Pl(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function uy(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function gy(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function yy(e){return e.length===2&&gy(e.codePointAt(0),e.codePointAt(1))}function ly(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function At(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ay(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function kl(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=Pl(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+Pl(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 ly(r)?null:Kn(r,ea)})(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)&&!hy(zv,p)||Yo(Qv,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=Wv(p,m);if(h){l+=h;continue}let d=$v.indexOf(m);l+=d<0?p:Gv[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(Hv(u)||l&&(/^\p{Mark}/u.test(u)||!Yv(u)||!tw(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${cw(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Cl(e));return n===null||ly(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(Il(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=Il(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Il(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function jl(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 by(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 xy(e){return e.username!==""||e.password!==""}function vl(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Pe="",He=null,B,Fs=!1,Ms=!1,ui=!1,bt;function xn(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,Pe="",He=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Fs=!1,Ms=!1,ui=!1,bt=r||0;let i=uw;switch(r){case 3:case 4:i=Us;break;case 5:i=Ml;break;case 6:i=li;break;case 7:i=wr;break;case 8:i=Hn}return i(G(e,E))!==1?B:null}function ne(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 Sy(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var uw=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 Pe=U.slice(E,n).toLowerCase(),E=n,lw(n<U.length?e:void 0)}else return bt?1:(--E,ne(t,e)?Iy(G(U,E)):0)},lw=e=>{let t=E;if(e===58){if(bt){if(At(B.scheme)!==At(Pe))return 0;if((xy(B)||B.port!==null)&&Pe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Pe,bt?(B.port===Ay(B.scheme)&&(B.port=null),0):(Pe="",B.scheme==="file"?ne(t,e)?ql(G(U,E)):0:At(B.scheme)&&He!==null&&He.scheme===B.scheme?ne(t,e)?dw(G(U,E)):0:At(B.scheme)?ne(t,e)?mw(G(U,E)):0:G(U,E+1)===47?(E++,ne(t,e)?pw(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ne(t,e)?wy(G(U,E)):0))}else return bt?1:(Pe="",E=-1,ne(t,e)?Iy(G(U,E)):0)},Iy=e=>{let t=E;return He===null||He.opaquePath&&e!==35?1:He.opaquePath&&e===35?(B.scheme=He.scheme,B.path=He.path.slice(),B.opaquePath=He.opaquePath,B.query=He.query,B.fragment="",ne(t,e)?Hn(G(U,E)):0):He.scheme==="file"?(E--,ne(t,e)?ql(G(U,E)):0):(E--,ne(t,e)?Fl(G(U,E)):0)},dw=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ne(t,e)?Vs(G(U,E)):0):(E--,ne(t,e)?Fl(G(U,E)):0)},pw=e=>{let t=E;return e===47?ne(t,e)?Qi(G(U,E)):0:(E--,ne(t,e)?Un(G(U,E)):0)},Fl=e=>{let t=E;return B.scheme=He.scheme,e===47||At(B.scheme)&&e===92?ne(t,e)?dy(G(U,E)):0:(B.username=He.username,B.password=He.password,B.host=He.host,B.port=He.port,B.path=He.path.slice(),B.query=He.query,e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ne(t,e)?Un(G(U,E)):0):ne(t,e)?Fl(G(U,E)):0)},dy=e=>{let t=E;return At(B.scheme)&&(e===47||e===92)?ne(t,e)?Vs(G(U,E)):0:e===47?ne(t,e)?Qi(G(U,E)):0:(B.username=He.username,B.password=He.password,B.host=He.host,B.port=He.port,E--,ne(t,e)?Un(G(U,E)):0)},mw=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ne(t,e)?Vs(G(U,E)):0},Vs=e=>{let t=E;return e!==47&&e!==92?(E--,ne(t,e)?Qi(G(U,E)):0):ne(t,e)?Vs(G(U,E)):0},Qi=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!At(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&&At(B.scheme))break;n+=qn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?Qi(G(U,E)):0}if(e===64){Fs&&(Pe=`%40${Pe}`),Fs=!0;for(let n=0;n<Pe.length;n++){let r=Pe.codePointAt(n);if(r===58&&!Ms){Ms=!0;continue}let i=fy(r,qs);Ms?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Pe="",ne(t,e)?Qi(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&At(B.scheme)?Fs&&Pe===""?1:(E-=Pe.length+1,Pe="",ne(t,e)?Us(G(U,E)):0):(Pe+=Sy(e),ne(t,e)?Qi(G(U,E)):0)},Us=e=>{let t=E;if(bt&&B.scheme==="file")return E--,ne(t,e)?Ul(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!At(B.scheme))){let n=E+qn(e);for(e===91?ui=!0:e===93&&(ui=!1);n<U.length;){let r=G(U,n);if(r==null||!ui&&r===58||r===35||r===47||r===63||r===92&&At(B.scheme))break;r===91?ui=!0:r===93&&(ui=!1),n+=qn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?Us(G(U,E)):0}else if(e===58&&!ui){if(Pe===""||bt===4)return 1;let n=kl(Pe,!At(B.scheme));return n===null?1:(B.host=jl(n),Pe="",ne(t,e)?Ml(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&At(B.scheme)){if(E--,At(B.scheme)&&Pe==="")return 1;if(bt&&Pe===""&&(xy(B)||B.port!==null))return 1;let n=kl(Pe,!At(B.scheme));return n===null?1:(B.host=jl(n),Pe="",bt?0:ne(t,e)?li(G(U,E)):0)}else return Pe+=Sy(e),ne(t,e)?Us(G(U,E)):0},Ml=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 Pe+=U.slice(E,n),E=n-1,ne(t,e)?Ml(G(U,E)):0}else if(bt||e==null||e===35||e===47||e===63||e===92&&At(B.scheme)){if(Pe!==""){let n=parseInt(Pe,10);if(n>65535)return 1;if(B.port=n===Ay(B.scheme)?null:n,Pe="",bt)return 0}return bt?1:(E--,ne(t,e)?li(G(U,E)):0)}else return 1};function vy(e,t){let n=e.length-t;if(n<2)return!1;if(gy(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 ql=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ne(t,e)?fw(G(U,E)):0:He?.scheme==="file"?(B.host=He.host,B.path=He.path.slice(),B.opaquePath=He.opaquePath,B.query=He.query,e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):e!=null?(B.query=null,vy(U,E)?B.path=[]:by(B),E--,ne(t,e)?Un(G(U,E)):0):ne(t,e)?ql(G(U,E)):0):(E--,ne(t,e)?Un(G(U,E)):0)},fw=e=>{let t=E;return e===47||e===92?ne(t,e)?Ul(G(U,E)):0:(He!==null&&He.scheme==="file"&&(!vy(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})(He.path[0])&&B.path.push(He.path[0]),B.host=He.host),E--,ne(t,e)?Un(G(U,E)):0)},Ul=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 Pe+=U.slice(E,n),E=n-1,ne(t,e)?Ul(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!bt&&yy(Pe))return ne(t,e)?Un(G(U,E)):0;if(Pe==="")return B.host="",bt?0:ne(t,e)?li(G(U,E)):0;{let n=kl(Pe,!At(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=jl(n),Pe="",bt?0:ne(t,e)?li(G(U,E)):0)}}return 1},li=e=>{let t=E;return At(B.scheme)?(e!==92&&e!==47&&E--,ne(t,e)?Un(G(U,E)):0):!bt&&e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):!bt&&e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):e!=null?(e!==47&&E--,ne(t,e)?Un(G(U,E)):0):(bt&&B.host===null&&B.path.push(""),ne(t,e)?li(G(U,E)):0)},Un=e=>{let t=E;if(e!=null&&e!==47&&(!At(B.scheme)||e!==92)&&(bt||e!==63&&e!==35)){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||At(B.scheme)&&r===92||!bt&&(r===63||r===35))break;n+=qn(r)}Pe+=Kn(U.slice(E,n),_l),E=n,e=G(U,n)}if(e==null||e===47||At(B.scheme)&&e===92||!bt&&(e===63||e===35)){let n=At(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}})(Pe)?(by(B),e!==47&&!n&&B.path.push("")):uy(Pe)&&e!==47&&!n?B.path.push(""):uy(Pe)||(B.scheme==="file"&&B.path.length===0&&yy(Pe)&&(Pe=`${Pe[0]}:`),B.path.push(Pe)),Pe="",e===63?(B.query="",ne(t,e)?wr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):ne(t,e)?Un(G(U,E)):0}else return Pe+=fy(e,_l),ne(t,e)?Un(G(U,E)):0},wy=e=>{let t=E;if(e===63)return B.query="",ne(t,e)?wr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Hn(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]+=Kn(r.slice(0,-1),ea)+"%20":B.path[0]+=Kn(r,ea),E=n,(e=G(U,n))===63)return B.query="",ne(t,e)?wr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Hn(G(U,E)):0}return ne(t,e)?wy(G(U,E)):0},wr=e=>{let t=E,n=E;if(e!=null){if(bt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=At(B.scheme)?Lv:Nl;B.query+=Kn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!bt?(B.fragment="",ne(t,e)?Hn(G(U,E)):0):ne(t,e)?wr(G(U,E)):0},Hn=e=>{let t=E;return e!=null&&(B.fragment+=Kn(U.slice(E),Vv),E=U.length),ne(t,e)?Hn(G(U,E)):0};function Tl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Oy(e){switch(e.scheme){case"blob":{let t=xn(Tl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Oy(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"),Pn=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=xn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=xn(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=xn(n,null,null,0),r==null)?!1:xn(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+=Tl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ze].url)}set href(t){let n=xn(t=We(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze].url=n,this[Ze].query&&wl(this[Ze].query,n.query)}get origin(){return Oy(this[Ze].url)}get protocol(){return`${this[Ze].url.scheme}:`}set protocol(t){xn(`${t=We(t)}:`,this[Ze].url,null,2)}get username(){return this[Ze].url.username}set username(t){t=We(t),vl(this[Ze].url)||(function(r,i){r.username=Kn(i,qs)})(this[Ze].url,t)}get password(){return this[Ze].url.password}set password(t){t=We(t),vl(this[Ze].url)||(function(r,i){r.password=Kn(i,qs)})(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||xn(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||xn(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];vl(n)||(t?xn(t,n,null,5):n.port=null)}get pathname(){return Tl(this[Ze].url)}set pathname(t){t=We(t);let{url:n}=this[Ze];n.opaquePath||(n.path=[],xn(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&&wl(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",xn(i,n,null,7),r&&wl(r,n.query)}}get searchParams(){let t=this[Ze],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Bs;return o[dt].url=i,o[dt].serialized=a==null,a&&(o[dt].list=Dl(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="",xn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(Pn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var dt=Symbol("URLSearchParamsImpl"),hw=Symbol.dispose||Symbol.for("dispose");function wl(e,t){t?e[dt].list=Dl(t):e[dt].list.length=0,e[dt].serialized=t==null}function Ns(e){if(e.url){let t=El(e.list);(function(r,i){r[Ze].url.query=i})(e.url,t||null),e.serialized=!0}}var gw=typeof Iterator<"u"?Iterator:Object,Xo=class extends gw{constructor(t,n){super(),this[dt]={ptr:t,map:n,index:0}}next(){let t=this[dt];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}[hw](){}},Bs=class{constructor(t){let n=this[dt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(iy(t[i]));else if((r=py(t))!=null){let i;for(;!(i=Ol(r.next())).done;)n.list.push(iy(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=Uv(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=Dl(i)}}get size(){return this[dt].list.length}append(t,n){t=We(t),n=We(n),this[dt].list.push([t,n]);let r=this[dt];r.url&&r.serialized?(function(a,o){let s=a[Ze].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,El([[t,n]])):Ns(r)}delete(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[dt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Ns(this[dt])}get(t){t=We(t);let{list:n}=this[dt];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[dt];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[dt];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[dt],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&&Ns(this[dt])}sort(){this[dt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Ns(this[dt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[dt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Xo(this[dt],t=>t)}keys(){return new Xo(this[dt],t=>t[0])}values(){return new Xo(this[dt],t=>t[1])}toString(){return El(this[dt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Bs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Or="https://api.longplayai.com";function Py(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=cr.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 Cy=Symbol("IndianaNoContent");function Pr(e,t,n=Pn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Me.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??Or);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??Py(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((Fe,at)=>{ke=()=>at(ye()),le.signal.addEventListener("abort",ke,{once:!0})}),xt=setTimeout(()=>le.abort(),C.timeoutMs??c),et=async()=>{let Fe=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...C.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[nc]:rc.current,[sd]:ry.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 at;try{at=Fe.status===204?Cy:await Fe.json()}catch{throw le.signal.aborted?ye():new b(Fe.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Fe.status,Fe.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(!Fe.ok){let ht=tc.safeParse(at),Xt=ht.success&&(!Zn.safeParse(ht.data.error.code).success||od(ht.data.error.code,Fe.status)),kr=Xt?ht.data.error.code:"HTTP_ERROR",jr=ca(kr,Fe.status,{retryAfter:Fe.headers.get("Retry-After"),recovery:Xt?ht.data.error.recovery:void 0,reason:Xt?ht.data.error.reason:void 0});throw new b(kr,Xt?ht.data.error.message:"Longplay request failed",Fe.status,Fe.headers.get("X-Request-Id")??(ht.success?ht.data.requestId:void 0),{...jr,...ht.success&&ht.data.error.retryable===!1?{retryable:!1}:{},...jr.retryAfterSeconds===void 0&&ht.success&&ht.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ht.data.error.retryAfterSeconds}:{}})}if(Fe.headers.get(nc)!==rc.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&at!==Cy){let ht=at&&typeof at=="object"&&"scope"in at?at:at&&typeof at=="object"&&"configuration"in at?at.configuration:null;if(!ht||typeof ht!="object"||!("scope"in ht))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Xt=Me.safeParse(ht.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 pi=Fe.headers.get("X-Indiana-Telemetry-Subject");if(pi){if(!/^[a-f0-9]{64}$/.test(pi))throw new b("INVALID_RESPONSE","Invalid telemetry identity");p!==pi&&(p=pi,t?.(p))}return at};try{return await Promise.race([et(),Se])}catch(Fe){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Fe instanceof b?Fe:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(xt),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=Me.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 _y(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(!Ut.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 Bl(e,t,n,r){if(!Kd(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 Cr(e,t,n){if(e.requirement){if(!t)throw new b("INVALID_RESPONSE","The requested access check is missing");Bl(e.requirement,t,e.customerId,n)}}function Qe(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var yw={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Ey(e){return{async checkEntitlement(t){Qe(t);let n=O.checkEntitlement,r=n.request.parse(t),i=await ge(e,n,r);return Bl(r.requirement,i.check,void 0,i.scope),i},async readHoldings(t={}){return ge(e,yw,t)}}}function Ry(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Qe(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Qe(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function ky(e){return{async setupPayment(t){Qe(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Qe(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Qe(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Qe(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Qe(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Qe(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Qe(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Qe(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Qe(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Qe(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function jy(e){return{async previewUpdate(t){Qe(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Qe(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Qe(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Qe(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Qe(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Qe(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Qe(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Ty(e){return{async redeemReward(t){return Qe(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 Qe(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Qe(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 Ny(e){return{...Ey(e),...Ry(e),...ky(e),...jy(e),...Ty(e)}}function Dy(e){return{async resolveContent(t){Qe(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Qe(t);let n=O.resolvePaywall,r=n.request.parse(t),i=await ge(e,n,r);return Cr(r,i.paywall.check,i.scope),i},async resolveOffering(t){Qe(t);let n=O.resolveOffering,r=n.request.parse(t),i=await ge(e,n,r);return Cr(r,i.check,i.scope),i}}}var Vl=e=>new TextEncoder().encode(JSON.stringify(e)).length,Fy=16384;function My(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&&!Kf(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(Vl({events:[y]})>Fy)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=Vl({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=Vl(_)+(x.length?1:0);if(x.length&&v+X>Fy)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 Ls(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:Et.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(Yn(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=cs.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=Et.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?Mo.parse(x):null,C=v??vn.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(kt(le)!==kt(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=Ii(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=Et.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 qy(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=qy(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Uy(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 xt=qy(Se);n.track(ye,ke,xt?{merchandise:xt}:{})}catch(xt){R(xt)}},A=Ls({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()}}}var By=require("zod");function Vy(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=By.z.object({funnelId:Rs.shape.id,funnelVersionId:Rs.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 Cr(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 Cr(c,u.paywall.check,u.scope),u},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Ly(e){let t=Pr(e),n=t.request,r;try{r=Xg(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=_y(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=My(n,i.isIdentified),o=Uy(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...ny(n,r),...Ny(n),...Dy(n),forFunnel(s){return i.assertActive(),Vy(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 Ji(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)=>Ji(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)&&Ji(a,Reflect.get(t,i)))}function zs(e,t){let n=Fg.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 Zi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $s(e){let t=Ut.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Zi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Rt.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=Pr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=zs(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")||!Ji(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 Ll(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 zy(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ll(e,t,n))}function Gs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Xu(n)===t.sha256}async function Ks(e,t){let n=oi.parse(t),{artifact:r,environmentId:i}=n.content,a=new Pn(e.baseUrl??Or).origin,o=new Pn(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 Ll(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(!Gs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return zh(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var $y=(e,t)=>new b(e,t);var bw=3,xw=2e3;function Sw(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Iw(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===bw||!Sw(n))throw n;await new Promise(r=>setTimeout(r,t*xw))}}async function zl(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=vw(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await Iw(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function vw(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=yl({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:vn.parse(o)}),c=ww(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 ww(e,t,n){return Yg(e,t,n,$y)}var ln=require("zod");var Gy=Rt.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}),Ky=ln.z.strictObject({schemaVersion:ln.z.literal(1),scope:Me,runId:ln.z.uuid(),funnelId:ln.z.uuid(),versionId:ln.z.uuid(),processBindingIds:ln.z.record(ln.z.uuid(),ln.z.uuid().nullable()).optional(),command:Gy.optional(),closeCommand:Gy.refine(e=>e.operation==="close").optional(),purchase:ln.z.strictObject({receiptId:ln.z.uuid(),operationId:ln.z.uuid(),generation:ln.z.number().int().nonnegative()}).optional(),closed:ln.z.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"),Hs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Hy(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:Ky.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(Hs(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=Ky.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&&!Hs(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&&!Hs(m.closeCommand,p))throw rn();return{...m,closeCommand:p,closed:!0}}if(!Hs(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 Qy(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??Or).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 Jy(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||!Ji(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(!Ut.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 _r(e){let{customerToken:t,...n}=e;return n}var Ow=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Zy({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:_r(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&&!Ow(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function h(y){let A=Rt.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(_r(a))!==JSON.stringify(_r(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(_r(i))!==JSON.stringify(_r(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,xt=le?.receiptId??ke?.receiptId,et=X?.selectionGeneration??u?.generation??0;if(e&&Se&&xt&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||et>=u.generation)){let Fe={receiptId:xt,operationId:Se,generation:et},at=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},Fe,at,j),t.assertCurrent(x),(!u||Fe.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(at?u?.operationId===Fe.operationId&&(u=void 0):u=Fe)}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 Er(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"||!Zi.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=Pr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=Jy(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Qy(e):void 0),o=a&&Hy(a),s=Zy({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,xt)=>{ye=()=>xt(X.reason),X.addEventListener("abort",ye,{once:!0}),le=setTimeout(()=>xt(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"?Jo.parse(j):Rt.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!C?{[Mg]: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,_=zs(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 zl(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;zl(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:Dg(_.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(_r(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(_r(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 Ks(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=Vg.parse(await c(Jo.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 Wy(e){if(!Ut.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=$s({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Er({...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 Yy(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 Xy(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function eA(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 tA(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 nA(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 rA(e,t){if(!Ut.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=Pr(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});Cr(n,v.paywall.check,v.scope);let C=await Ks(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&&(!Yy(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:kd(v.merchantTerms)}:{}});return Xy(ye.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(ye.operation):(s=tA(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 nA({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=zf(v.product,x.selection,i.capabilities);if(!C)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Nh(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(),eA(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 iA(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 Pw=O.trackUsage.request.shape.command,Cw=O.trackUsage.response;function oA(e){let t=Me.parse(e.scope),n=Ly({...e,scope:t}),r={...e,scope:t,session:n.session},i=iA(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 Wy({...r,customerToken:s()})},resumeFunnel(c){return s(),Er({...r,runToken:c})},paywall(c){return rA(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Pw.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=Cw.parse(p);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}var cA=require("zod");var Wi=require("zod");var _w=Wi.z.record(Wi.z.string().regex(/^[a-f0-9]{64}$/),Wi.z.strictObject({at:Wi.z.number(),text:Wi.z.string()})),di=2*1048576,Ew=100;function Rw(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function aA(e,t){let n=t===void 0?Rw():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),Ew)})]);return typeof h=="string"&&h.length<=di&&new TextEncoder().encode(h).byteLength<=di?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 _w.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>di||new TextEncoder().encode(p).byteLength>di||(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>di)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>di||(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+_>di||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 Ce=(e,t)=>new b(e,t),Rr=()=>performance.now(),sA=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function uA(e){let t=Zu.parse(e.scope),n=new Pn(e.origin??Or);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 Ce("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let W=new Pn(Y);if(W.protocol!=="https:"||W.username||W.password||W.search||W.hash||W.pathname!=="/")throw Ce("INVALID_URL","Invalid configuration asset origin");return W.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${kt(t)}`,s=aA(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&&Rr()<u&&Date.now()<l;function xt(){if(!Se())throw Ce("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function et(Y,W,me){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+me>sn.maxCacheBytes);){let fe=j.entries().next().value;X-=fe[1].byteLength,j.delete(fe[0])}j.set(Y,{text:W,byteLength:me}),X+=me}}function Fe(Y,W,me){return zy(Y,W,{signal:me,error:fe=>Ce("INVALID_RESPONSE",fe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function at(Y){let W=new Pn(Y,n);if(!r.has(W.origin)||W.username||W.password||W.hash||W.search)throw Ce("INVALID_URL","Configuration artifact origin is not trusted");return W.href}async function ta(Y,W,me=!1){let fe=await i(at(Y),{method:"GET",credentials:"omit",redirect:"error",cache:me?"default":"no-cache",signal:W,headers:{}});if(fe.status===429){let rt=fe.headers.get("retry-after")??"";x=/^\d+$/.test(rt)?Number(rt)*1e3:Math.max(0,Date.parse(rt)-Date.now())||15e3}if(!fe.ok&&fe.status!==304)throw Ce(`CONFIGURATION_HTTP_${fe.status}`,"Configuration synchronization failed");return fe}function pi(Y,W,me){let fe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),rt=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),ut=Date.parse(Y.headers.get("date")??""),Je=Y.headers.get("age"),dn=Je!==null&&/^\d+(\.\d+)?$/.test(Je)?Number(Je)*1e3:NaN;if(![fe,rt,ut,dn].every(Number.isFinite)||rt<=fe||rt-fe>sn.maxControlAgeMs||fe>ut+1e3)throw Ce("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Gt=Math.min(rt-fe,me.maxControlAgeSeconds*1e3,sn.maxControlAgeMs)-Math.max(dn,ut-fe,0)-(Rr()-W);if(Gt<=0)throw Ce("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Rr()+Gt}function ht(){if(clearTimeout(y),clearTimeout(A),m||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?ht():ye()},Math.max(1,u-Rr())),sA(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))),sA(y)}async function Xt(){if(m)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=h,W=new AbortController;R=W;let me=(async()=>{if(!le){le=!0;try{let ra=await s.readManifest();if(ra&&!c){let Jn=Yu.parse(JSON.parse(ra));kt(Jn.scope)===kt(t)&&(c=Jn)}}catch{}}W.signal.throwIfAborted();let Je=c,dn=Rr(),Qt=await ta(a,W.signal);Qt.status===304&&(!Je||!Qt.headers.has("x-indiana-config-validated-at")||!Qt.headers.has("x-indiana-config-valid-until")||!Qt.headers.has("age"))&&(Qt=await ta(a,W.signal));let Gt=Qt.status===304?Je:Yu.parse(JSON.parse(await Fe(Qt,sn.maxManifestBytes,W.signal))),{generation:mi,...fi}=Gt,Qn=Qt.headers.get("etag");if(kt(Gt.scope)!==kt(t)||Uh(fi)!==mi||Qn!==`"${mi}"`&&Qn!==`W/"${mi}"`)throw Ce("INVALID_RESPONSE","Configuration scope or content identity changed");if(Je&&(Gt.revision<Je.revision||Gt.revision===Je.revision&&Gt.generation!==Je.generation))throw Ce("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ra,Jn]of Object.entries(Je?.funnels??{})){let Nr=Gt.funnels[ra];if(Nr&&(Nr.controlRevision<Jn.controlRevision||Nr.evaluationRevision<Jn.evaluationRevision||Nr.controlRevision===Jn.controlRevision&&Nr.state!==Jn.state||Nr.evaluationRevision===Jn.evaluationRevision&&Nr.evaluationMode!==Jn.evaluationMode))throw Ce("INVALID_RESPONSE","Funnel control revision changed identity")}let Tr=pi(Qt,dn,Gt.policy);if(W.signal.throwIfAborted(),Y!==h)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Gt,u=Tr,l=Date.now()+Math.max(0,Tr-Rr()),p=!1,d=0,x=0,s.writeManifest(kt(Gt)),ye(),structuredClone(Gt)})(),fe=setTimeout(()=>W.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs),rt=new Promise((Je,dn)=>W.signal.addEventListener("abort",()=>dn(W.signal.reason),{once:!0})),ut=Promise.race([me,rt]).catch(Je=>{throw d++,(Je instanceof cA.z.ZodError||Je instanceof SyntaxError||Je instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Je.code))&&(u=0,p=!0,ye()),Je}).finally(()=>{clearTimeout(fe),g===ut&&(g=void 0),ht()});return g=ut,ut}async function kr(Y){let W=Y.sha256,me=fi=>Gs(fi,Y);at(Y.url);let fe=j.get(W);if(fe){if(fe.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(W),j.set(W,fe),fe.text}let rt=_.get(W);if(rt){if(rt.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return rt.promise}let ut=new AbortController;C.add(ut);let Je=h,dn=(async()=>{try{let Tr=await s.readArtifact(W);if(Tr&&me(Tr)){if(ut.signal.throwIfAborted(),m||Je!==h)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return et(W,Tr,Y.byteLength),Tr}}catch{}ut.signal.throwIfAborted();let fi=await ta(Y.url,ut.signal,!0),Qn=await Fe(fi,Y.byteLength,ut.signal);if(!me(Qn))throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||Je!==h)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return et(W,Qn,Y.byteLength),s.writeArtifact(W,Qn),Qn})(),Qt=setTimeout(()=>ut.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),sn.initializationMs),Gt=new Promise((fi,Qn)=>ut.signal.addEventListener("abort",()=>Qn(ut.signal.reason),{once:!0})),mi=Promise.race([dn,Gt]).finally(()=>{clearTimeout(Qt),C.delete(ut),_.delete(W)});return _.set(W,{promise:mi,byteLength:Y.byteLength}),mi}async function jr(){return Se()||await Xt(),xt(),c}async function Yi(Y){let W,me=new Promise((fe,rt)=>{W=setTimeout(()=>rt(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs)});try{return await Promise.race([Y(),me])}finally{clearTimeout(W)}}function Xi(Y,W){if(xt(),c?.generation!==Y.generation)throw Ce("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(W&&c.funnels[W]?.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Gl(Y){let W=Y.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let me=Y.artifacts[W];if(me.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let fe=Iu.parse(JSON.parse(await kr(me)));if(kt(fe.scope)!==kt({projectId:t.projectId,environment:t.environment})||fe.generation!==me.generation||fe.remoteFeatures.some(rt=>Object.hasOwn(fe.features,rt)))throw Ce("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Xi(Y),{...fe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Rr())).toISOString()}}async function Kl(Y,W){let me=await jr(),fe=me.funnels[Y];W&&(!fe||fe.evaluationMode==="local"&&!fe.versions[W])&&(g&&await g,me=await Xt()),Xi(me,Y);let rt=me.funnels[Y];if(rt.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let ut=W??rt.currentVersionId,Je=rt.versions[ut];if(!Je)throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(me.artifacts[Je.artifact].formatVersion!==3)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[dn,Qt]=await Promise.all([kr(me.artifacts[Je.artifact]).then(Gt=>Vh(JSON.parse(Gt))),rt.evaluationMode==="local"?Gl(me):void 0]);if(Qt&&kt(Bh(dn,Qt))!==kt(Je.dependencies))throw Ce("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Xi(me,Y),{document:dn,growth:Qt,versionId:ut,control:structuredClone(rt),manifest:structuredClone(me)}}async function Hl(Y,W){try{return await Kl(Y,W)}catch(me){if(!(me instanceof b)||!(me.code==="CONFIGURATION_CHANGED"||me.code==="CONFIGURATION_HTTP_404"&&Se()))throw me;let fe=c?.generation;if(g&&await g,await Xt(),me.code!=="CONFIGURATION_CHANGED"&&c?.generation===fe)throw me;return Kl(Y,W)}}function Qs(){p=!0,ye(),Xt().catch(ke)}let na=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Qs()};function pA(Y){if(m)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Qs),window.addEventListener("focus",na),document.addEventListener("visibilitychange",na)),ht()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Ql())}}function Ql(){typeof window<"u"&&(window.removeEventListener("online",Qs),window.removeEventListener("focus",na),document.removeEventListener("visibilitychange",na))}return{scope:Object.freeze({...t}),refresh:Xt,subscribe:pA,assertFresh:xt,assertFeatures(Y){xt();let W=c.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[W].generation!==Y)throw Ce("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-Rr()):0},async features(){return Yi(async()=>Gl(await jr()))},pageExperiments:()=>Yi(async()=>{let Y=await jr(),W=Y.gb.pageExperiments;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let me=Y.artifacts[W];if(me.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let fe=Jg.parse(JSON.parse(await kr(me)));if(fe.environmentId!==t.environmentId||fe.generation!==me.generation)throw Ce("INVALID_RESPONSE","Page experiment scope or generation changed");return Xi(Y),fe}),funnel:(Y,W)=>Yi(()=>Hl(Y,W)),paywall:(Y,W)=>Yi(async()=>{let me=await jr(),fe=me.paywalls?.[Y];if(!fe||!W&&fe.state!=="published")throw Ce("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let rt=W??fe.currentVersionId,ut=fe.versions[rt],Je=ut&&me.artifacts[ut.artifact];if(!Je||Je.kind!=="paywall"||Je.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let dn=Cs.parse(JSON.parse(await kr(Je)));return Xi(me),{document:dn,versionId:rt,version:ut.version,control:structuredClone(fe),manifest:structuredClone(me)}}),async localFunnel(Y,W){let me=await Yi(()=>Hl(Y,W));if(!me.growth)throw Ce("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:fe,remoteFeatures:rt,...ut}=me.growth;return Hg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:me.versionId,evaluationMode:"local",evaluationRevision:me.control.evaluationRevision,document:me.document,payload:ut})},assertFunnel(Y,W,me){xt();let fe=c.funnels[Y];if(!fe||fe.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable");if(fe.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel now executes at Longplay");if(W!==void 0&&fe.controlRevision!==W)throw Ce("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(me!==void 0&&!fe.versions[me])throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,R?.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Ql(),ye(),v.clear();for(let Y of C)Y.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function lA(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&&kt(n)!==kt(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=Zi.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=$s({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Er({...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 $l(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function dA(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=gl.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)$l(j,d.run);d.run.instruction?.type==="authentication_required"&&$l(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=Er({...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()}}}
|