@tinkerlandai/indiana-sdk 0.0.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +52 -264
- package/dist/{api-DDlcUvTv.d.ts → ai-usage-CO0lDavO.d.ts} +3163 -660
- package/dist/chunk-EZFAY4ZL.js +1 -0
- package/dist/chunk-ULRVTA45.js +1 -0
- package/dist/chunk-YOH6DIUN.js +27 -0
- package/dist/{coupon-gncDkBtm.d.ts → customer-page-aZb5Twue.d.ts} +122 -3
- package/dist/funnel-runtime-host-OJJSHKUD.js +1 -0
- package/dist/funnel-runtime-start-DvrWekm0.d.ts +9330 -0
- package/dist/index.d.ts +8677 -1611
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -3
- package/dist/openrouter.js +1 -1
- package/dist/paywall-HCADUT22.js +1 -0
- package/dist/popup.d.ts +19 -123
- package/dist/popup.js +5 -4
- package/dist/{funnel-runtime-C05ZECiP.d.ts → screen-DfuSw6Tz.d.ts} +320 -2419
- package/dist/server.d.ts +4 -765
- package/dist/server.js +1 -1
- package/dist/src-3GT6E6XD.js +1 -0
- package/package.json +3 -3
- package/dist/ai-usage-CzA11PV5.d.ts +0 -235
- package/dist/chunk-IUDHYOKC.js +0 -21
- package/dist/chunk-OIWEFX7U.js +0 -1
- package/dist/chunk-TDSKWZTO.js +0 -1
- package/dist/feature-client-CyYevYy2.d.ts +0 -450
- package/dist/funnel-runtime-host-DWRQK5U2.js +0 -4
- package/dist/src-MCXYJ2QR.js +0 -1
package/dist/chunk-IUDHYOKC.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import{z as H}from"zod";var Zc=H.object({fromProductVersionId:H.uuid(),toProductVersionId:H.uuid(),membershipIds:H.array(H.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length)}).strict().refine(e=>e.fromProductVersionId!==e.toProductVersionId),vm=H.object({fingerprint:H.string().regex(/^[a-f0-9]{64}$/),rows:H.array(H.object({customerId:H.uuid(),membershipId:H.uuid().nullable(),entityId:H.uuid().nullable(),benefitTiming:H.enum(["immediate","renewal"]),priceEffectiveAt:H.iso.datetime({offset:!0}).nullable(),reason:H.enum(["membership_unavailable","unsupported_contract","binding_unavailable","change_pending","proration_required"]).nullable()}).strict()).max(1e3)}).strict(),Am=H.object({requestId:H.uuid(),selection:Zc,fingerprint:H.string().regex(/^[a-f0-9]{64}$/)}).strict(),km=H.object({id:H.uuid(),status:H.enum(["queued","complete","partial"]),total:H.number().int().positive().max(1e3),rows:H.array(H.object({id:H.uuid(),customerId:H.uuid(),membershipId:H.uuid(),entityId:H.uuid().nullable(),benefitTiming:H.enum(["immediate","renewal"]),benefitsAppliedAt:H.iso.datetime({offset:!0}).nullable(),priceEffectiveAt:H.iso.datetime({offset:!0}).nullable(),status:H.enum(["queued","processing","scheduled","effective","failed"]),errorCode:H.enum(["conflict","unsupported_contract","forbidden","internal_error"]).nullable()}).strict()).max(100),nextAfter:H.uuid().nullable()}).strict();import{z as Ye}from"zod";import{z as Qt}from"zod";var yo=Qt.number().int().min(0).max(1e8),Vn=Qt.strictObject({kind:Qt.enum(["graduated","volume"]),tiers:Qt.array(Qt.strictObject({upTo:Qt.number().int().min(1).max(1e4).nullable(),unitAmountMinor:yo,flatAmountMinor:yo.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>t.upTo!==null&&(n===0||t.upTo>e.tiers[n-1].upTo)),"Tier ceilings must increase and end unbounded");function Fr(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");if(t===0)return 0;let n=0n,r=0;if(!e.pricing)n=BigInt(e.amountMinor)*BigInt(t);else for(let i of e.pricing.tiers){let o=i.upTo??1e4;if(e.pricing.kind==="volume"){if(t<=o){n=BigInt(t)*BigInt(i.unitAmountMinor)+BigInt(i.flatAmountMinor??0);break}}else t>r&&(n+=BigInt(Math.min(t,o)-r)*BigInt(i.unitAmountMinor)+BigInt(i.flatAmountMinor??0));r=o}if(n>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(n)}function qn(e){return Fr({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as Dt}from"zod";var So=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],xo=Dt.string().min(3).max(120).regex(/^[a-z0-9-]+\/[^\s]+$/),Br=Dt.number().min(-100).max(1e3).refine(e=>/^-?\d+(\.\d{1,4})?$/.test(String(e)),"Markup supports four decimal places"),Tt=Dt.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Hc=Dt.strictObject({input:Tt,output:Tt,cache_read:Tt.optional(),cache_write:Tt.optional(),reasoning:Tt.optional(),input_audio:Tt.optional(),output_audio:Tt.optional()}),$r=(e,t)=>Dt.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),Nn=Dt.strictObject({defaultMarkup:Br,providerMarkups:$r(Dt.string().min(1).max(60).regex(/^[a-z0-9-]+$/),Br),modelMarkups:$r(xo,Br),customModels:$r(xo,Hc)});import{z as h}from"zod";import{z as j}from"zod";import{z as it}from"zod";import{z as Jc}from"zod";var It=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],z=Jc.enum(It);function Ft(e){let t=z.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function Rm(e,t){let n=Ft(t),r=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!r||(r[2]?.length??0)>n)throw new Error("Amount has invalid currency precision");let i=BigInt(r[1])*BigInt(10**n)+BigInt((r[2]??"").padEnd(n,"0")||"0");if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(i)}function Em(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=Ft(t),r=String(e).padStart(n+1,"0");return n?`${r.slice(0,-n)}.${r.slice(-n)}`:r}function Io(e,t,n="en",r={}){let i=z.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**Ft(i))}import{z as mt}from"zod";var Bm={plans:It,creditPacks:It,paidSeats:It,postpaid:It},wo=mt.partialRecord(mt.enum(It),mt.number().int().min(1).max(1e8)),Yc=mt.strictObject({currency:mt.enum(It),automaticTax:mt.boolean()}),Xc=mt.strictObject({projectId:mt.uuid(),environmentId:mt.uuid()}),$m=Xc.extend({settings:Yc});var eu=it.string().regex(/^[a-z][a-z0-9_]{0,63}$/),vo=it.number().int().min(0).max(1e4),Vr=it.object({key:eu,featureId:it.uuid(),planVersionId:it.uuid(),includedQuantity:vo,maximumQuantity:vo,unitAmountCents:it.number().int().min(0).max(1e8),currency:z,currencyOptions:wo.optional(),stripePriceId:it.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:it.array(it.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:it.boolean()}).strict().refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency),"Additional prices cannot repeat the default currency").refine(e=>e.maximumQuantity>=e.includedQuantity,"\u6700\u5927\u5E2D\u4F4D\u6570\u4E0D\u80FD\u5C0F\u4E8E\u5305\u542B\u5E2D\u4F4D\u6570").refine(e=>new Set(e.pooledResources).size===e.pooledResources.length,"\u5171\u4EAB\u6765\u6E90\u4E0D\u80FD\u91CD\u590D");import{z as X}from"zod";import{z as Oe}from"zod";import{z as Se}from"zod";var je=Se.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),_=Se.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),qr=Se.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Ao=_.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Zt=Se.string().regex(/^[a-z][a-z0-9_]{0,63}$/),mn=Zt,Ce=Se.record(Zt,Se.union([Se.string().max(120),Se.number().finite(),Se.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),ko=Se.record(Zt,Se.string().min(1).max(120)).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u9700\u8981 1\u20138 \u4E2A\u5C5E\u6027"),Wt=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split("."),i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},jo=Se.array(Se.object({upTo:Ao.nullable(),cost:_}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>t.upTo!==null&&(n===0||Wt(t.upTo)>Wt(e[n-1].upTo))),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),Nr=Se.object({key:Zt,match:ko,priority:Se.number().int().min(-100).max(100).default(0),cost:_.optional(),tiers:jo.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Ur=Se.object({key:Zt,match:ko,factor:_.default("1"),add:qr.default("0")}).strict(),Mr=Se.object({units:Ao.default("1"),cost:_,tiers:jo.optional(),dimensions:Se.array(Nr).max(12).optional(),multipliers:Se.array(Ur).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(a=>a.key)).size!==n.length||new Set(r.map(a=>a.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){let c=n[a],p=n[s];Object.keys(c.match).length===Object.keys(p.match).length&&c.priority===p.priority&&!Object.keys(c.match).some(u=>p.match[u]!==void 0&&p.match[u]!==c.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"})}let i=[e.cost,...(e.tiers??[]).map(a=>a.cost),...n.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(s=>s.cost)])],o=Wt(e.units);for(let a of i)for(let s=0;s<1<<r.length;s++){let c=Wt(a),p=BigInt("1"),u=BigInt("0");for(let ne=0;ne<r.length;ne++)s&1<<ne&&(c*=Wt(r[ne].factor),p*=BigInt("1000000"),u+=Wt(r[ne].add));let S=(c+u*p)*BigInt("1000000"),Q=p*o;(S<BigInt("0")||S%Q!==BigInt("0")||S/Q>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Gm=Mr.safeExtend({featureKey:Zt});var Lr=Oe.object({days:Oe.number().int().min(1).max(730),cardRequired:Oe.boolean(),featureAllowances:Oe.record(Oe.uuid(),Oe.number().int().min(0).max(1e9)),creditAmounts:Oe.record(Oe.uuid(),_)}).strict(),Gr=Oe.object({id:Oe.uuid(),planVersionId:Oe.uuid(),slot:Oe.string(),cardRequired:Oe.boolean(),status:Oe.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:Oe.iso.datetime().nullable(),endsAt:Oe.iso.datetime().nullable(),createdAt:Oe.iso.datetime()}).strict();var Kr=X.object({group:X.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:X.enum(["main","addon"]).default("main")}).strict(),tu=X.enum(["immediate","end_of_cycle"]),nu=X.enum(["attach","change","cancel","resume","cancel_change"]),Co=X.object({id:X.uuid(),subscriptionId:X.uuid().nullable(),targetPlanVersionId:X.uuid().nullable(),action:nu,timing:tu,status:X.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:X.iso.datetime().nullable(),createdAt:X.iso.datetime()}),ru=X.object({id:X.uuid(),planVersionId:X.uuid(),planId:X.uuid(),basePlanId:X.uuid().nullable(),name:X.string(),group:X.string(),kind:X.enum(["main","addon"]),source:X.enum(["subscription","assignment","license","apple","google"]),status:X.string(),accessEnabled:X.boolean(),startsAt:X.iso.datetime().nullable(),endsAt:X.iso.datetime().nullable(),cancelAtPeriodEnd:X.boolean(),scheduledChange:Co.nullable(),trial:Gr.nullable().optional()}),Ym=X.object({customerId:X.uuid(),evaluatedAt:X.iso.datetime(),holdings:X.array(ru),changes:X.array(Co),trials:X.array(Gr).optional()});import{z as Qr}from"zod";var Wr=Qr.enum(["sandbox","live"]),be=Qr.object({projectId:Qr.string().min(1),environment:Wr}).strict();var He=j.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),cp=j.record(j.string().min(1).max(80),j.union([j.string().max(500),j.number().finite(),j.boolean(),j.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),Oo=j.object({key:He,name:j.string().trim().min(1).max(80),description:j.string().trim().max(240),type:j.enum(["boolean","metered"]),usageType:j.enum(["consumable","non_consumable"]).optional()}),up=Oo.extend({...be.shape,id:j.string().min(1),archived:j.boolean(),createdAt:j.iso.datetime()}),Po=j.object({amountCents:j.number().int().min(0).max(1e8),currency:z,interval:j.enum(["free","month","year"]),currencyOptions:j.partialRecord(z,j.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C"),iu=j.object({featureId:j.string().min(1),allowance:j.number().int().min(0).max(1e9).nullable(),pooled:j.boolean().optional()}),zo=j.object({name:j.string().trim().min(1).max(80),description:j.string().trim().max(240),price:Po,membership:Kr.optional(),trial:Lr.nullable().optional(),licenses:j.array(Vr).max(20).optional(),items:j.array(iu).max(100).refine(e=>new Set(e.map(t=>t.featureId)).size===e.length,"\u540C\u4E00\u529F\u80FD\u4E0D\u80FD\u91CD\u590D\u52A0\u5165\u5957\u9910")}),lp=j.object({key:He,config:zo}),dp=be.extend({id:j.string().min(1),key:He,draft:zo,status:j.enum(["draft","published","archived"]),publishedVersionId:j.string().nullable(),isDefault:j.boolean(),updatedAt:j.iso.datetime()}),ou=Oo.pick({key:!0,name:!0,type:!0}).extend({featureId:j.string(),allowance:j.number().int().min(0).max(1e9).nullable(),pooled:j.boolean().optional()}).refine(e=>e.type==="boolean"?e.allowance===null:e.allowance!==null,"\u5F00\u5173\u578B\u65E0\u6570\u91CF\uFF0C\u8BA1\u91CF\u578B\u5FC5\u987B\u6307\u5B9A\u989D\u5EA6"),_o=be.extend({id:j.string().min(1),planId:j.string().min(1),variant:j.object({basePlanId:j.uuid(),baseVersionId:j.uuid()}).nullable(),version:j.number().int().positive(),name:j.string(),description:j.string(),price:Po,membership:Kr.optional(),trial:Lr.nullable().optional(),licenses:j.array(Vr).optional(),items:j.array(ou),publishedAt:j.iso.datetime()}).strict(),Zr=j.object({startsAt:j.iso.datetime(),endsAt:j.iso.datetime().nullable()}).refine(e=>e.endsAt===null||Date.parse(e.endsAt)>Date.parse(e.startsAt),"\u5230\u671F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u751F\u6548\u65F6\u95F4"),mp=be.extend({id:j.string(),customerId:j.string(),planVersionId:j.string(),assignedAt:j.iso.datetime(),source:j.literal("demo"),validity:Zr.nullable().default(null),used:j.record(j.string(),j.number().int().min(0))}),pp=be.extend({id:j.string(),customerId:j.string(),at:j.iso.datetime(),message:j.string()});import{z as m}from"zod";import{z as F}from"zod";import{z as f}from"zod";function Un(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function Ht(e,t,n){return n===2?Un(Un(e+t)+"")%1e4/1e4:n===1?Un(t+e)%1e3/1e3:null}function Ro(e){return e<=0?[]:new Array(e).fill(1/e)}function pn(e,t){return e>=t[0]&&e<t[1]}function Hr(e,t){let n=Ht("__"+t[0],e,1);return n===null?!1:n>=t[1]&&n<t[2]}function Jr(e,t){for(let n=0;n<t.length;n++)if(pn(e,t[n]))return n;return-1}function Yr(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=Ro(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let o=0,a=t;return n.map(s=>{let c=o;return o+=s,[c,c+a*s]})}function Xr(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let i=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>parseInt(o));return i.length>0&&i[0]>=0&&i[0]<n?i[0]:null}function ei(e){try{return e()}catch{return!1}}function Jt(e){return typeof e=="string"?e:JSON.stringify(e)}function Be(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function Mn(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function ti(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i=0;i<t.length;i++){let o=cu(e,t[i].type,t[i].pattern);if(t[i].include===!1){if(o)return!1}else n=!0,o&&(r=!0)}return r||!n}function au(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function su(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,o)=>{r.push([e.searchParams.get(o)||"",i,!1])}),!r.some(i=>!au(i[0],i[1],i[2]))}catch{return!1}}function cu(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=Mn(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return su(r,n);return!1}catch{return!1}}var Eo=new Map,ni=32,To=new WeakMap,Do=new WeakMap,Ln=e=>typeof e=="string"?e.toLowerCase():e;function qo(e){let t=To.get(e);return t||(t=new Set(e),To.set(e,t)),t}function uu(e){let t=Do.get(e);return t||(t=new Set(e.map(Ln)),Do.set(e,t)),t}function No(e){for(let t of Object.values(e)){let n=Array.isArray(t)?t:t&&t.type==="list"&&Array.isArray(t.values)?t.values:null;n&&n.length>=ni&&qo(n)}return e}function Ue(e,t,n,r){n=n||{},r=r||new Set;for(let[i,o]of Object.entries(t))switch(i){case"$or":if(!Vo(e,o,n,r))return!1;break;case"$nor":if(Vo(e,o,n,r))return!1;break;case"$and":if(!fu(e,o,n,r))return!1;break;case"$not":if(Ue(e,o,n,r))return!1;break;case"$savedGroup":if(!lu(e,o,n,r))return!1;break;default:if(!fn(o,Uo(e,i),n,!1,r))return!1}return!0}function lu(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:o}=t;if(typeof i!="string"||r.has(i)||o!==void 0&&typeof o!="string")return!1;let a=n[i];if(!a||Array.isArray(a)||typeof a!="object")return!1;let s=new Set(r).add(i);if(a.type==="list"){let c=o??a.attributeKey;return typeof c!="string"||!Array.isArray(a.values)?!1:Bt(Uo(e,c),a.values)}return a.type==="condition"?!a.condition||typeof a.condition!="object"?!1:Ue(e,a.condition,n,s):!1}function Uo(e,t){let n=t.split("."),r=e;for(let i=0;i<n.length;i++)if(r&&typeof r=="object"&&n[i]in r)r=r[n[i]];else return null;return r}function Fo(e,t=!1){let n=`${e}${t?"/i":""}`,r=Eo.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Eo.set(n,r)),r}function fn(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!Mo(e))return JSON.stringify(t)===JSON.stringify(e);let o=e;for(let a in o)if(!pu(a,t,o[a],n,i))return!1;return!0}function Mo(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function du(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function mu(e,t,n,r){if(!Array.isArray(e))return!1;let i=Mo(t)?o=>fn(t,o,n,!1,r):o=>Ue(o,t,n,r);for(let o=0;o<e.length;o++)if((e[o]??null)!==null&&i(e[o]))return!0;return!1}function Bt(e,t,n=!1){if(n){let i;if(t.length>=ni){let o=uu(t);i=a=>{let s=Ln(a);return!(typeof s=="number"&&Number.isNaN(s))&&o.has(s)}}else i=o=>t.some(a=>Ln(o)===Ln(a));return Array.isArray(e)?e.some(o=>i(o)):i(e)}let r=t.length>=ni?(i=>o=>i.has(o))(qo(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Bo(e){return e===void 0?[]:Array.isArray(e)?e:e&&typeof e=="object"&&e.type==="list"&&Array.isArray(e.values)?e.values:null}function $o(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let o=0;o<t.length;o++){let a=!1;for(let s=0;s<e.length;s++)if(fn(t[o],e[s],n,r,i)){a=!0;break}if(!a)return!1}return!0}function pu(e,t,n,r,i=new Set){let o=t,a=n;switch(e){case"$veq":return Be(t)===Be(n);case"$vne":return Be(t)!==Be(n);case"$vgt":return Be(t)>Be(n);case"$vgte":return Be(t)>=Be(n);case"$vlt":return Be(t)<Be(n);case"$vlte":return Be(t)<=Be(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return o<a;case"$lte":return o<=a;case"$gt":return o>a;case"$gte":return o>=a;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?Bt(t,n):!1;case"$ini":return Array.isArray(n)?Bt(t,n,!0):!1;case"$inGroup":{let s=Bo(r[n]);return s===null?!1:Bt(t,s)}case"$notInGroup":{let s=Bo(r[n]);return s===null?!1:!Bt(t,s)}case"$nin":return Array.isArray(n)?!Bt(t,n):!1;case"$nini":return Array.isArray(n)?!Bt(t,n,!0):!1;case"$not":return!fn(n,t,r,!1,i);case"$size":return Array.isArray(t)?fn(n,t.length,r,!1,i):!1;case"$elemMatch":return mu(t,n,r,i);case"$all":return Array.isArray(n)?$o(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?$o(t,n,r,!0,i):!1;case"$regex":try{return Fo(n).test(t)}catch{return!1}case"$regexi":try{return Fo(n,!0).test(t)}catch{return!1}case"$type":return du(t)===n;default:return!1}}function Vo(e,t,n,r){if(!t.length)return!0;for(let i=0;i<t.length;i++)if(Ue(e,t[i],n,r))return!0;return!1}function fu(e,t,n,r){for(let i=0;i<t.length;i++)if(!Ue(e,t[i],n,r))return!1;return!0}function ri(e){return{context:e,stack:{evaluatedFeatures:new Set}}}function Gn(e){return{...e.attributes,...e.attributeOverrides}}function pt(e,t,n){let r=t||"id",i="",o=Gn(e);return o[r]&&(i=o[r]),!i&&n&&(o[n]&&(i=o[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function J(e,t,n){e.context.log?.(t,n)}function gn(e,t){return t=t||0,`${e}__${t}`}function Kn(e,t){return`${e}||${t}`}function gu(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:o}=pt(e,t),a=Kn(i,Jt(o)),{hashAttribute:s,hashValue:c}=pt(e,n),p=c?Kn(s,Jt(c)):null,u={};return p&&r[p]&&Object.assign(u,r[p].assignments||{}),r[a]&&Object.assign(u,r[a].assignments||{}),u}function ii({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:o,expMeta:a}){n=n||0,o=o||0,r=r||"id",a=a||[];let s=gn(t,n),c=gu(e,r,i);if(o>0)for(let S=0;S<o;S++){let Q=gn(t,S);if(c[Q]!==void 0)return{variation:-1,versionIsBlocked:!0}}let p=c[s];if(p===void 0)return{variation:-1};let u=a.findIndex(S=>S.key===p);return u<0?{variation:-1}:{variation:u}}function oi(e,t,n,r){let i=Kn(t,n),o=e.stickyBucketAssignmentDocs,a=o&&o[i]?o[i].assignments||{}:{},s={...a,...r},c=JSON.stringify(a)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function Lo(e,t){let n=ri(t),r=Qo(e,null,n);return t.onExperimentEval?.(e,r),r}function Go(e,t){return si(e,ri(t))}function hu(e){return e.forcedVariations||{}}function Ko(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=Ho(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}ai(()=>r.onExperimentViewed?.(t,n))}function bu(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}ai(()=>r.onFeatureUsage?.(t,n))}function ai(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function si(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return J(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),wt(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.forcedFeatureValues;if(r&&r.has(e))return J(t,"Global override",{id:e,value:r.get(e)}),wt(t,e,r.get(e),"override");if(!n.features||!n.features[e])return J(t,"Unknown feature",{id:e}),wt(t,e,null,"unknownFeature");let i=n.features[e];if(i.rules){let o=new Set(t.stack.evaluatedFeatures);e:for(let a of i.rules){if(a.parentConditions)for(let p of a.parentConditions){t.stack.evaluatedFeatures=new Set(o);let u=si(p.id,t);if(u.source==="cyclicPrerequisite")return wt(t,e,null,"cyclicPrerequisite");let S={value:u.value};if(!Ue(S,p.condition||{},n.savedGroups||{})){if(p.gate)return J(t,"Feature blocked by prerequisite",{id:e,rule:a}),wt(t,e,null,"prerequisite");J(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:a});continue e}}if(a.filters&&Zo(a.filters,t)){J(t,"Skip rule because of filters",{id:e,rule:a});continue}if("force"in a){if(a.condition&&!Wo(a.condition,t)){J(t,"Skip rule because of condition ff",{id:e,rule:a});continue}if(!yu(t,a.seed||e,a.hashAttribute,n.saveStickyBucketAssignmentDoc&&!a.disableStickyBucketing?a.fallbackAttribute:void 0,a.range,a.coverage,a.hashVersion)){J(t,"Skip rule because user not included in rollout",{id:e,rule:a});continue}return J(t,"Force value from rule",{id:e,rule:a}),a.tracks&&a.tracks.forEach(p=>{Ko(t,p.experiment,p.result)}),wt(t,e,a.force,"force",a.id)}if(!a.variations){J(t,"Skip invalid rule",{id:e,rule:a});continue}let s={variations:a.variations,key:a.key||e};"coverage"in a&&(s.coverage=a.coverage),a.weights&&(s.weights=a.weights),a.hashAttribute&&(s.hashAttribute=a.hashAttribute),a.fallbackAttribute&&(s.fallbackAttribute=a.fallbackAttribute),a.disableStickyBucketing&&(s.disableStickyBucketing=a.disableStickyBucketing),a.bucketVersion!==void 0&&(s.bucketVersion=a.bucketVersion),a.minBucketVersion!==void 0&&(s.minBucketVersion=a.minBucketVersion),a.namespace&&(s.namespace=a.namespace),a.meta&&(s.meta=a.meta),a.ranges&&(s.ranges=a.ranges),a.name&&(s.name=a.name),a.phase&&(s.phase=a.phase),a.seed&&(s.seed=a.seed),a.hashVersion&&(s.hashVersion=a.hashVersion),a.filters&&(s.filters=a.filters),a.condition&&(s.condition=a.condition);let c=Qo(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return wt(t,e,c.value,"experiment",a.id,s,c)}}return J(t,"Use default value",{id:e,value:i.defaultValue}),wt(t,e,i.defaultValue===void 0?null:i.defaultValue,"defaultValue")}function Qo(e,t,n){let{context:r}=n,i=e.key,o=e.variations.length;if(o<2)return J(n,"Invalid experiment",{id:i}),pe(n,e,-1,!1,t);if(r.enabled===!1)return J(n,"Context disabled",{id:i}),pe(n,e,-1,!1,t);if(e=xu(e,r),e.urlPatterns&&!ti(r.url||"",e.urlPatterns))return J(n,"Skip because of url targeting",{id:i}),pe(n,e,-1,!1,t);let a=Xr(i,r.url||"",o);if(a!==null)return J(n,"Force via querystring",{id:i,variation:a}),pe(n,e,a,!1,t);let s=hu(r);if(i in s){let he=s[i];return J(n,"Force via dev tools",{id:i,variation:he}),pe(n,e,he,!1,t)}if(e.status==="draft"||e.active===!1)return J(n,"Skip because inactive",{id:i}),pe(n,e,-1,!1,t);let{hashAttribute:c,hashValue:p}=pt(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!p)return J(n,"Skip because missing hashAttribute",{id:i}),pe(n,e,-1,!1,t);let u=-1,S=!1,Q=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:he,versionIsBlocked:rt}=ii({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta});S=he>=0,u=he,Q=!!rt}if(!S){if(e.filters){if(Zo(e.filters,n))return J(n,"Skip because of filters",{id:i}),pe(n,e,-1,!1,t)}else if(e.namespace&&!Hr(p,e.namespace))return J(n,"Skip because of namespace",{id:i}),pe(n,e,-1,!1,t);if(e.include&&!ei(e.include))return J(n,"Skip because of include function",{id:i}),pe(n,e,-1,!1,t);if(e.condition&&!Wo(e.condition,n))return J(n,"Skip because of condition exp",{id:i}),pe(n,e,-1,!1,t);if(e.parentConditions){let he=new Set(n.stack.evaluatedFeatures);for(let rt of e.parentConditions){n.stack.evaluatedFeatures=new Set(he);let dt=si(rt.id,n);if(dt.source==="cyclicPrerequisite")return pe(n,e,-1,!1,t);let xe={value:dt.value};if(!Ue(xe,rt.condition||{},r.savedGroups||{}))return J(n,"Skip because prerequisite evaluation fails",{id:i}),pe(n,e,-1,!1,t)}}if(e.groups&&!Iu(e.groups,r))return J(n,"Skip because of groups",{id:i}),pe(n,e,-1,!1,t)}if(e.url&&!Su(e.url,r))return J(n,"Skip because of url",{id:i}),pe(n,e,-1,!1,t);let ne=Ht(e.seed||i,p,e.hashVersion||1);if(ne===null)return J(n,"Skip because of invalid hash version",{id:i}),pe(n,e,-1,!1,t);if(!S){let he=e.ranges||Yr(o,e.coverage===void 0?1:e.coverage,e.weights);u=Jr(ne,he)}if(Q)return J(n,"Skip because sticky bucket version is blocked",{id:i}),pe(n,e,-1,!1,t,void 0,!0);if(u<0)return J(n,"Skip because of coverage",{id:i}),pe(n,e,-1,!1,t);if("force"in e)return J(n,"Force variation",{id:i,variation:e.force}),pe(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return J(n,"Skip because QA mode",{id:i}),pe(n,e,-1,!1,t);if(e.status==="stopped")return J(n,"Skip because stopped",{id:i}),pe(n,e,-1,!1,t);let ke=pe(n,e,u,!0,t,ne,S);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:he,key:rt,doc:dt}=oi(r,c,Jt(p),{[gn(e.key,e.bucketVersion)]:ke.key});if(he){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[rt]=dt;let xe=r.saveStickyBucketAssignmentDoc;ai(()=>xe(dt))}}return Ko(n,e,ke),J(n,"In experiment",{id:i,variation:ke.variationId}),ke}function wt(e,t,n,r,i,o,a){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return o&&(s.experiment=o),a&&(s.experimentResult=a),r!=="override"&&bu(e,t,s),s}function Wo(e,t){return Ue(Gn(t.context),e,t.context.savedGroups||{})}function Zo(e,t){return e.some(n=>{let{hashValue:r}=pt(t.context,n.attribute);if(!r)return!0;let i=Ht(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(o=>pn(i,o))})}function yu(e,t,n,r,i,o,a){if(!i&&o===void 0)return!0;if(!i&&o===0)return!1;let{hashValue:s}=pt(e.context,n,r);if(!s)return!1;let c=Ht(t,s,a||1);return c===null?!1:i?pn(c,i):o!==void 0?c<=o:!0}function pe(e,t,n,r,i,o,a){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:p}=pt(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),u=t.meta?t.meta[n]:{},S={key:u.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:t.variations[n],hashAttribute:c,hashValue:p,stickyBucketUsed:!!a};return u.name&&(S.name=u.name),o!==void 0&&(S.bucket=o),u.passthrough&&(S.passthrough=u.passthrough),S}function xu(e,t){let n=e.key,r=t.overrides;if(r&&r[n]){let i=Object.assign({},e,r[n]);typeof i.url=="string"&&(i.url=Mn(i.url)),e=i}return e}function Su(e,t){let n=t.url;if(!n)return!1;let r=n.replace(/^https?:\/\//,"").replace(/^[^/]*\//,"/");return!!(e.test(n)||e.test(r))}function Iu(e,t){let n=t.groups||{};for(let r=0;r<e.length;r++)if(n[e[r]])return!0;return!1}function Ho(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
-
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
-
|
|
4
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
-
furnished to do so, subject to the following conditions:
|
|
6
|
-
|
|
7
|
-
The above copyright notice and this permission notice shall be included in all
|
|
8
|
-
copies or substantial portions of the Software.
|
|
9
|
-
|
|
10
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
-
SOFTWARE.
|
|
17
|
-
*/var Me=f.json().superRefine((e,t)=>{let n=0;function r(i,o){if(++n>1e4||o>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(a=>r(a,o+1));else if(i&&typeof i=="object")for(let[a,s]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,o+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Je=f.record(f.string().min(1).max(128),Me).superRefine((e,t)=>{(!Me.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"})}),wu=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"]),ot=Je.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r)){if(i==="$savedGroup"&&!f.strictObject({id:f.uuid(),attributeKey:f.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!wu.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(o)}}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)}),Wn=f.discriminatedUnion("type",[f.strictObject({type:f.literal("condition"),condition:ot}),f.strictObject({type:f.literal("list"),attributeKey:f.string().min(1).max(128),values:f.array(f.union([f.string(),f.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 vu(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(o)}return n(e),[...t]}var Jo=f.record(f.uuid(),Wn).superRefine((e,t)=>{let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(o),a.type==="condition"&&vu(a.condition).forEach(i),n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),hn=f.tuple([f.number().min(0).max(1),f.number().min(0).max(1)]).refine(([e,t])=>e<=t),Yo=f.strictObject({attribute:f.string().optional(),seed:f.string().min(1),hashVersion:f.literal(2),ranges:f.array(hn).min(1).max(100)}),Au=f.strictObject({id:f.string().min(1).max(128),condition:ot,gate:f.boolean().optional()}),Qn={id:f.string().max(128).optional(),condition:ot.optional(),parentConditions:f.array(Au).max(50).optional(),filters:f.array(Yo).max(20).optional()},ku=f.union([f.strictObject({...Qn}),f.strictObject({...Qn,force:Me,coverage:f.number().min(0).max(1).optional(),range:hn.optional(),seed:f.string().min(1).optional(),hashAttribute:f.string().optional(),hashVersion:f.literal(2).optional()}),f.strictObject({...Qn,type:f.literal("experiment-ref"),experimentId:f.uuid(),values:f.record(f.string().min(1),Me),meta:f.record(f.string().min(1),f.strictObject({passthrough:f.boolean()})).optional()})]),ju=f.strictObject({defaultValue:Me,rules:f.array(ku).max(100)}),Zn=f.record(f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ju).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(o){if(n.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}n.add(o);for(let s of a.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),Cu=f.strictObject({name:f.string().max(80),reason:f.string().max(500),dateStarted:f.iso.datetime({offset:!0}),dateEnded:f.iso.datetime({offset:!0}).nullable(),coverage:f.number().min(0).max(1),variationWeights:f.array(f.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:ot,savedGroups:f.array(f.strictObject({match:f.enum(["any","all","none"]),ids:f.array(f.uuid()).min(1)})).max(50),namespace:f.strictObject({id:f.uuid(),ranges:f.array(hn).min(1)}).nullable(),seed:f.string().min(1).max(128)}),Yt=f.strictObject({key:f.string().min(1).max(128),name:f.string().min(1).max(80),hypothesis:f.string().max(2e3),status:f.enum(["draft","running","stopped"]),hashAttribute:f.string().min(1).max(128),fallbackAttribute:f.string().max(128).nullable(),hashVersion:f.literal(2),disableStickyBucketing:f.boolean(),bucketVersion:f.number().int().min(0).max(1e3),minBucketVersion:f.number().int().min(0).max(1e3),variations:f.array(f.strictObject({id:f.string().min(1),key:f.string().min(1),name:f.string().max(80),description:f.string().max(500)})).min(2).max(20),phases:f.array(Cu).min(1).max(100),releasedVariationId:f.string().nullable(),excludeFromPayload:f.boolean(),statusSchedule:f.strictObject({startAt:f.iso.datetime({offset:!0}).nullable(),stopAt:f.iso.datetime({offset:!0}).nullable(),stopAfter:f.strictObject({value:f.number().int().positive().max(36500),unit:f.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>r>0&&(Date.parse(n.dateStarted)<Date.parse(e.phases[r-1].dateStarted)||!e.phases[r-1].dateEnded||Date.parse(e.phases[r-1].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],o,a)=>r>=i||a.some(([s,c],p)=>p!==o&&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"})});function qp(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{defaultValue:i.defaultValue,rules:i.rules.flatMap(o=>{if(!("experimentId"in o))return[{...o,hashVersion:2}];let a=t[o.experimentId];if(!a)throw new Error(`Missing experiment: ${o.experimentId}`);let s=a.phases[a.phases.length-1],c=a.statusSchedule?.startAt?Date.parse(a.statusSchedule.startAt):null,p=Xo(a),u=a.status!=="stopped"&&(a.status==="running"||c!==null&&n>=c)&&(c===null||n>=c)&&(p===null||n<p),{type:S,experimentId:Q,values:ne,meta:ke,...he}=o;if(a.variations.some(xe=>!Object.hasOwn(ne,xe.key))||Object.keys(ne).length!==a.variations.length||Object.keys(ke??{}).some(xe=>!a.variations.some(dn=>dn.key===xe)))throw new Error("Every variation needs a Feature value");let rt={$and:[s.condition,...he.condition?[he.condition]:[],...s.savedGroups.map(xe=>{let dn=xe.ids.map(Wc=>({$savedGroup:{id:Wc}}));return xe.match==="all"?{$and:dn}:xe.match==="none"?{$nor:dn}:{$or:dn}})]},dt=a.variations.find(xe=>xe.id===a.releasedVariationId);return dt&&!a.excludeFromPayload?ke?.[dt.key]?.passthrough?[{...he,condition:rt}]:[{...he,condition:rt,force:ne[dt.key]}]:[{...he,condition:rt,key:a.key,variations:a.variations.map(xe=>ne[xe.key]),meta:a.variations.map(xe=>({key:xe.key,name:xe.name,...ke?.[xe.key]})),weights:s.variationWeights,coverage:u?s.coverage:0,seed:s.seed,hashVersion:2,hashAttribute:a.hashAttribute,fallbackAttribute:a.fallbackAttribute??void 0,disableStickyBucketing:!u||a.disableStickyBucketing,bucketVersion:a.bucketVersion,minBucketVersion:a.minBucketVersion,filters:[...he.filters??[],...a.filters??[]]}]})}]))}function Xo(e){if(e.statusSchedule?.stopAt)return Date.parse(e.statusSchedule.stopAt);let t=e.statusSchedule?.stopAfter;return!t||e.status==="draft"&&!e.statusSchedule?.startAt?null:Date.parse(e.statusSchedule?.startAt??e.phases[e.phases.length-1].dateStarted)+t.value*(t.unit==="days"?864e5:36e5)}function Np(e,t=Date.now()){let n=Object.values(e).filter(r=>r.status!=="stopped"&&!(r.releasedVariationId&&!r.excludeFromPayload)).flatMap(r=>[r.statusSchedule?.startAt?Date.parse(r.statusSchedule.startAt):null,Xo(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var Ou=f.strictObject({...Qn,force:Me.optional(),variations:f.array(Me).min(2).max(20).optional(),weights:f.array(f.number().min(0).max(1)).optional(),key:f.string().optional(),hashAttribute:f.string().optional(),fallbackAttribute:f.string().optional(),hashVersion:f.literal(2).optional(),disableStickyBucketing:f.boolean().optional(),bucketVersion:f.number().int().min(0).max(1e3).optional(),minBucketVersion:f.number().int().min(0).max(1e3).optional(),coverage:f.number().min(0).max(1).optional(),seed:f.string().optional(),range:hn.optional(),ranges:f.array(hn).optional(),meta:f.array(f.strictObject({key:f.string(),name:f.string().optional(),passthrough:f.boolean().optional()})).optional(),name:f.string().optional(),phase:f.string().optional()}),Up=f.strictObject({scope:f.strictObject({projectId:f.uuid(),environment:f.enum(["sandbox","live"])}),funnelId:f.uuid(),versionId:f.uuid(),expiresAt:f.iso.datetime({offset:!0}).nullable(),features:f.record(f.string(),f.strictObject({defaultValue:Me,rules:f.array(Ou)})),savedGroups:Jo}),ci=Yt.safeExtend({filters:f.array(Yo).optional()}),ui=f.strictObject({experiments:f.record(f.uuid(),ci),savedGroups:Jo}),Pu=f.strictObject({attributeName:f.string(),attributeValue:f.string(),assignments:f.record(f.string(),f.string())}),Mp=f.strictObject({snapshot:ui,attributes:Je,results:Je,stickyBucketAssignmentDocs:f.record(f.string(),Pu)}),Lp=f.strictObject({variantKey:f.string().nullable(),bucketVersion:f.number().int().min(0),source:f.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:f.number().min(0).max(1).optional(),stickyBucketUsed:f.boolean().optional(),hashUsed:f.boolean().optional()});import{z as zu}from"zod";var ta=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,ft=zu.string().max(16).regex(ta,"\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");function $t(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:r,region:i}=new Intl.Locale(t),o=[n,r,i].filter(Boolean).join("-");return ta.test(o)?o:null}catch{return null}}var _u=new Set(["TW","HK","MO"]);function ea(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,o=n?.length===4?r:n;return i?`zh-${i}`:o&&_u.has(o)?"zh-Hant":"zh-Hans"}function Hn(e,t,n){let r=t.map(i=>({code:ft.parse(i),normalized:i}));for(let i of e){let o=$t(i);if(!o)continue;let a=r.find(p=>p.normalized===o);if(a)return a.code;let s=ea(o),c=r.filter(p=>ea(p.normalized)===s);if(c.length>0)return(c.find(p=>!p.normalized.includes("-")||p.normalized===s)??c[0]).code}return n}var Ru=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function Qp(e){return Ru.find(t=>t.code===e)?.label??e}var li={"zh-Hans":{once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{once:"\u521D\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15",repeating:"\u6700\u521D\u306E {months} \u304B\u6708\u9593\u3001\u6BCE\u6708 {discount} \u5272\u5F15",forever:"\u6BCE\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15"},ko:{once:"\uCCAB \uACB0\uC81C {discount} \uD560\uC778",repeating:"\uCCAB {months}\uAC1C\uC6D4 \uB3D9\uC548 \uB9E4\uC6D4 {discount} \uD560\uC778",forever:"\uB9E4 \uACB0\uC81C {discount} \uD560\uC778"},es:{once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{once:"{discount} de r\xE9duction sur le premier paiement",repeating:"{discount} de r\xE9duction par mois pendant les {months} premiers mois",forever:"{discount} de r\xE9duction sur chaque paiement",repeatingOne:"{discount} de r\xE9duction pendant le premier mois"},de:{once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat f\xFCr die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por m\xEAs nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro m\xEAs"},it:{once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{once:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043F\u0435\u0440\u0432\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436",repeating:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043A\u0430\u0436\u0434\u044B\u0439 \u043C\u0435\u0441\u044F\u0446 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",repeatingOne:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u0432 \u043F\u0435\u0440\u0432\u044B\u0439 \u043C\u0435\u0441\u044F\u0446",forever:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043A\u0430\u0436\u0434\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436"},vi:{once:"Gi\u1EA3m {discount} cho l\u1EA7n thanh to\xE1n \u0111\u1EA7u ti\xEAn",repeating:"Gi\u1EA3m {discount} m\u1ED7i th\xE1ng trong {months} th\xE1ng \u0111\u1EA7u",forever:"Gi\u1EA3m {discount} cho m\u1ED7i l\u1EA7n thanh to\xE1n"},th:{once:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01",repeating:"\u0E25\u0E14 {discount} \u0E15\u0E48\u0E2D\u0E40\u0E14\u0E37\u0E2D\u0E19\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",forever:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E17\u0E38\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07"},id:{once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{once:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u062F\u0641\u0639\u0629 \u0627\u0644\u0623\u0648\u0644\u0649",repeating:"\u062E\u0635\u0645 {discount} \u0634\u0647\u0631\u064A\u064B\u0627 \u0644\u0645\u062F\u0629 {period}",forever:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0643\u0644 \u062F\u0641\u0639\u0629"}},Jp=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function di(e){let t=$t(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(i=>["TW","HK","MO"].includes(i))?"zh-Hant":"zh-Hans":n[0];return li[r]?{locale:t,copy:li[r]}:{locale:"en",copy:li.en}}function Eu(e,t,n="zh-CN"){let r=Ft(t);return Io(e,t,di(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function Tu(e,t="zh-CN"){let n=di(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):Eu(e.amountOffCents,e.currency,n)}var na={zh:"\u524D {months} \u4E2A\u6708\u5185\u5F00\u51FA\u7684\u8D26\u5355\u51CF {discount}","zh-Hant":"\u524D {months} \u500B\u6708\u5167\u958B\u51FA\u7684\u5E33\u55AE\u6E1B {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"\u6700\u521D\u306E {months} \u304B\u6708\u4EE5\u5185\u306E\u8ACB\u6C42\u304C {discount} \u5272\u5F15",ko:"\uCCAB {months}\uAC1C\uC6D4 \uB0B4 \uCCAD\uAD6C\uC11C {discount} \uD560\uC778",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de r\xE9duction sur les factures \xE9mises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u0441\u0447\u0435\u0442\u0430 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",vi:"Gi\u1EA3m {discount} cho h\xF3a \u0111\u01A1n trong {months} th\xE1ng \u0111\u1EA7u",th:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E1A\u0E41\u0E08\u0E49\u0E07\u0E2B\u0E19\u0E35\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u0641\u0648\u0627\u062A\u064A\u0631 \u0627\u0644\u0635\u0627\u062F\u0631\u0629 \u062E\u0644\u0627\u0644 \u0623\u0648\u0644 {period}"};function ra(e,t="zh-CN",n="month"){let r=di(t),i=Tu(e.discount,r.locale),o=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0],s=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,c=e.duration.type==="repeating"&&n!=="month"?na[s]??na.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],p=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",o).replace("{period}",p)}var rf=F.enum(["draft","active","paused","archived"]),Xt=F.discriminatedUnion("type",[F.object({type:F.literal("percent"),percentOff:F.number().int().min(1).max(100)}).strict(),F.object({type:F.literal("amount"),amountOffCents:F.number().int().min(1).max(1e8),currency:z}).strict()]),at=F.discriminatedUnion("type",[F.object({type:F.literal("once")}).strict(),F.object({type:F.literal("repeating"),months:F.number().int().min(1).max(36)}).strict(),F.object({type:F.literal("forever")}).strict()]),ia=F.discriminatedUnion("type",[F.object({type:F.literal("all")}).strict(),F.object({type:F.literal("plans"),planIds:F.array(F.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),Du=F.strictObject({firstPurchaseOnly:F.boolean(),condition:ot}),oa=F.object({name:F.string().trim().min(1).max(80),description:F.string().max(500),discount:Xt,duration:at,appliesTo:ia,eligibility:Du,startsAt:F.iso.datetime().nullable(),endsAt:F.iso.datetime().nullable(),totalLimit:F.number().int().min(1).max(1e6).nullable(),perCustomerLimit:F.number().int().min(1).max(10),grantWindowHours:F.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"]}),of=F.object({code:F.string().trim().transform(e=>e.toUpperCase()).pipe(F.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:F.number().int().min(1).max(1e6).nullable(),expiresAt:F.iso.datetime().nullable(),firstPurchaseOnly:F.boolean(),minimumAmountCents:F.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:z.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function af(){return{name:"\u65B0\u4F18\u60E0\u5238",description:"",discount:{type:"percent",percentOff:20},duration:{type:"once"},appliesTo:{type:"all"},eligibility:{firstPurchaseOnly:!1,condition:{}},startsAt:null,endsAt:null,totalLimit:null,perCustomerLimit:1,grantWindowHours:72}}var mi=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function sf(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return mi(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),mi(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),mi(t.appliesTo,n.appliesTo)||r.push({field:"appliesTo",reason:"immutable"}),t.startsAt!==n.startsAt&&r.push({field:"startsAt",reason:"immutable"}),t.endsAt!==n.endsAt&&(n.endsAt===null||t.endsAt!==null&&Date.parse(n.endsAt)>Date.parse(t.endsAt))&&r.push({field:"endsAt",reason:"only_earlier"}),t.totalLimit!==n.totalLimit&&(n.totalLimit===null||t.totalLimit!==null&&n.totalLimit>t.totalLimit)&&r.push({field:"totalLimit",reason:"only_reduce"}),n.perCustomerLimit>t.perCustomerLimit&&r.push({field:"perCustomerLimit",reason:"only_reduce"}),r}var Fu=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function cf(e,t="zh-CN"){return ra(e,t)}function uf(e){return Fu(e)}function lf(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var pi=F.object({id:F.uuid(),couponId:F.uuid(),status:F.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:F.iso.datetime(),expiresAt:F.iso.datetime(),coupon:F.object({name:F.string(),discount:Xt,duration:at,appliesTo:ia}).strict()}).strict(),Jn=F.enum(["inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var ua=m.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),en=m.string().regex(/^(0|[1-9]\d{0,14})$/),tn=m.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Bu=m.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),bn=Bu,qt=_.refine(e=>/[1-9]/.test(e)),$e=m.iso.datetime({offset:!0}),Vt=e=>{let[t,n=""]=e.split(".");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},$u=m.array(m.object({upTo:qt.nullable(),unitAmountMinor:ua,flatAmountMinor:m.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)=>t.upTo!==null&&(n===0||Vt(t.upTo)>Vt(e[n-1].upTo)))}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Vu=m.discriminatedUnion("kind",[m.object({kind:m.literal("flat"),units:qt,unitAmountMinor:ua}).strict(),m.object({kind:m.enum(["graduated","volume"]),units:qt,tiers:$u}).strict()]),qu=m.strictObject({interval:m.enum(["month","year"]),count:m.number().int().min(1).max(12),anchor:m.enum(["membership","calendar"])}),vt=m.object({currency:z,pricing:Vu,billingCycle:qu.optional()}).strict().refine(e=>e.pricing.kind!=="volume","Volume tiers require prepaid billing");function la(e){return e.pricing.kind==="flat"&&Vt(e.pricing.units)>0n&&Vt(e.pricing.unitAmountMinor)===Vt(e.pricing.units)*BigInt(10**Ft(e.currency))}var aa={requestId:m.uuid(),productVersionId:m.uuid(),entitlementVersionId:m.uuid(),currency:z,maxAmountMinorPerPeriod:bn},da=m.strictObject({hour:m.number().int().min(1).max(1e3).optional(),week:m.number().int().min(1).max(1e3).optional(),month:m.number().int().min(1).max(1e3).optional()}).refine(e=>Object.keys(e).length>0,"Specify a purchase window"),nn=m.discriminatedUnion("kind",[m.object({...aa,kind:m.literal("auto_topup"),threshold:_,maxPurchasesPerDay:m.number().int().min(1).max(1e3),purchaseLimits:da.optional()}).strict(),m.object({...aa,kind:m.literal("postpaid"),maxOutstandingMinor:bn}).strict()]),sa={productVersionId:m.uuid(),entitlementVersionId:m.uuid(),currency:z,maxAmountMinorPerPeriod:bn},Yn=m.discriminatedUnion("kind",[m.object({...sa,kind:m.literal("auto_topup"),threshold:_,maxPurchasesPerDay:m.number().int().min(1).max(1e3),purchaseLimits:da.optional(),purchaseAmountMinor:bn,purchaseUnits:qt}).strict(),m.object({...sa,kind:m.literal("postpaid"),maxOutstandingMinor:bn,cashPrice:vt}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Xn=m.object({id:m.uuid(),terms:Yn,status:m.enum(["prepared","active","revoked","blocked"]),createdAt:$e,acceptedAt:$e.nullable(),effectiveAt:$e.nullable(),revokedAt:$e.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"),ma=m.object({authorizationId:m.uuid(),terms:Yn,setupUrl:m.url().nullable()}).strict(),pa=m.object({authorizationId:m.uuid(),accepted:m.literal(!0)}).strict(),fa=m.object({authorizationId:m.uuid(),requestId:m.uuid()}).strict(),ga=m.object({entitlementId:m.uuid(),entityId:m.uuid().nullable(),interval:m.enum(["day","week","month","year"]),basis:m.enum(["usage","credits"]),filter:Ce.optional(),revision:m.number().int().nonnegative(),limit:_.nullable(),thresholds:m.array(m.number().positive().max(1)).max(8),includedThresholds:m.array(m.number().positive().max(1)).max(8).optional(),absoluteThresholds:m.array(qt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>n===0||t>e.thresholds[n-1])&&(e.includedThresholds??[]).every((t,n,r)=>n===0||t>r[n-1])&&(e.absoluteThresholds??[]).every((t,n,r)=>n===0||Vt(t)>Vt(r[n-1])),"Notification thresholds must increase"),Nu=ga.safeExtend({requestId:m.uuid()}),ca={control:m.literal("overage"),requestId:m.uuid(),entitlementId:m.uuid(),entityId:m.uuid().nullable(),revision:m.number().int().min(0).max(Number.MAX_SAFE_INTEGER)},Uu=m.discriminatedUnion("action",[m.strictObject({...ca,action:m.literal("set"),allowed:m.boolean().nullable(),overageLimit:_.nullable(),skipOverageBilling:m.boolean(),interval:m.enum(["day","week","month","year"])}),m.strictObject({...ca,action:m.literal("remove")})]),ha=m.union([Nu,Uu]),Mu=m.strictObject({entitlementId:m.uuid(),entityId:m.uuid().nullable(),allowed:m.boolean().nullable(),overageLimit:_.nullable(),skipOverageBilling:m.boolean(),interval:m.enum(["day","week","month","year"]),revision:m.number().int().min(1).max(Number.MAX_SAFE_INTEGER),startsAt:$e,endsAt:$e,used:m.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:m.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:m.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Lu=m.object({entitlementId:m.uuid(),entityId:m.uuid().nullable(),interval:m.enum(["day","week","month","year"]),basis:m.enum(["usage","credits"]),filter:Ce.optional(),revision:m.number().int().nonnegative(),startsAt:$e,endsAt:$e,used:je,reserved:je,limit:_.nullable(),thresholds:m.array(m.number().positive().max(1)).max(8),notifiedThresholds:m.array(m.number().positive().max(1)).max(1024),includedThresholds:m.array(m.number().positive().max(1)).max(8).optional(),includedAllowance:m.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:m.array(m.number().positive().max(1)).max(1024).optional(),absoluteThresholds:m.array(qt).max(8).optional(),notifiedAbsoluteThresholds:m.array(qt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||_.safeParse(e.used).success&&_.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Gu=m.object({authorizationId:m.uuid(),status:m.enum(["idle","pending","blocked"]),orderId:m.uuid().nullable(),hostedInvoiceUrl:m.url().nullable(),purchasesToday:m.number().int().min(0),amountMinorThisMonth:en,nextAttemptAt:$e.nullable(),failureReason:m.string().min(1).max(240).nullable()}).strict(),ba=m.object({entitlementId:m.uuid().optional(),entityId:m.uuid().optional()}).strict(),fi=m.object({authorizations:m.array(Xn).max(100),revision:m.number().int().nonnegative(),limits:m.array(ga).max(100),overages:m.array(Mu).max(100).optional(),windows:m.array(Lu).max(200),autoTopups:m.array(Gu).max(100),limited:m.boolean()}).strict(),Ku=m.object({id:m.uuid(),entitlementId:m.uuid(),entitlementVersionId:m.uuid(),productVersionId:m.uuid(),authorizationId:m.uuid(),entityId:m.uuid().nullable(),units:_,amountMinor:tn,cashPrice:vt}).strict(),yn=m.object({id:m.uuid(),sourceKind:m.enum(["product","usage"]),providerInvoiceId:m.string().min(1).max(240).nullable(),status:m.enum(["accruing","open","pending","paid","failed","void"]),currency:z,startsAt:$e,endsAt:$e,amountMinor:en,grossAmountMinor:en,discountMinor:en,paidAmountMinor:en,refundedAmountMinor:en,createdAt:$e,hostedInvoiceUrl:m.url().nullable(),adjustment:m.object({originalInvoiceId:m.uuid(),amountMinor:m.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:$e.nullable()}).strict().nullable(),lines:m.array(Ku).max(100),linesLimited:m.boolean()}).strict(),ya=m.object({invoiceId:m.uuid(),accepted:m.literal(!0)}).strict(),xa=m.object({after:m.uuid().nullable(),limit:m.number().int().min(1).max(100)}).strict(),Sa=m.object({rows:m.array(yn).max(100),nextCursor:m.uuid().nullable()}).strict(),Ia=m.strictObject({authorizationId:m.uuid(),requestId:m.uuid(),grantIds:m.array(m.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),wa=m.strictObject({authorizationId:m.uuid(),grants:m.array(m.strictObject({id:m.uuid(),couponId:m.uuid(),name:m.string(),discount:Xt,duration:at,startedAt:$e.nullable()})).max(20)});import{z as xn}from"zod";var Sn=xn.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),In=xn.number().int().min(1).max(1e3),Nt=xn.object({cap:_.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:xn.number().positive().max(1e4).nullable(),cycles:xn.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var rn={key:He,name:h.string().trim().min(1).max(80),description:h.string().trim().max(240)},gi=_.refine(e=>/[1-9]/.test(e)),hi=Mr.safeExtend({entitlementVersionId:h.uuid(),units:gi,dimensions:h.array(Nr.safeExtend({priority:h.number().int().min(-100).max(100)})).max(12).optional(),multipliers:h.array(Ur.safeExtend({factor:_,add:qr})).max(4).optional()}),va=h.discriminatedUnion("kind",[h.object({...rn,kind:h.literal("access")}).strict(),h.object({...rn,kind:h.literal("metered"),usageType:h.enum(["consumable","non_consumable"]),aiPricing:Nn.optional()}).strict().refine(e=>!e.aiPricing||e.usageType==="consumable","AI pricing requires a consumable micro USD meter"),h.object({...rn,kind:h.literal("credit"),rates:h.array(hi).min(1).max(100)}).strict().refine(e=>new Set(e.rates.map(t=>t.entitlementVersionId)).size===e.rates.length,"Rate entitlement versions must be unique")]),er=h.array(h.object({currency:z,amountMinor:h.number().int().min(0).max(1e8)}).strict()).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique"),bi=h.strictObject({units:gi,prices:h.array(h.strictObject({currency:z,amountMinor:h.number().int().min(0).max(1e8),pricing:Vn.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:h.number().int().min(0).max(1e4),maximumQuantity:h.number().int().min(1).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&Fr(t,n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),Qu=h.discriminatedUnion("kind",[h.object({kind:h.literal("access"),entitlementVersionId:h.uuid()}).strict(),h.object({kind:h.literal("metered"),entitlementVersionId:h.uuid(),amount:_.nullable(),reset:Sn,resetCount:In,pooled:h.boolean(),rollover:Nt.nullable().optional(),cashPrice:vt.nullable().optional(),prepaidPrice:bi.optional()}).strict().refine(e=>!e.cashPrice||e.amount!==null,"Cash pricing requires a finite prepaid allowance").refine(e=>!e.rollover||e.amount!==null&&e.reset!=="lifetime","Rollover requires a finite recurring consumable allowance").refine(e=>!e.prepaidPrice||e.amount!==null,"Purchased quantities require a finite included allowance").refine(e=>{if(!e.prepaidPrice||e.amount===null)return!0;try{return xi(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),h.object({kind:h.literal("credit"),entitlementVersionId:h.uuid(),amount:_,reset:Sn,resetCount:In,rollover:Nt.nullable(),pooled:h.boolean(),creditRates:h.array(hi).min(1).max(100).refine(e=>new Set(e.map(t=>t.entitlementVersionId)).size===e.length,"Override feature versions must be unique").optional(),cashPrice:vt.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&la(e.cashPrice),"Itemized invoice credits require a recurring, unpooled allowance without rollover priced at one currency unit per credit").refine(e=>!e.rollover||e.reset!=="lifetime","Rollover requires a recurring allowance")]),yi=h.array(Qu).max(100).refine(e=>new Set(e.map(t=>t.entitlementVersionId)).size===e.length,"An entitlement can be granted once per product"),Aa=h.object({days:h.number().int().min(1).max(730),cardRequired:h.boolean(),allowances:yi}).strict().refine(e=>e.allowances.every(t=>t.kind==="access"||!t.cashPrice&&(t.kind!=="metered"||!t.prepaidPrice)),"Trial allowances do not charge cash overages or purchased quantities"),ka=h.object({key:He,entitlementVersionId:h.uuid(),productVersionId:h.uuid(),includedQuantity:h.number().int().min(0).max(1e4),maximumQuantity:h.number().int().min(0).max(1e4),prices:er,pooledEntitlementVersionIds:h.array(h.uuid()).max(100),requireAssignment:h.boolean()}).strict().refine(e=>e.maximumQuantity>=e.includedQuantity,"Capacity cannot be less than included seats").refine(e=>new Set(e.pooledEntitlementVersionIds).size===e.pooledEntitlementVersionIds.length,"Shared entitlements must be unique"),Ut=h.discriminatedUnion("kind",[h.object({...rn,kind:h.literal("membership"),groupId:h.uuid(),membershipType:h.enum(["main","addon"]),interval:h.enum(["free","week","month","year","one_time"]),intervalCount:h.number().int().min(1).max(156).optional(),prices:er,allowances:yi,trial:Aa.nullable(),licenses:h.array(ka).max(20).refine(e=>new Set(e.map(t=>t.key)).size===e.length,"License keys must be unique")}).strict().refine(e=>e.interval==="free"?e.prices.every(t=>t.amountMinor===0):e.prices.every(t=>e.interval==="one_time"?t.amountMinor>0||e.allowances.some(n=>n.kind==="metered"&&n.prepaidPrice?.prices.some(r=>r.currency===t.currency&&r.amountMinor>0)):t.amountMinor>=0),"Prices must match the billing interval").refine(e=>e.interval!=="one_time"||e.trial===null,"Lifetime plans cannot have a subscription trial").refine(e=>e.intervalCount===void 0||(e.interval==="week"||e.interval==="month"||e.interval==="year")&&e.intervalCount<=(e.interval==="year"?3:e.interval==="month"?36:156),"Recurring billing intervals cannot exceed three years").refine(e=>e.allowances.every(t=>t.kind!=="metered"||!t.prepaidPrice||e.interval!=="free"&&t.prepaidPrice.prices.length===e.prices.length&&t.prepaidPrice.prices.every(n=>e.prices.some(r=>r.currency===n.currency))),"Purchased features require a paid plan and all its published currencies"),h.object({...rn,kind:h.literal("topup"),interval:h.literal("one_time"),prices:er,entitlementVersionId:h.uuid(),amount:gi,expiresDays:h.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),tr=h.object({interval:h.enum(["free","week","month","year","one_time"]).optional(),intervalCount:h.number().int().min(1).max(156).nullable().optional(),prices:er.optional(),allowances:h.object({upsert:yi,remove:h.array(h.uuid()).max(100)}).strict().refine(e=>new Set(e.remove).size===e.remove.length&&e.upsert.every(t=>!e.remove.includes(t.entitlementVersionId)),"An allowance cannot be removed and replaced together").optional(),trial:Aa.nullable().optional(),licenses:h.array(ka).max(20).optional()}).strict(),ja=h.object({...rn,kind:h.literal("variant"),baseProductVersionId:h.uuid(),overrides:tr}).strict(),Ca=h.union([Ut,ja]);function Of(e,t){let n=ja.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...o}=n.overrides,a=new Map(e.allowances.map(c=>[c.entitlementVersionId,c]));for(let c of r?.remove??[])if(!a.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])a.delete(c.entitlementVersionId);for(let c of r?.upsert??[])a.set(c.entitlementVersionId,c);let s={...structuredClone(e),...structuredClone(o),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...a.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),Ut.parse(s)}function Pf(e,t){if(e.kind!=="membership"||t.kind!=="membership"||e.groupId!==t.groupId||e.membershipType!==t.membershipType)throw new Error("Variant group and membership type must match the base");let n={};for(let s of["interval","intervalCount","prices","trial","licenses"])(s==="intervalCount"&&["week","month","year"].includes(t.interval)?(e.intervalCount??1)===(t.intervalCount??1):JSON.stringify(e[s])===JSON.stringify(t[s]))||Object.assign(n,{[s]:s==="intervalCount"&&t[s]===void 0?null:structuredClone(t[s])});let r=new Map(e.allowances.map(s=>[s.entitlementVersionId,s])),i=new Set(t.allowances.map(s=>s.entitlementVersionId)),o=t.allowances.filter(s=>JSON.stringify(r.get(s.entitlementVersionId))!==JSON.stringify(s)),a=e.allowances.filter(s=>!i.has(s.entitlementVersionId)).map(s=>s.entitlementVersionId);return(o.length||a.length)&&(n.allowances={upsert:o,remove:a}),tr.parse(n)}var zf=h.object({products:h.array(h.object({id:h.uuid(),productId:h.uuid(),name:h.string(),kind:h.enum(["membership","topup"]),version:h.number().int().positive()}).strict()).max(500),limited:h.boolean()}).strict(),Oa={id:h.uuid(),projectId:h.uuid(),environmentId:h.uuid(),revision:h.number().int().nonnegative(),status:h.enum(["draft","published","archived"]),publishedVersionId:h.uuid().nullable(),updatedAt:h.iso.datetime({offset:!0})},Wu=h.object({...Oa,draft:Ca}).strict(),Zu=h.object({...Oa,draft:va}).strict(),_f=h.object({rows:h.array(Wu).max(200),nextCursor:h.uuid().nullable()}).strict(),Rf=h.object({rows:h.array(Zu).max(200),nextCursor:h.uuid().nullable()}).strict(),Hu=h.object({entitlements:h.array(h.object({id:h.uuid(),entitlementId:h.uuid(),key:He,name:h.string().min(1).max(80),kind:h.enum(["access","metered","credit"]),usageType:h.enum(["consumable","non_consumable"]).nullable(),version:h.number().int().positive(),rates:h.array(hi).min(1).max(100).optional()}).strict().refine(e=>e.kind!=="credit"||e.rates!==void 0,"Credit options require their immutable rates")).max(500),limited:h.boolean()}).strict(),Pa={id:h.uuid().nullable(),revision:h.number().int().nonnegative()},Ef=h.discriminatedUnion("action",[h.object({...Pa,action:h.literal("save"),configuration:Ca}).strict(),h.object({id:h.uuid(),revision:h.number().int().nonnegative(),action:h.enum(["publish","archive","set_default","clear_default"])}).strict()]),Tf=h.discriminatedUnion("action",[h.object({...Pa,action:h.literal("save"),configuration:va}).strict(),h.object({id:h.uuid(),revision:h.number().int().nonnegative(),action:h.enum(["publish","archive"])}).strict()]),Df=h.object({groups:h.array(h.object({id:h.uuid(),name:h.string(),defaultProductVersionId:h.uuid().nullable()}).strict()).max(500),entitlements:Hu.shape.entitlements,products:h.array(h.object({id:h.uuid(),productId:h.uuid(),version:h.number().int().positive(),configuration:Ut,baseProductVersionId:h.uuid().nullable()}).strict()).max(500),limited:h.boolean()}).strict();function xi(e,t,n){let r=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[s,c=""]=a.split(".");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(o?"."+o:"")}var Vf=Ye.object({requestId:Ye.uuid(),baseProductVersionId:Ye.uuid(),name:Ye.string().trim().min(1).max(80),description:Ye.string().trim().max(240),overrides:tr}).strict(),qf=Ye.object({productId:Ye.uuid(),productVersionId:Ye.uuid(),bindingStatus:Ye.enum(["ready","requires_binding"]),missingCurrencies:Ye.array(Ye.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();import{z as oe}from"zod";var Ju=oe.object({minAccountAgeDays:oe.number().int().min(0).max(3650),paymentStatus:oe.enum(["all","unpaid","paid"])}),Yu=oe.object({percentOff:oe.number().int().min(1).max(100),redemptionWindowHours:oe.number().int().min(1).max(2160)}),Xu=oe.object({title:oe.string().trim().min(1).max(80),description:oe.string().trim().min(1).max(240),buttonLabel:oe.string().trim().min(1).max(30)}),el=oe.object({name:oe.string().trim().min(1).max(80),audience:Ju,offer:Yu,popup:Xu}),Lf=el.extend({id:oe.string().min(1),projectId:oe.string().min(1),environment:Wr,status:oe.enum(["draft","active","paused"]),updatedAt:oe.iso.datetime()}),Gf=be.extend({id:oe.string().min(1),externalUserId:oe.string().min(1),name:oe.string().min(1),email:oe.union([oe.email(),oe.literal("")]),createdAt:oe.iso.datetime(),paymentStatus:oe.enum(["unpaid","paid"]),stripeCustomerId:oe.string().nullable()}),Kf=oe.object({error:oe.object({code:oe.string(),message:oe.string()})});import{z as At}from"zod";var za=At.strictObject({itemKey:At.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}$/),entitlementVersionId:At.uuid(),includedAmount:At.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:At.number().int().min(0).max(1e4),terms:bi,pricing:Vn.optional(),unitAmountMinor:At.number().int().min(0).max(1e8),productId:At.string().min(1).max(255).nullable(),priceId:At.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{xi(e.includedAmount,e.terms.units,e.quantity),qn(e)}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as C}from"zod";var Si=C.object({id:C.uuid(),productVersionId:C.uuid(),connectionId:C.uuid(),currency:C.string().regex(/^[A-Z]{3}$/),productId:C.string().min(1).max(255),priceId:C.string().min(1).max(255),enabled:C.boolean()}).strict(),eg=C.object({productId:C.uuid(),name:C.string(),environment:C.enum(["sandbox","live"]),versions:C.array(C.object({id:C.uuid(),version:C.number().int().positive(),configuration:Ut}).strict()),connections:C.array(C.object({id:C.uuid(),accountId:C.string()}).strict()),bindings:C.array(Si),seatBindings:C.array(Si.extend({key:C.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:C.array(Si.extend({entitlementVersionId:C.uuid()}).strict()),limited:C.boolean()}).strict(),tg=C.discriminatedUnion("action",[C.strictObject({action:C.literal("bind_feature"),requestId:C.uuid(),productId:C.uuid(),productVersionId:C.uuid(),connectionId:C.uuid(),currency:C.string().regex(/^[A-Z]{3}$/),entitlementVersionId:C.uuid(),priceId:C.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),C.strictObject({action:C.literal("disable_feature"),productId:C.uuid(),bindingId:C.uuid()}),C.object({action:C.literal("bind_seat"),requestId:C.uuid(),productId:C.uuid(),productVersionId:C.uuid(),connectionId:C.uuid(),currency:C.string().regex(/^[A-Z]{3}$/),key:C.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:C.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),C.object({action:C.literal("disable_seat"),productId:C.uuid(),bindingId:C.uuid()}).strict(),C.object({action:C.literal("bind"),requestId:C.uuid(),productId:C.uuid(),productVersionId:C.uuid(),connectionId:C.uuid(),currency:C.string().regex(/^[A-Z]{3}$/),priceId:C.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),C.object({action:C.literal("disable"),productId:C.uuid(),bindingId:C.uuid()}).strict()]);import{z as M}from"zod";var nr=M.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),_a=M.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),tl=M.enum(["none","introductory","promotional"]),Ra=M.strictObject({offerKind:tl,couponId:M.uuid().nullable()}),nl=M.strictObject({id:M.uuid(),productVersionId:M.uuid(),connectionId:M.uuid(),provider:M.enum(["apple","google"]),currency:z,productId:nr,basePlanId:_a.nullable(),offerId:nr.nullable(),policy:Ra,enabled:M.boolean()}),ag=M.strictObject({productId:M.uuid(),name:M.string().min(1).max(80),environment:M.enum(["sandbox","live"]),versions:M.array(M.strictObject({id:M.uuid(),version:M.number().int().positive(),configuration:Ut})).max(100),connections:M.array(M.strictObject({id:M.uuid(),provider:M.enum(["apple","google"]),applicationId:M.string().min(1).max(255)})).max(100),bindings:M.array(nl).max(500),coupons:M.array(M.strictObject({id:M.uuid(),name:M.string().min(1).max(80)})).max(500),limited:M.boolean()}),sg=M.discriminatedUnion("action",[M.strictObject({action:M.literal("bind"),requestId:M.uuid(),productId:M.uuid(),productVersionId:M.uuid(),connectionId:M.uuid(),currency:z,storeProductId:nr,basePlanId:_a.nullable(),offerId:nr.nullable(),policy:Ra}),M.strictObject({action:M.literal("disable"),productId:M.uuid(),bindingId:M.uuid()})]);import{z as P}from"zod";var kt=_.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),wn=P.string().min(1).max(120),rr=P.enum(["cap","overflow"]),De=(e,t)=>{let[n,r=""]=e.split(".");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},vn=e=>{try{return e()}catch{return!1}},An=P.discriminatedUnion("operation",[P.object({operation:P.literal("quote"),overageBehavior:rr.optional(),entitlementId:P.uuid(),entityId:P.uuid().optional(),quantity:kt,properties:Ce}).strict(),P.object({operation:P.literal("consume"),overageBehavior:rr.optional(),occurredAt:P.iso.datetime({offset:!0}).optional(),entitlementId:P.uuid(),entityId:P.uuid().optional(),quantity:_,properties:Ce,idempotencyKey:wn}).strict(),P.object({operation:P.literal("reserve"),occurredAt:P.iso.datetime({offset:!0}).optional(),entitlementId:P.uuid(),entityId:P.uuid().optional(),quantity:kt,properties:Ce,idempotencyKey:wn,expiresInSeconds:P.number().int().min(1).max(86400)}).strict(),P.object({operation:P.literal("confirm"),operationId:P.uuid(),quantity:kt,properties:Ce.optional(),idempotencyKey:wn}).strict(),P.object({operation:P.literal("refund"),operationId:P.uuid(),quantity:kt,idempotencyKey:wn}).strict(),P.object({operation:P.literal("release"),operationId:P.uuid(),idempotencyKey:wn}).strict()]),Ii=P.object({creditVersionId:P.uuid().nullable(),meteredVersionId:P.uuid(),dimension:P.string().min(1).max(64),counterKey:P.string().min(1).max(240),cycleStart:P.iso.datetime({offset:!0}),unitCost:_,units:kt,amount:je,tier:P.number().int().min(1).max(12).nullable()}).strict(),Ea=P.discriminatedUnion("funding",[P.strictObject({funding:P.literal("unbilled"),units:kt}),P.object({funding:P.literal("prepaid"),sourceId:P.uuid(),units:kt,amount:je,pricing:P.array(Ii).min(1).max(12)}).strict().refine(e=>vn(()=>e.pricing.reduce((t,n)=>t+De(n.units,6),0n)===De(e.units,6)&&e.pricing.reduce((t,n)=>t+De(n.amount,12),0n)===De(e.amount,12)&&e.pricing.every(t=>De(t.unitCost,6)*De(t.units,6)===De(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),P.object({funding:P.literal("postpaid"),invoiceLineId:P.uuid().nullable(),units:kt,authorizationId:P.uuid()}).strict()]),ir=P.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Ta=P.object({allowed:P.boolean(),entitlementId:P.uuid(),quantity:_,requestedQuantity:_.optional(),overageBehavior:rr.optional(),reason:ir.nullable(),allocations:P.array(Ea).max(500)}).strict().refine(e=>vn(()=>e.allowed?e.reason===null&&e.allocations.reduce((t,n)=>t+De(n.units,6),0n)===De(e.quantity,6):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>vn(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&De(e.requestedQuantity,6)>=De(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),or=P.object({id:P.uuid(),entitlementId:P.uuid(),kind:P.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:P.uuid().nullable(),quantity:_,requestedQuantity:_.optional(),overageBehavior:rr.optional(),accepted:P.boolean(),reason:P.enum([...ir.options,"expired"]).nullable(),createdAt:P.iso.datetime({offset:!0}),reservationStatus:P.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:P.iso.datetime({offset:!0}).nullable(),allocations:P.array(Ea).max(500)}).strict().refine(e=>vn(()=>e.accepted?e.reason===null&&e.allocations.reduce((t,n)=>t+De(n.units,6),0n)===De(e.quantity,6):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>vn(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&De(e.requestedQuantity,6)>=De(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as K}from"zod";var jt=K.iso.datetime({offset:!0}),Da=_.refine(e=>/[1-9]/.test(e)),Fa=K.strictObject({interval:Sn.exclude(["lifetime"]),count:In}),rl=K.strictObject({action:K.literal("create"),requestId:K.uuid(),entitlementVersionId:K.uuid(),entityId:K.uuid().nullable(),name:K.string().trim().min(1).max(80),amount:Da.nullable(),startsAt:jt,expiresAt:jt.nullable(),reset:Fa.nullable(),rollover:Nt.nullable(),nextResetAt:jt.nullable()}).refine(e=>e.expiresAt===null||Date.parse(e.expiresAt)>Date.parse(e.startsAt),"Expiry must follow the start").refine(e=>!e.rollover||e.reset!==null&&e.amount!==null,"Rollover requires a finite recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&Date.parse(e.nextResetAt)>Date.parse(e.startsAt)&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset must follow the start and precede expiry"),Ba=K.discriminatedUnion("action",[rl,K.strictObject({action:K.literal("update"),requestId:K.uuid(),grantId:K.uuid(),revision:K.number().int().nonnegative(),name:K.string().trim().min(1).max(80),amount:Da.nullable(),expiresAt:jt.nullable(),rollover:Nt.nullable(),nextResetAt:jt.nullable()}),K.strictObject({action:K.enum(["add","subtract","set_remaining"]),requestId:K.uuid(),grantId:K.uuid(),revision:K.number().int().nonnegative(),amount:_}),K.strictObject({action:K.literal("revoke"),requestId:K.uuid(),grantId:K.uuid(),revision:K.number().int().nonnegative()})]),wi=K.strictObject({id:K.uuid(),entitlementVersionId:K.uuid(),entityId:K.uuid().nullable(),name:K.string(),amount:_.nullable(),reset:Fa.nullable(),rollover:Nt.nullable(),nextResetAt:jt.nullable(),startsAt:jt,expiresAt:jt.nullable(),revision:K.number().int().nonnegative(),revoked:K.boolean(),available:je,held:je,spent:je}),$a=K.strictObject({customerId:K.uuid(),after:K.uuid().nullable(),limit:K.number().int().min(1).max(100)}),Va=K.strictObject({rows:K.array(wi).max(100),nextCursor:K.uuid().nullable()});import{z as O}from"zod";var st=O.iso.datetime({offset:!0}),qa=O.strictObject({invoiceId:O.uuid(),after:O.string().min(1).max(180).nullable(),limit:O.number().int().min(1).max(100)}),il=O.strictObject({kind:O.literal("product"),key:O.string(),productVersionId:O.uuid(),productName:O.string(),itemKey:O.string(),entityId:O.uuid().nullable(),quantity:O.number().int().positive(),subtotalMinor:O.string().regex(/^-?\d+$/),discountMinor:O.string().regex(/^\d+$/),taxMinor:O.string().regex(/^-?\d+$/),totalMinor:O.string().regex(/^-?\d+$/),startsAt:st,endsAt:st,providerLineId:O.string().nullable(),providerItemId:O.string()}),Na=O.strictObject({invoice:yn,items:O.array(O.discriminatedUnion("kind",[il,O.strictObject({kind:O.literal("invoice_credit"),key:O.string(),entitlementId:O.uuid(),entitlementVersionId:O.uuid(),creditVersionId:O.uuid(),name:O.string(),units:_,reserved:_,amountMinor:tn,grossAmountMinor:tn,creditsAppliedMinor:tn,properties:Ce,cashPrice:vt,providerItemId:O.string().nullable(),creditProviderItemId:O.string().nullable()}),O.strictObject({kind:O.literal("usage"),key:O.string(),entitlementId:O.uuid(),entitlementVersionId:O.uuid(),name:O.string(),units:_,reserved:_,amountMinor:tn,cashPrice:vt})])).max(100),nextCursor:O.string().min(1).max(180).nullable()}),ol=O.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),vi=O.strictObject({from:st,to:st,entityId:O.uuid().optional(),snapshotAt:st.nullable(),after:O.strictObject({at:st,id:O.uuid(),position:O.number().int().nonnegative()}).nullable(),limit:O.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"),Ua=O.strictObject({customerId:O.uuid(),entityId:O.uuid().nullable(),from:st,to:st,snapshotAt:st,totals:O.array(O.strictObject({creditVersionId:O.uuid(),name:O.string(),consumed:je,refunded:je,net:ol})).max(1e3),rows:O.array(O.strictObject({operationId:O.uuid(),position:O.number().int().nonnegative(),kind:O.enum(["consume","confirm","refund"]),originalId:O.uuid().nullable(),occurredAt:st,entitlementId:O.uuid(),entitlementName:O.string(),sourceId:O.uuid(),creditVersionId:O.uuid(),creditName:O.string(),units:_,amount:je,pricing:O.array(Ii).max(12),properties:Ce})).max(100),nextCursor:vi.shape.after});import{z as Ve}from"zod";var vg=Ve.enum(["billing.updated","invoice.finalized","billing.auto_topup_failed","billing.auto_topup_succeeded","billing.conflict","billing.purchase","billing.refund","usage.consume","usage.confirm","usage.refund","usage.limit","usage.alert","usage.allowance"]),Ma=Ve.object({operationId:Ve.uuid(),windowId:Ve.uuid(),customerId:Ve.uuid(),entityId:Ve.uuid().nullable(),entitlementId:Ve.uuid(),entitlementKey:mn,basis:Ve.enum(["usage","credits"]),interval:Ve.enum(["day","week","month","year"]),filter:Ce,startsAt:Ve.iso.datetime({offset:!0}),endsAt:Ve.iso.datetime({offset:!0}),limit:_.refine(e=>/[1-9]/.test(e)),used:je,reserved:je,threshold:Ve.number().positive().max(1),revision:Ve.number().int().nonnegative()}).strict(),Ag=Ma.omit({threshold:!0,limit:!0}).extend({alertThreshold:_.refine(e=>/[1-9]/.test(e)),limit:_.nullable()}),kg=Ma.omit({limit:!0}).extend({includedAllowance:Ve.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as x}from"zod";import{z as Xe}from"zod";var al=Xe.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),sl=Xe.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ar=Xe.strictObject({entitlementId:Xe.uuid(),entityId:Xe.uuid().nullable()}),La=ar.extend({quantity:_,expectedRevision:Xe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:Xe.string().min(1).max(120),properties:Ce.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),kn=ar.extend({operationId:Xe.uuid().nullable(),usage:_,capacity:al.nullable(),remaining:sl.nullable(),withinLimit:Xe.boolean(),revision:Xe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Xe.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[o,a=""]=(i?r.slice(1):r).split(".");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.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 ye=x.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),et=x.iso.datetime({offset:!0}),cl=x.enum(["access","metered","credit"]),Cn={entitlementId:x.uuid(),entitlementVersionId:x.uuid(),version:x.number().int().positive(),key:x.string().min(1).max(64),name:x.string().min(1).max(120),kind:cl},Ga=x.object({customerId:x.uuid(),snapshotAt:et,memberships:x.array(x.object({id:x.uuid(),productId:x.uuid(),productVersionId:x.uuid(),billingProductVersionId:x.uuid(),version:x.number().int().positive(),key:x.string().min(1).max(64),name:x.string().min(1).max(120),groupId:x.uuid(),membershipType:x.enum(["main","addon"]),status:x.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:x.boolean(),accessEnabled:x.boolean(),renewalChange:x.object({productVersionId:x.uuid(),name:x.string().min(1).max(120),version:x.number().int().positive(),effectiveAt:et,benefitsAppliedAt:et.nullable(),timing:x.enum(["immediate","renewal"]),changeKind:x.enum(["plan","seats","quantity"]),feature:x.strictObject({entitlementVersionId:x.uuid(),name:x.string().min(1).max(80),fromQuantity:x.number().int().min(0).max(1e4),toQuantity:x.number().int().min(0).max(1e4)}).optional(),seat:x.object({key:x.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:x.number().int().min(0).max(1e4),toQuantity:x.number().int().min(0).max(1e4)}).strict().nullable(),status:x.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:x.object({phase:x.enum(["paid","trial"]),startsAt:et,endsAt:et.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:x.boolean(),balances:x.array(x.object({...Cn,usageType:x.enum(["consumable","non_consumable"]).nullable(),accessible:x.boolean(),unlimited:x.boolean(),available:ye,held:ye,debt:ye,nextExpiresAt:et.nullable(),usage:kn.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.entitlementId===e.entitlementId&&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:x.boolean()}).strict(),Ka=x.enum(["source","usage","transaction","debt","settlement"]),sr=x.object({at:et,id:x.uuid(),type:Ka}).strict(),Qa=x.object({type:Ka.nullable(),from:x.iso.date().nullable(),to:x.iso.date().nullable(),after:sr.nullable(),limit:x.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),jn={id:x.uuid(),occurredAt:et},ul=x.discriminatedUnion("type",[x.object({...jn,...Cn,type:x.literal("source"),reason:x.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:ye,unlimited:x.boolean(),status:x.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:et,expiresAt:et.nullable(),orderId:x.uuid().nullable(),parentSourceId:x.uuid().nullable()}).strict(),x.object({...jn,type:x.literal("usage"),entitlementId:x.uuid(),name:x.string().min(1).max(120),kind:x.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:x.uuid().nullable(),quantity:_,accepted:x.boolean(),reason:x.enum([...ir.options,"expired"]).nullable(),properties:Ce,reservationStatus:x.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:et.nullable(),charges:x.array(x.discriminatedUnion("funding",[x.object({...Cn,funding:x.literal("prepaid"),amount:ye}).strict(),x.object({funding:x.literal("postpaid"),invoiceId:x.uuid(),invoiceLineId:x.uuid(),authorizationId:x.uuid(),units:_,currency:z}).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"),x.object({...jn,type:x.literal("transaction"),purpose:x.enum(["product","invoice"]),productVersionId:x.uuid().nullable(),productName:x.string().min(1).max(120).nullable(),productVersion:x.number().int().positive().nullable(),invoiceId:x.uuid().nullable(),orderId:x.uuid(),originalId:x.uuid().nullable(),kind:x.enum(["purchase","refund"]),amountMinor:x.number().int().nonnegative().max(2e8).nullable(),currency:z.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"),x.object({...jn,...Cn,type:x.literal("debt"),sourceId:x.uuid(),transactionId:x.uuid(),amount:ye}).strict(),x.object({...jn,...Cn,type:x.literal("settlement"),sourceId:x.uuid(),debtId:x.uuid(),kind:x.enum(["payment","usage_refund","payment_return"]),amount:ye}).strict()]),Wa=x.object({customerId:x.uuid(),rows:x.array(ul).max(50),nextCursor:sr.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as R}from"zod";var Za=R.object({customerId:R.uuid()}).strict(),Ha=R.discriminatedUnion("action",[R.object({customerId:R.uuid(),requestId:R.uuid(),action:R.literal("assign"),poolId:R.uuid(),memberCustomerId:R.uuid()}).strict(),R.strictObject({customerId:R.uuid(),requestId:R.uuid(),action:R.literal("assign_entity"),poolId:R.uuid(),entityId:R.uuid()}),R.object({customerId:R.uuid(),requestId:R.uuid(),action:R.literal("release"),poolId:R.uuid(),slotId:R.uuid()}).strict()]),Ai=R.object({customerId:R.uuid(),pools:R.array(R.object({id:R.uuid(),membershipId:R.uuid(),entityId:R.uuid().nullable(),key:R.string(),name:R.string(),entitlementVersionId:R.uuid(),memberProductVersionId:R.uuid(),includedQuantity:R.number().int().nonnegative(),quantity:R.number().int().nonnegative(),maximumQuantity:R.number().int().nonnegative(),assignedQuantity:R.number().int().nonnegative(),availableQuantity:R.number().int().nonnegative(),accessEnabled:R.boolean(),requireAssignment:R.boolean(),pendingChange:R.object({receiptId:R.uuid(),quantity:R.number().int().min(0).max(1e4),timing:R.enum(["immediate","renewal"]),status:R.enum(["prepared","quoted","confirmed","pending","scheduled"]),effectiveAt:R.iso.datetime({offset:!0})}).strict().nullable(),period:R.object({startsAt:R.iso.datetime({offset:!0}),endsAt:R.iso.datetime({offset:!0}).nullable()}).strict()}).strict()).max(2e3),slots:R.array(R.object({id:R.uuid(),poolId:R.uuid(),position:R.number().int().positive(),memberCustomerId:R.uuid().nullable(),entityId:R.uuid().nullable(),assignedAt:R.iso.datetime({offset:!0}),releasedAt:R.iso.datetime({offset:!0}).nullable()}).strict().refine(e=>e.memberCustomerId===null!=(e.entityId===null),"A seat has exactly one beneficiary")).max(1e4),limited:R.boolean()}).strict();import{z as Ct}from"zod";var ll=Ct.object({name:Ct.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Ct.string().trim().max(63).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"\u9879\u76EE\u6807\u8BC6\u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26")}),Ja=Ct.object({description:Ct.string().trim().max(240)}),Vg=Ct.object({project:ll.extend({id:Ct.string().min(1)}),environments:Ct.object({sandbox:Ja,live:Ja})});import{z as ce}from"zod";import{z as ee}from"zod";import{z as on}from"zod";var Ya=on.enum(["stripe","apple","google"]),Xa=on.enum(["membership","credit_pack","lifetime"]),Ug=on.enum(["active","grace","suspended","inactive","revoked"]),Mg=on.strictObject({currency:on.string().regex(/^[A-Z]{3}$/),micros:on.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var On=ee.object({type:ee.literal("native_purchase"),receiptId:ee.uuid(),orderId:ee.uuid(),productVersionId:ee.uuid(),provider:ee.enum(["apple","google"]),productId:ee.string().min(1).max(255),productKind:Xa,replacement:ee.strictObject({sourceOrderId:ee.uuid(),sourceProductId:ee.string().min(1).max(255),policy:ee.enum(["apple_store","google_full_price"]),sourceAccountTokens:ee.array(ee.uuid()).max(50)}).nullable(),appAccountToken:ee.uuid().optional(),obfuscatedAccountId:ee.string().min(1).max(64).optional(),obfuscatedProfileId:ee.uuid().optional(),basePlanId:ee.string().min(1).max(255).optional(),offerId:ee.string().min(1).max(255).optional(),offerKind:ee.enum(["none","introductory","promotional"]),currency:z,catalogAmountMinor:ee.number().int().nonnegative().max(1e8),discountMinor:ee.number().int().nonnegative().max(1e8),trialDays:ee.number().int().min(1).max(730).nullable(),seatBundle:ee.array(ee.strictObject({key:ee.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:ee.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:ee.strictObject({offerId:ee.string().min(1).max(255),keyId:ee.string().min(1).max(255),nonce:ee.uuid(),signature:ee.string().min(1).max(1024),timestamp:ee.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 bound store policy"})});import{z as d}from"zod";var es=d.strictObject({requestId:d.uuid(),entityId:d.uuid().optional(),billingSubscriptionId:d.uuid().optional(),newBillingSubscription:d.literal(!0).optional(),offerId:d.uuid().optional(),plans:d.array(d.strictObject({productVersionId:d.uuid(),seatQuantities:d.record(He,d.number().int().min(0).max(1e4)).optional(),featureQuantities:d.record(d.uuid(),d.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:d.enum(["stripe","apple","google"]),currency:z}).refine(e=>!e.offerId||e.provider==="stripe"&&!e.billingSubscriptionId,"Held offers apply to a new Stripe Checkout; existing subscriptions use billing coupons").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target"),Mt=d.strictObject({operationId:d.uuid()}),fe=d.number().int().min(0).max(1e8),dl=d.strictObject({lineId:d.uuid(),productVersionId:d.uuid(),productName:d.string().min(1).max(80),interval:d.enum(["free","week","month","year","one_time"]),intervalCount:d.number().int().min(1).max(156).optional(),baseAmountMinor:fe,seats:d.array(d.strictObject({key:He,quantity:d.number().int().min(0).max(1e4),includedQuantity:d.number().int().min(0).max(1e4),maximumQuantity:d.number().int().min(0).max(1e4),unitAmountMinor:fe})).max(20),prepaid:d.array(za).max(100).optional(),catalogAmountMinor:fe,trial:d.strictObject({days:d.number().int().min(1).max(730),cardRequired:d.boolean()}).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+qn(n),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),ts=d.strictObject({operationId:d.uuid(),entityId:d.uuid().nullable(),billingSubscriptionId:d.uuid().nullable(),discount:d.strictObject({offerId:d.uuid(),couponId:d.uuid(),discount:Xt,duration:at,amountMinor:fe,allocations:d.array(d.strictObject({productVersionId:d.uuid(),amountMinor:fe})).min(1).max(20),expiresAt:d.iso.datetime({offset:!0})}).nullable(),charge:d.strictObject({effectiveAt:d.iso.datetime({offset:!0}),periodEndsAt:d.iso.datetime({offset:!0}),debitMinor:fe,discountMinor:fe,taxMinor:fe,totalMinor:fe}).nullable(),expiresAt:d.iso.datetime({offset:!0}),provider:d.enum(["stripe","apple","google"]),currency:z,lines:d.array(dl).min(1).max(20),catalogAmountMinor:fe,automaticTax:d.boolean()}).refine(e=>(!e.discount||e.provider==="stripe"&&!e.billingSubscriptionId&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>t.productVersionId===e.lines[n].productVersionId&&t.amountMinor<=e.lines[n].catalogAmountMinor)&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ki=d.strictObject({operationId:d.uuid(),orderId:d.uuid(),status:d.enum(["pending","complete","cancelled","failed"]),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),currency:z,catalogAmountMinor:fe,taxMinor:fe,totalMinor:d.number().int().min(0).max(2e8).nullable(),quoteFinalized:d.boolean(),nativePurchase:On.nullable()}),cr=d.strictObject({enabled:d.literal(!0),featureIds:d.array(d.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),ns=d.strictObject({requestId:d.uuid(),membershipId:d.uuid(),carryOverBalances:cr.optional(),carryOverUsages:cr.optional(),membershipIds:d.array(d.uuid()).min(1).max(20).optional(),timing:d.enum(["immediate","renewal","store"]),change:d.discriminatedUnion("type",[d.strictObject({type:d.literal("plan"),productVersionId:d.uuid()}),d.strictObject({type:d.literal("seats"),licenseKey:He,quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("quantity"),entitlementVersionId:d.uuid(),quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("cancel")}),d.strictObject({type:d.literal("uncancel")})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").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"),ji=d.strictObject({carryOverBalances:cr.optional(),carryOverUsages:cr.optional(),operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),expiresAt:d.iso.datetime({offset:!0}),currency:z,creditMinor:fe,debitMinor:fe,discountMinor:fe,taxMinor:fe,totalMinor:fe,retainedProductVersionIds:d.array(d.uuid()).max(19)}),ml=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable()}),pl=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.literal("store"),effectiveAt:d.null(),expiresAt:d.iso.datetime({offset:!0}),currency:z,creditMinor:d.null(),debitMinor:d.null(),discountMinor:d.null(),taxMinor:d.null(),totalMinor:d.null(),retainedProductVersionIds:d.array(d.uuid()).max(19),store:d.strictObject({provider:d.enum(["apple","google"]),productId:d.string().min(1).max(255),catalogAmountMinor:fe,policy:d.enum(["apple_store","google_full_price"])})}),fl=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","pending","effective","cancelled","failed"]),timing:d.literal("store"),effectiveAt:d.iso.datetime({offset:!0}).nullable(),checkoutUrl:d.null(),nativePurchase:On.nullable()}),rs=d.union([ji,pl]),Ci=d.union([ml,fl]),Oi=d.strictObject({requestId:d.uuid(),membershipId:d.uuid(),purchaseId:d.uuid(),lines:d.array(d.strictObject({invoiceLineId:d.string().regex(/^il_[A-Za-z0-9_]+$/),amountMinor:fe.positive()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.invoiceLineId)).size===e.length,"Refund lines must be unique"),entitlementAction:d.enum(["retain","revoke"])}),is=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),purchaseId:d.uuid(),invoiceId:d.string().startsWith("in_"),currency:z,amountMinor:fe.positive(),entitlementAction:d.enum(["retain","revoke"]),lines:Oi.shape.lines,expiresAt:d.iso.datetime({offset:!0})}),Pi=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),purchaseId:d.uuid(),status:d.enum(["prepared","confirmed","pending","effective","failed"]),currency:z,amountMinor:fe.positive(),entitlementAction:d.enum(["retain","revoke"]),refundId:d.string().startsWith("re_").nullable(),creditNoteId:d.string().startsWith("cn_").nullable()}),nh=d.strictObject({customerId:d.uuid(),membershipId:d.uuid(),limited:d.boolean(),purchases:d.array(d.strictObject({purchaseId:d.uuid(),currency:z,occurredAt:d.iso.datetime({offset:!0}),lines:d.array(d.strictObject({invoiceLineId:d.string().regex(/^il_[A-Za-z0-9_]+$/),invoiceId:d.string().startsWith("in_"),itemKey:d.string().min(1).max(100),paidMinor:d.number().int().min(0).max(2e8),availableMinor:fe})).min(1).max(20)})).max(20)});var os=ce.strictObject({requestId:ce.uuid(),targets:ce.array(ce.strictObject({membershipId:ce.uuid(),action:ce.enum(["cancel","uncancel"]),timing:ce.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"),ur=ce.strictObject({batchId:ce.uuid()}),gl=ce.strictObject({operationId:ce.uuid(),membershipIds:ce.array(ce.uuid()).min(1).max(20),provider:ce.enum(["stripe","apple","google"]),action:ce.enum(["cancel","uncancel"]),timing:ce.enum(["immediate","renewal"]),status:ce.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ji.nullable(),managementUrl:ce.url().nullable(),failureCode:ce.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Pn=ce.strictObject({batchId:ce.uuid(),ready:ce.boolean(),status:ce.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ce.iso.datetime({offset:!0}),acceptedAt:ce.iso.datetime({offset:!0}).nullable(),groups:ce.array(gl).min(1).max(100)});import{z as ae}from"zod";var hl=ae.string().trim().min(1).max(240),zi={requestId:ae.uuid(),reason:hl},lr=ae.discriminatedUnion("action",[ae.strictObject({...zi,action:ae.literal("start"),productVersionId:ae.uuid(),entityId:ae.uuid().optional(),days:ae.number().int().min(1).max(730).optional()}),ae.strictObject({...zi,action:ae.literal("extend"),membershipId:ae.uuid(),days:ae.number().int().min(1).max(730)}),ae.strictObject({...zi,action:ae.literal("end"),membershipId:ae.uuid()})]),as=ae.strictObject({operationId:ae.uuid()}),_i=ae.strictObject({operationId:ae.uuid(),status:ae.enum(["effective","store_action_required"]),provider:ae.enum(["free","stripe","apple","google"]),membershipIds:ae.array(ae.uuid()).min(1).max(20),endsAt:ae.iso.datetime({offset:!0}).nullable(),managementUrl:ae.url().nullable()}).refine(e=>e.status==="store_action_required"==(e.provider==="apple"||e.provider==="google")&&e.status==="store_action_required"==(e.managementUrl!==null),"Store trials require a channel action"),ch=ae.strictObject({groupId:ae.uuid(),productVersionId:ae.uuid(),enabled:ae.boolean()});import{z as qe}from"zod";var ss=qe.strictObject({requestId:qe.uuid(),currency:z,makeDefault:qe.boolean()}),cs=qe.strictObject({setupId:qe.uuid()}),Ri=qe.strictObject({id:qe.uuid(),provider:qe.literal("stripe"),status:qe.enum(["prepared","complete","expired"]),currency:z,makeDefault:qe.boolean(),url:qe.url().nullable(),createdAt:qe.iso.datetime({offset:!0}),expiresAt:qe.iso.datetime({offset:!0}),completedAt:qe.iso.datetime({offset:!0}).nullable()});import{z as Ae}from"zod";var us=Ae.union([Ae.string(),Ae.number(),Ae.boolean(),Ae.null()]),ls=Ae.strictObject({customerId:Ae.uuid()}),ds=Ae.strictObject({customerId:Ae.uuid(),provider:Ae.literal("stripe"),checkedAt:Ae.iso.datetime({offset:!0}),status:Ae.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ae.number().int().nonnegative(),differences:Ae.array(Ae.strictObject({subscriptionId:Ae.string().startsWith("sub_"),itemId:Ae.string().nullable(),field:Ae.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","evidence"]),expected:us,actual:us})).max(1e4)});import{z as $}from"zod";var dr=$.iso.datetime({offset:!0}),mr=$.strictObject({createdAt:dr,id:$.uuid()}),pr=$.strictObject({customerId:$.uuid().optional(),entityId:$.uuid().optional(),productId:$.uuid().optional(),provider:$.enum(["stripe","apple","google","free"]).optional(),status:$.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:mr.optional(),limit:$.number().int().min(1).max(100).optional()}),Ei={id:$.uuid(),customerId:$.uuid(),entityId:$.uuid().nullable(),productId:$.uuid(),productVersionId:$.uuid(),name:$.string().min(1).max(120),provider:$.enum(["stripe","apple","google","free"]),createdAt:dr},bl=$.strictObject({...Ei,status:$.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:$.boolean(),billingSubscriptionId:$.uuid().nullable()}),yl=$.strictObject({...Ei,status:$.enum(["active","ended","refunded"]),orderId:$.uuid(),transactionId:$.uuid(),currency:z.nullable(),amountMinor:$.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),xl=$.strictObject({...Ei,status:$.enum(["blocked","resolved"]),conflict:$.strictObject({detectedAt:dr,blockingMembershipIds:$.array($.uuid()).min(1).max(100),transactionId:$.uuid()}),resolvedAt:dr.nullable()}),ms=pr.extend({status:$.enum(["blocked","resolved"]).optional()}),ps=$.strictObject({customerId:$.uuid(),orderId:$.uuid()}),fs=$.strictObject({orderId:$.uuid(),status:$.enum(["blocked","resolved"])}),gs=$.strictObject({items:$.array(bl).max(100),nextCursor:mr.nullable()}),hs=$.strictObject({items:$.array(yl).max(100),nextCursor:mr.nullable()}),bs=$.strictObject({items:$.array(xl).max(100),nextCursor:mr.nullable()});import{z as le}from"zod";var ys=le.discriminatedUnion("provider",[le.strictObject({requestId:le.uuid(),provider:le.literal("apple"),purchaseIntentId:le.uuid(),productId:le.string().min(1).max(255),signedTransaction:le.string().min(1).max(131072)}),le.strictObject({requestId:le.uuid(),provider:le.literal("google"),purchaseIntentId:le.uuid(),productId:le.string().min(1).max(255),purchaseToken:le.string().min(1).max(16384)})]),xs=le.strictObject({requestId:le.uuid(),orderId:le.uuid(),purchaseIntentId:le.uuid(),status:le.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:z,refunded:le.boolean(),completion:le.strictObject({transactionIds:le.array(le.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:le.boolean()}).nullable()});import{z as Ee}from"zod";var Ss={requestId:Ee.uuid(),sourceId:Ee.uuid(),expectedAvailable:ye},Is=Ee.discriminatedUnion("action",[Ee.strictObject({...Ss,action:Ee.enum(["add","subtract","set_remaining"]),amount:_}),Ee.strictObject({...Ss,action:Ee.literal("edit"),granted:_,expiresAt:Ee.iso.datetime({offset:!0}).nullable(),nextResetAt:Ee.iso.datetime({offset:!0}).nullable(),expectedRevision:Ee.number().int().nonnegative()})]),Ti=Ee.strictObject({sourceId:Ee.uuid(),available:ye,held:ye,spent:ye,adjustmentGrantId:Ee.uuid().nullable()}),ws=Ti.extend({granted:ye,expiresAt:Ee.iso.datetime({offset:!0}).nullable(),nextResetAt:Ee.iso.datetime({offset:!0}).nullable(),revision:Ee.number().int().nonnegative()});import{z as Le}from"zod";var vs=Le.discriminatedUnion("action",[Le.object({action:Le.literal("upsert"),externalId:Le.string().min(1).max(128),name:Le.string().trim().min(1).max(80)}).strict(),Le.object({action:Le.literal("archive"),entityId:Le.uuid()}).strict()]),As=Le.object({id:Le.uuid(),externalId:Le.string().min(1).max(128),name:Le.string().min(1).max(80),archived:Le.boolean()}).strict();import{z as Pe}from"zod";import{z as D}from"zod";var Lt=D.iso.datetime({offset:!0}),Ot=D.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Sl=D.discriminatedUnion("kind",[D.object({kind:D.literal("absolute"),from:Lt,to:Lt}).strict(),D.object({kind:D.literal("last_days"),days:D.union([D.literal(1),D.literal(7),D.literal(30),D.literal(90)])}).strict(),D.object({kind:D.literal("billing_cycles"),membershipId:D.uuid(),count:D.number().int().min(1).max(12),includeCurrent:D.boolean()}).strict()]),ks=D.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"),Il=D.object({key:D.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:D.array(D.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Gt=D.object({range:Sl,timezone:ks,filterBy:D.array(Il).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:D.enum(["hour","day","week","month"]),entitlementId:D.uuid().nullable(),entityId:D.uuid().nullable(),topN:D.number().int().min(1).max(50).nullable(),groupBy:D.union([D.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),D.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:D.object({bucket:Lt,group:D.string().max(240),isOther:D.boolean(),entitlementId:D.uuid(),resourceId:D.uuid()}).strict().nullable(),limit:D.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)"})}),js=D.object({from:Lt,to:Lt,interval:D.enum(["hour","day","week","month"]),timezone:ks,rows:D.array(D.object({bucket:Lt,group:D.string().max(240),isOther:D.boolean(),entitlementId:D.uuid(),resourceId:D.uuid(),consumedUnits:Ot,refundedUnits:Ot,reservedUnits:Ot,charged:Ot,refunded:Ot,reserved:Ot,netUnits:Ot,netCharged:Ot}).strict()).max(100),nextCursor:D.object({bucket:Lt,group:D.string().max(240),isOther:D.boolean(),entitlementId:D.uuid(),resourceId:D.uuid()}).strict().nullable()}).strict();var an=Pe.string().regex(/^(0|[1-9]\d{0,29})$/),Cs=Pe.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Di=Pe.strictObject({bucket:Pe.iso.datetime({offset:!0}),group:Pe.string().max(240),isOther:Pe.boolean(),entitlementId:Pe.uuid()}),Os=Pe.strictObject({...Gt.shape,groupBy:Pe.union([Pe.enum(["customer","entity","entitlement"]),Pe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Di.nullable()}).superRefine((e,t)=>{let n=Gt.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Ps=Pe.strictObject({from:Pe.iso.datetime({offset:!0}),to:Pe.iso.datetime({offset:!0}),interval:Gt.shape.interval,timezone:Gt.shape.timezone,rows:Pe.array(Pe.strictObject({...Di.shape,eventCount:an,units:Cs,tokenEventCount:an,tokens:Pe.strictObject(Object.fromEntries(So.map(e=>[e,an]))),totalTokens:an,providerCostEventCount:an,providerCostUsd:Cs,invalidTelemetryEventCount:an})).max(100),nextCursor:Di.nullable()});import{z as ge}from"zod";var zs=ge.object({requestId:ge.uuid(),items:ge.array(ge.object({customerId:ge.uuid(),command:An.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"),_s=ge.object({batchId:ge.uuid(),after:ge.number().int().min(-1).max(999),limit:ge.number().int().min(1).max(100)}).strict(),Rs=ge.object({batchId:ge.uuid(),status:ge.enum(["queued","complete"]),total:ge.number().int().min(1).max(1e3),processed:ge.number().int().min(0).max(1e3),items:ge.array(ge.object({position:ge.number().int().min(0).max(999),customerId:ge.uuid(),idempotencyKey:ge.string().min(1).max(120),status:ge.enum(["queued","accepted","rejected","failed"]),receipt:or.nullable(),errorCode:ge.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:ge.number().int().min(0).max(999).nullable()}).strict();import{z as b}from"zod";var wl=b.discriminatedUnion("kind",[b.object({kind:b.literal("access"),entitlementVersionId:b.uuid(),expiresDays:b.number().int().min(1).max(3660).nullable()}).strict(),b.object({kind:b.enum(["metered","credit"]),entitlementVersionId:b.uuid(),amount:_.refine(e=>/[1-9]/.test(e)),expiresDays:b.number().int().min(1).max(3660).nullable()}).strict()]),vl=b.discriminatedUnion("type",[b.object({type:b.literal("coupon"),couponId:b.uuid()}).strict(),b.object({type:b.literal("feature_grant"),grants:b.array(wl).min(1).max(100).refine(e=>new Set(e.map(t=>t.entitlementVersionId)).size===e.length,"Duplicate entitlement grants")}).strict(),b.object({type:b.literal("free_product"),productVersionId:b.uuid(),duration:at}).strict()]),Al=b.enum(["draft","active","paused","archived"]),Es=b.object({key:b.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:b.string().trim().min(1).max(80),configuration:vl}).strict(),Fi=b.object({code:b.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),maxUses:b.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:b.boolean(),expiresAt:b.iso.datetime({offset:!0}).nullable()}).strict(),Ts=b.object({key:b.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:b.string().trim().min(1).max(80),rewardId:b.uuid(),redeemOn:b.enum(["customer_creation","checkout"]),receivedBy:b.enum(["referrer","all"]),maxRedemptions:b.number().int().min(1).max(1e6).nullable(),productIds:b.array(b.uuid()).max(50).refine(e=>new Set(e).size===e.length),excludeTrial:b.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Ds={id:b.uuid(),projectId:b.uuid(),environmentId:b.uuid(),revision:b.number().int().nonnegative(),status:Al,createdAt:b.iso.datetime({offset:!0}),updatedAt:b.iso.datetime({offset:!0})},kl=Es.extend(Ds).strict(),jl=Ts.safeExtend(Ds).strict(),qh=b.discriminatedUnion("action",[b.object({action:b.literal("save"),id:b.uuid().nullable(),revision:b.number().int().nonnegative(),input:Es}).strict(),b.object({action:b.enum(["activate","pause","resume","archive","delete"]),id:b.uuid(),revision:b.number().int().nonnegative()}).strict()]),Nh=b.discriminatedUnion("action",[b.object({action:b.literal("save"),id:b.uuid().nullable(),revision:b.number().int().nonnegative(),input:Ts}).strict(),b.object({action:b.enum(["activate","pause","resume","archive","delete"]),id:b.uuid(),revision:b.number().int().nonnegative()}).strict()]),Bi=b.object({id:b.uuid(),rewardId:b.uuid(),programId:b.uuid().nullable(),customerId:b.uuid(),referrerId:b.uuid().nullable(),status:b.enum(["pending","applied"]),result:b.record(b.string(),b.unknown()).nullable(),createdAt:b.iso.datetime({offset:!0})}).strict(),Fs=b.object({code:b.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:b.uuid()}).strict(),Bs=b.strictObject({redemptionId:b.uuid(),currency:z,requestId:b.uuid(),accepted:b.literal(!0)}),Cl=b.strictObject({type:b.literal("checkout"),orderId:b.uuid(),productVersionId:b.uuid(),currency:z,duration:at,renewalAmountMinor:b.number().int().positive().max(1e8),status:b.enum(["created","pending","trialing","paid","cancelled","failed"]),url:b.url().nullable()}),$s=b.discriminatedUnion("type",[Cl,b.strictObject({type:b.literal("subscription"),operationId:b.uuid(),membershipId:b.uuid(),productVersionId:b.uuid(),currency:z,duration:at,renewalAmountMinor:b.number().int().positive().max(1e8),status:b.enum(["pending","running","applied","failed"])})]),Vs=b.object({programId:b.uuid(),requestId:b.uuid()}).strict(),qs=b.object({id:b.uuid(),programId:b.uuid(),code:Fi.shape.code,createdAt:b.iso.datetime({offset:!0})}).strict(),Uh=b.object({rows:b.array(kl).max(100),nextCursor:b.uuid().nullable()}).strict(),Mh=b.object({rows:b.array(jl).max(100),nextCursor:b.uuid().nullable()}).strict(),Ol=Fi.extend({id:b.uuid(),active:b.boolean(),createdAt:b.iso.datetime({offset:!0}),redemptions:b.number().int().nonnegative()}).strict(),Lh=b.object({codes:b.array(Ol).max(100),redemptions:b.array(Bi).max(100),codesCursor:b.uuid().nullable(),redemptionsCursor:b.uuid().nullable()}).strict(),Gh=b.discriminatedUnion("action",[b.object({action:b.literal("create"),rewardId:b.uuid(),revision:b.number().int().nonnegative(),input:Fi}).strict(),b.object({action:b.literal("deactivate"),rewardId:b.uuid(),revision:b.number().int().nonnegative(),codeId:b.uuid()}).strict()]);import{z as g}from"zod";import{z as T}from"zod";var $i=T.array(T.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"),Vi=T.intersection(Je,T.object({tags:$i.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),qi=T.string().trim().max(80),Ni=T.union([T.email().max(254),T.literal("")]),Ui=T.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"\u8BBE\u5907\u6307\u7EB9\u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26"),Ns=T.object({externalUserId:T.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace").optional(),name:qi.default(""),email:Ni.default(""),attributes:Vi.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),sn=T.object({id:T.uuid(),externalUserId:T.string().min(1).max(255).nullable(),name:qi,email:Ni,attributes:Vi,revision:T.number().int().nonnegative(),createdAt:T.iso.datetime(),updatedAt:T.iso.datetime()}).strict(),Us=T.object({customer:sn,changed:T.boolean(),replayed:T.boolean()}).strict(),Pl=T.discriminatedUnion("type",[T.object({type:T.literal("id"),value:T.uuid()}).strict(),T.object({type:T.literal("externalUserId"),value:T.string().trim().min(1).max(255)}).strict()]),zl=T.object({name:qi.optional(),email:Ni.optional(),attributes:Vi.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:T.array(T.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:T.strictObject({add:$i,remove:$i}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Mi=T.object({lookup:Pl}).strict(),Ms=Mi.extend({revision:T.number().int().nonnegative(),requestId:T.uuid(),patch:zl}).strict(),Ls=T.object({search:T.string().trim().max(200).default(""),tag:T.string().trim().max(40).default(""),planId:T.union([T.uuid(),T.literal("")]).default(""),versionId:T.union([T.uuid(),T.literal("")]).default(""),holdingStatus:T.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:T.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:T.union([T.iso.datetime(),T.literal("")]).default(""),createdUntil:T.union([T.iso.datetime(),T.literal("")]).default(""),offset:T.coerce.number().int().min(0).max(1e5).default(0),limit:T.coerce.number().int().min(1).max(100).default(50)}).strict(),Gs=T.object({customers:sn.array(),hasMore:T.boolean(),total:T.number().int().nonnegative().nullable(),evaluatedAt:T.iso.datetime()}).strict();var _l=g.enum(["customers:read","customers:write","entitlements:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage"]),Ks={scope:be,permissions:g.array(_l),expiresAt:g.iso.datetime().nullable()},wb=g.discriminatedUnion("kind",[g.object({...Ks,kind:g.literal("server"),keyId:g.string().min(1)}),g.object({...Ks,kind:g.literal("customer"),customerId:g.string().min(1),identityKind:g.enum(["identified","guest"]),expiresAt:g.iso.datetime()})]),k=g.object({requestId:g.uuid(),scope:be}).strict(),Rl=Ns.safeExtend({fingerprint:Ui.optional()}).strict(),El=k.extend({customer:sn,created:g.boolean()}),Tl=g.enum(["unassigned","unknown","scheduled","active","expired"]),vb=g.object({customerId:g.string().min(1),evaluatedAt:g.iso.datetime(),status:Tl,validity:Zr.nullable(),planVersion:_o.nullable(),holdings:g.array(g.object({id:g.uuid(),planVersionId:g.uuid(),source:g.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:g.array(g.object({featureId:g.string(),featureKey:g.string(),featureName:g.string(),type:g.enum(["boolean","metered"]),allowance:g.number().int().nonnegative().nullable(),used:g.number().finite().nonnegative(),remaining:g.number().finite().nonnegative().nullable(),allowed:g.boolean(),sources:g.array(g.object({holdingId:g.uuid(),planVersionId:g.uuid(),group:g.string(),kind:g.enum(["main","addon"]),allowance:g.number().nullable()})).optional()}))}),Ab=g.enum(["UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","INTERNAL_ERROR"]);function Qs(){return k.extend({offer:pi.nullable(),reason:Jn.nullable()})}var A={readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:g.strictObject({customerId:g.uuid(),sourceId:g.uuid()}),response:k.extend({balance:ws})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:g.strictObject({customerId:g.uuid(),command:Is}),response:k.extend({balance:Ti})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:g.strictObject({entitlementId:g.uuid()}),response:k.extend({entitlementVersionId:g.uuid(),configuration:Nn})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:g.strictObject({customerId:g.uuid(),query:ar}),response:k.extend({usage:kn})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:g.strictObject({customerId:g.uuid(),command:La}),response:k.extend({usage:kn})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:g.strictObject({customerId:g.uuid(),command:Ba}),response:k.extend({grant:wi})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:$a,response:k.extend({grants:Va})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:g.union(ys.options.map(e=>e.extend({customerId:g.uuid().optional()}))),response:k.extend({operation:xs})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:ss.extend({customerId:g.uuid().optional()}),response:k.extend({setup:Ri})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:cs.extend({customerId:g.uuid().optional()}),response:k.extend({setup:Ri})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:os.safeExtend({customerId:g.uuid()}),response:k.extend({batch:Pn})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ur.extend({customerId:g.uuid()}),response:k.extend({batch:Pn})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ur.extend({customerId:g.uuid()}),response:k.extend({batch:Pn})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ur.extend({customerId:g.uuid()}),response:k.extend({batch:Pn})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:g.discriminatedUnion("action",[lr.options[0].extend({customerId:g.uuid()}),lr.options[1].extend({customerId:g.uuid()}),lr.options[2].extend({customerId:g.uuid()})]),response:k.extend({trial:_i})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:as.extend({customerId:g.uuid()}),response:k.extend({trial:_i})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:pr,response:k.extend({subscriptions:gs})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:pr,response:k.extend({purchases:hs})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:ms,response:k.extend({conflicts:bs})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:ps,response:k.extend({resolution:fs})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:ls,response:k.extend({verification:ds})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:es.safeExtend({customerId:g.uuid().optional()}),response:k.extend({quote:ts})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Mt.extend({customerId:g.uuid().optional(),intent:g.enum(["confirm","cancel"]).optional()}),response:k.extend({operation:ki})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Mt.extend({customerId:g.uuid().optional()}),response:k.extend({operation:ki})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:ns.safeExtend({customerId:g.uuid().optional()}),response:k.extend({quote:rs})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Mt.extend({customerId:g.uuid().optional(),intent:g.enum(["confirm","cancel"]).optional()}),response:k.extend({operation:Ci})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Mt.extend({customerId:g.uuid().optional()}),response:k.extend({operation:Ci})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Oi.extend({customerId:g.uuid()}),response:k.extend({quote:is})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Mt.extend({customerId:g.uuid()}),response:k.extend({operation:Pi})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Mt.extend({customerId:g.uuid()}),response:k.extend({operation:Pi})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:ba,response:k.extend({controls:fi})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:nn,response:k.extend({prepared:ma})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:pa,response:k.extend({authorization:Xn})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Ia,response:k.extend({coupons:wa})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:fa,response:k.extend({authorization:Xn})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:xa,response:k.extend({invoices:Sa})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:ya,response:k.extend({invoice:yn})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:g.object({customerId:g.uuid(),command:ha}).strict(),response:k.extend({controls:fi})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:g.object({customerId:g.uuid(),command:vs}).strict(),response:k.extend({entity:As})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:g.strictObject({customerId:g.uuid().nullable(),query:Os}),response:k.extend({analytics:Ps})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:g.object({customerId:g.uuid().nullable(),query:Gt}).strict(),response:k.extend({analytics:js})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:zs,response:k.extend({batchId:g.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:_s,response:k.extend({batch:Rs})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:g.object({customerId:g.uuid().optional(),entityId:g.uuid().optional()}).strict(),response:k.extend({holdings:Ga})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:g.object({customerId:g.uuid().optional(),query:Qa}).strict(),response:k.extend({ledger:Wa})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:qa.extend({customerId:g.uuid().optional()}),response:k.extend({detail:Na})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:vi.safeExtend({customerId:g.uuid().optional()}),response:k.extend({statement:Ua})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:g.object({customerId:g.uuid().optional(),command:An.options[0]}).strict(),response:k.extend({quote:Ta})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:g.object({customerId:g.uuid(),command:An.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:k.extend({receipt:or})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Fs,response:k.extend({redemption:Bi})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Vs,response:k.extend({referralCode:qs})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Bs,response:k.extend({checkout:$s})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Za,response:k.extend({seats:Ai})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Ha,response:k.extend({seats:Ai})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:Rl,response:El},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Mi,response:k.extend({customer:sn})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Ls,response:k.extend(Gs.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Ms,response:k.extend(Us.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:g.object({customerId:g.uuid()}).strict(),response:k.extend({customerToken:g.string().min(1),expiresAt:g.iso.datetime(),sessionId:g.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:g.strictObject({customerId:g.uuid(),customerToken:g.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:k.extend({customerToken:g.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:g.uuid(),expiresAt:g.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:g.strictObject({customerId:g.uuid(),sessionId:g.uuid().optional()}),response:k.extend({revoked:g.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:g.strictObject({guestToken:g.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ui.optional()}),response:k.extend({customerId:g.uuid(),guestToken:g.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:g.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:g.strictObject({guestToken:g.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:k.extend({customerId:g.uuid(),customerToken:g.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:g.uuid(),expiresAt:g.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:g.strictObject({guestToken:g.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:g.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:g.uuid()}),response:k.extend({customer:sn,merged:g.boolean(),replayed:g.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:g.strictObject({code:g.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:g.uuid()}),response:Qs()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:g.object({}).strict(),response:k.extend({offers:g.array(pi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"server",request:g.object({customerId:g.string().min(1).max(255),couponId:g.uuid(),requestId:g.uuid()}).strict(),response:Qs()}},kb={setupPayment:A.setupPayment,readPaymentSetup:A.readPaymentSetup,previewSubscriptionBatch:A.previewSubscriptionBatch,confirmSubscriptionBatch:A.confirmSubscriptionBatch,readSubscriptionBatch:A.readSubscriptionBatch,abandonSubscriptionBatch:A.abandonSubscriptionBatch,manageSubscriptionTrial:A.manageSubscriptionTrial,readSubscriptionTrial:A.readSubscriptionTrial,listSubscriptions:A.listSubscriptions,listPurchases:A.listPurchases,listSubscriptionConflicts:A.listSubscriptionConflicts,retrySubscriptionConflict:A.retrySubscriptionConflict,readAiPricing:A.readAiPricing,readUsage:A.readUsage,setUsage:A.setUsage,previewRefund:A.previewRefund,refund:A.refund,readRefund:A.readRefund,previewUpdate:A.previewUpdate,update:A.update,readSubscriptionUpdate:A.readSubscriptionUpdate,restoreNativePurchase:A.restoreNativePurchase,verifySubscriptions:A.verifySubscriptions,previewAttach:A.previewAttach,attach:A.attach,readSubscriptionOperation:A.readSubscriptionOperation,manageBalanceGrant:A.manageBalanceGrant,readBalanceSource:A.readBalanceSource,adjustBalance:A.adjustBalance,listBalanceGrants:A.listBalanceGrants,readBillingControls:A.readBillingControls,prepareBillingAuthorization:A.prepareBillingAuthorization,confirmBillingAuthorization:A.confirmBillingAuthorization,setBillingCoupons:A.setBillingCoupons,revokeBillingAuthorization:A.revokeBillingAuthorization,listBillingInvoices:A.listBillingInvoices,confirmBillingAdjustment:A.confirmBillingAdjustment,manageBillingLimits:A.manageBillingLimits,createCustomer:A.createCustomer,getCustomer:A.getCustomer,listCustomers:A.listCustomers,updateCustomer:A.updateCustomer,createSession:A.createSession,renewSession:A.renewSession,revokeSessions:A.revokeSessions,createGuestCustomer:A.createGuestCustomer,resumeGuestSession:A.resumeGuestSession,claimGuestCustomer:A.claimGuestCustomer,readHoldings:A.readHoldings,readLedger:A.readLedger,readBillingInvoice:A.readBillingInvoice,readCreditStatement:A.readCreditStatement,quoteBalance:A.quoteBalance,mutateBalance:A.mutateBalance,manageUsageEntity:A.manageUsageEntity,readUsageAnalytics:A.readUsageAnalytics,readCreditAnalytics:A.readCreditAnalytics,submitUsageBatch:A.submitUsageBatch,readUsageBatch:A.readUsageBatch,listOffers:A.listOffers,grantOffer:A.grantOffer,redeemCoupon:A.redeemCoupon,redeemReward:A.redeemReward,createReferralCode:A.createReferralCode,claimRewardProduct:A.claimRewardProduct,readSeats:A.readSeats,manageSeat:A.manageSeat};import{z as B}from"zod";var Dl=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at"],Zs=B.object({plan:B.uuid().optional(),coupon:B.uuid().optional(),promotionCode:B.uuid().optional(),picker:B.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ws=B.object({text:B.string().optional(),label:B.string().optional(),alt:B.string().optional(),html:B.string().max(32768).optional(),price:B.object({current:B.string(),original:B.string().nullable(),period:B.string()}).optional(),code:B.string().optional(),countdownAt:B.iso.datetime().optional(),planId:B.uuid().optional(),planVersionId:B.uuid().optional(),currency:z.optional(),couponId:B.uuid().optional(),offerId:B.uuid().optional(),unavailable:B.boolean().optional(),unavailableReason:B.string().optional(),missing:B.array(B.string()).optional()}).strict(),Hs=B.object({nodes:B.record(B.string(),B.object({base:Ws,picker:B.string().optional(),byPlan:B.record(B.string(),Ws).optional()}).strict()),plans:B.record(B.string(),B.object({id:B.uuid(),versionId:B.uuid(),name:B.string(),price:B.string(),period:B.string(),currency:z.optional()}).strict()),pickers:B.record(B.string(),B.object({options:B.array(B.uuid()).max(20),selected:B.uuid().nullable()}).strict()),diagnostics:B.array(B.object({nodeId:B.string(),message:B.string()}).strict())}).strict();function fr(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].map(t=>t[1].trim())}function gr(e){let t=fr(e).filter(r=>!Dl.includes(r)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function Pb(e,t,n,r=!1){let i=fr(e).filter(o=>!/^(input|params)\.[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(o)&&t[o]===void 0);return i.length&&!r?{value:n,missing:i}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(o,a)=>t[a.trim()]??o),missing:i}}function zb(e,t,n={}){let r=e?.nodes[t];if(!r)return;let i=r.picker?n[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof i=="string"?r.byPlan?.[i]??r.base:r.base}import{z as l}from"zod";import{z as E}from"zod";var Fl=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Js=E.enum(Fl),Ys=E.object({source:Js,layout:E.enum(["full","compact"]),resourceKey:mn.optional(),pageSize:E.number().int().min(1).max(50),showSources:E.boolean(),allowPurchase:E.boolean(),outputs:E.object({billing_adjustment:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((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"})}),Ie=E.string().max(2e3),Xs=E.object({id:E.string().max(100),label:Ie,detail:E.array(Ie).max(12),value:Ie.optional(),status:Ie.optional(),facts:E.array(E.object({label:Ie,value:Ie}).strict()).max(1e3),purchaseId:E.uuid().optional(),invoiceUrl:E.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:E.array(E.strictObject({action:E.literal("invoice_open"),label:Ie})).max(1).optional(),membershipActions:E.array(E.object({value:E.string().max(100),label:Ie}).strict()).max(3).optional()}).strict(),Bl=E.object({key:mn,name:Ie,spendable:Ie,reserved:Ie,available:Ie,expiry:Ie.nullable(),sources:E.array(Xs).max(50),sourceCount:E.number().int().nonnegative(),sourcePage:E.number().int().positive(),hasNextSources:E.boolean(),hasPreviousSources:E.boolean()}).strict(),$l=E.object({source:Js,status:E.enum(["idle","loading","ready","error"]),stale:E.boolean(),preview:E.boolean(),errorCode:E.string().max(80).optional(),errorMessage:Ie.optional(),resources:E.array(Bl).max(500),rows:E.array(Xs).max(50),hasNext:E.boolean(),hasPrevious:E.boolean(),page:E.number().int().positive(),filter:E.string().max(40),updatedAt:E.iso.datetime().optional(),buyingId:E.uuid().optional(),membershipBusy:E.boolean().optional(),billingBusy:E.boolean().optional(),membershipReview:E.object({title:Ie,note:Ie,facts:E.array(E.object({label:Ie,value:Ie}).strict()).max(100)}).strict().optional(),membershipResult:Ie.optional()}).strict(),ec=E.object({nodes:E.record(E.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),$l)}).strict(),Tb=E.object({nodeId:E.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:E.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:E.string().max(100).optional()}).strict();function tc(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function Li(e){let t=gr(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let o=e[n];if(i)o===i&&(i="");else if(o==='"'||o==="'")i=o;else if(o===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function nc(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Bb(e,t,n,r=!1){let i=Li(e);if(i.length)throw new Error(i[0]);let o=[...new Set(fr(e).filter(a=>t[a]===void 0))];return o.length&&!r?{value:nc(n),missing:o}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(a,s)=>t[s.trim()]===void 0?a:nc(t[s.trim()])),missing:o}}var Vl=3,tt={nodes:150,depth:8,children:50,locales:20,actions:40,pages:1,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},oc=l.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),de=l.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ql=l.enum(["none","xs","sm","md","lg","xl"]),Nl=l.enum(["none","sm","md","lg","full"]),Gi=l.string().regex(/^#[0-9a-fA-F]{6}$/),ac=l.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"),Ki=l.union([ac,l.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),l.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),l.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),rc=l.object({primary:Gi,background:Gi,text:Gi,radius:Nl,font:l.enum(["system","serif","rounded","mono"])}).strict(),zn=l.union([l.enum(["primary","text","muted","background","surface"]),l.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),re=(e,t)=>l.number().int().min(e).max(t),ic=l.union([l.enum(["fit","fill"]),re(1,1200)]),Ul=l.object({top:re(0,200),right:re(0,200),bottom:re(0,200),left:re(0,200)}).strict(),Ml=l.object({top:re(-100,200),right:re(-100,200),bottom:re(-100,200),left:re(-100,200)}).strict(),sc=l.object({x:re(0,100),y:re(0,100)}).strict(),Ll=l.discriminatedUnion("type",[l.object({type:l.literal("color"),color:zn}).strict(),l.object({type:l.literal("linear"),angle:re(0,360),stops:l.array(l.object({color:zn,at:re(0,100)}).strict()).min(2).max(4)}).strict(),l.object({type:l.literal("image"),src:Ki,fit:l.enum(["cover","contain"]),position:sc.optional()}).strict()]),Gl=l.discriminatedUnion("type",[l.object({type:l.literal("rect"),radius:l.union([re(0,200),l.object({topLeft:re(0,200),topRight:re(0,200),bottomRight:re(0,200),bottomLeft:re(0,200)}).strict()])}).strict(),l.object({type:l.literal("pill")}).strict()]),Kl=l.object({width:re(0,12),color:zn,style:l.enum(["solid","dashed"])}).strict(),Ql=l.object({x:re(-40,40),y:re(-40,40),blur:re(0,80),spread:re(-20,40),color:zn}).strict(),Wl=l.object({font:l.enum(["system","serif","rounded","mono"]),size:re(8,96),weight:l.number().int().min(100).max(900).multipleOf(100),lineHeight:l.number().min(.8).max(3),letterSpacing:l.number().min(-5).max(20),color:zn,align:l.enum(["start","center","end"]),italic:l.boolean(),decoration:l.enum(["none","underline","line-through"]),transform:l.enum(["none","uppercase"])}).strict().partial(),cn=l.object({width:ic,height:ic,padding:Ul,margin:Ml,gap:re(0,120),grow:l.union([l.boolean(),l.number().min(0).max(12)]),background:Ll,opacity:l.number().min(0).max(1),clipContent:l.boolean(),shape:Gl,border:Kl,shadow:Ql,text:Wl}).strict().partial(),Qe={id:oc,name:l.string().trim().min(1).max(60).optional(),hidden:l.boolean().optional(),style:cn.optional(),fallback:de.optional()},Zl=l.object({...Qe,type:l.literal("text"),text:de,variant:l.enum(["title","heading","body","caption"])}).strict(),Hl=l.object({...Qe,type:l.literal("image"),src:Ki,localizedSrc:l.record(ft,Ki).optional(),alt:de,aspect:l.enum(["auto","1:1","4:3","16:9","3:1"]),fit:l.enum(["cover","contain"]),position:sc.optional()}).strict(),Jl=l.object({...Qe,type:l.literal("button"),label:de,variant:l.enum(["primary","secondary","link"]),action:de}).strict(),Yl=l.object({...Qe,type:l.literal("divider")}).strict(),Xl=l.object({...Qe,type:l.literal("customer_data"),title:de,data:Ys}).strict(),ed=l.object({...Qe,type:l.literal("spacer"),size:ql}).strict(),td=l.object({...Qe,type:l.literal("custom_html"),html:l.record(ft,l.string().max(tt.customHtml)),css:l.string().max(tt.customCss)}).strict(),nd=l.object({...Qe,type:l.literal("price"),fallback:de,parts:l.object({current:cn.optional(),original:cn.optional(),period:cn.optional()}).strict().optional()}).strict(),rd=l.object({...Qe,type:l.literal("coupon_code"),label:de,fallback:de}).strict(),id=l.object({...Qe,type:l.literal("countdown"),source:l.enum(["offer.ends_at","offer.expires_at","fixed"]),at:l.iso.datetime().optional(),granularity:l.enum(["day","hour","minute","second"]),expired:de,fallback:de}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),od=l.object({...Qe,type:l.literal("plan_picker"),label:de,fallback:de,planIds:l.array(l.uuid()).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:l.uuid().optional(),states:l.object({selected:cn.optional()}).strict().optional()}).strict(),ad=l.discriminatedUnion("type",[l.object({type:l.literal("input"),label:de,keyboard:l.enum(["text","email","tel","url"]),maxLength:re(1,500)}).strict(),l.object({type:l.literal("multiselect"),label:de,min:re(0,50),max:re(1,50)}).strict(),l.object({type:l.literal("select"),label:de,defaultIndex:re(0,49),purpose:l.enum(["option","package","tier"]).optional(),selectedStyle:cn.optional()}).strict(),l.object({type:l.literal("tabs"),label:de,defaultIndex:re(0,49),purpose:l.literal("tier").optional()}).strict(),l.object({type:l.literal("toggle"),label:de,defaultEnabled:l.boolean()}).strict(),l.object({type:l.literal("carousel"),label:de}).strict()]),cc=l.lazy(()=>l.object({...Qe,type:l.literal("stack"),direction:l.enum(["vertical","horizontal","overlay"]),align:l.enum(["start","center","end","stretch"]),justify:l.enum(["start","center","end","between"]),children:l.array(sd).max(tt.children),interaction:ad.optional(),bind:Zs.optional()}).strict()),sd=l.lazy(()=>l.union([cc,Zl,Hl,Jl,Yl,ed,td,nd,rd,id,od,Xl])),cd=l.union([l.string().max(500),l.number().finite(),l.boolean(),l.null()]),hr={id:de,event:de,properties:l.record(de,cd).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ud=l.discriminatedUnion("type",[l.object({...hr,type:l.literal("event"),close:l.boolean()}).strict(),l.object({...hr,type:l.literal("close"),close:l.literal(!0)}).strict(),l.object({...hr,type:l.literal("open_url"),close:l.boolean(),url:ac}).strict(),l.object({...hr,type:l.literal("claim_offer"),close:l.boolean(),couponId:l.uuid()}).strict()]),ld=l.object({defaultLocale:ft,locales:l.record(ft,l.record(de,l.string().max(tt.stringLength)))}).strict(),Qi=l.enum(["popup","paywall","onboarding","page"]),Lb={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},dd=l.discriminatedUnion("type",[l.object({type:l.literal("modal"),size:l.enum(["sm","md","lg"])}).strict(),l.object({type:l.literal("sheet"),size:l.enum(["sm","md","lg"])}).strict(),l.object({type:l.literal("fullscreen")}).strict()]),Gb={sm:360,md:420,lg:560},md=l.object({kind:l.literal("screen"),schemaVersion:l.literal(Vl),name:l.string().trim().min(1).max(80),surface:Qi,presentation:dd,theme:rc,pages:l.array(l.object({id:oc,name:l.string().trim().min(1).max(60),root:cc,theme:rc.optional(),editorPosition:l.object({x:l.number().finite().min(-1e5).max(1e5),y:l.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(tt.pages),strings:ld,actions:l.array(ud).max(tt.actions)}).strict();function nt(e,t){for(let n of e.pages)Pt(n.root,t)}function Kb(e,t){return{...e,pages:e.pages.map((n,r)=>r===0?{...n,root:t}:n)}}var We=md.superRefine((e,t)=>{let n=tt;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=u=>t.addIssue({code:"custom",message:u}),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>tt.locales&&r(`\u6700\u591A ${tt.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let u of e.actions)o.has(u.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${u.id}`),o.add(u.id);let a=new Set;for(let u of e.pages)["next","back"].includes(u.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${u.id}`),a.has(u.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${u.id}`),a.add(u.id);let s=new Set,c=0,p=!1;nt(e,(u,S)=>{if(c++,S>tt.depth&&(p=!0),s.has(u.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${u.id}`),s.add(u.id),u.type==="button"&&!o.has(u.action)&&r(`\u6309\u94AE ${u.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${u.action}`),u.type==="custom_html")for(let Q of Object.keys(u.html))i.includes(Q)||r(`\u81EA\u5B9A\u4E49 HTML ${u.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${Q}`);if(u.type==="image")for(let Q of Object.keys(u.localizedSrc??{}))i.includes(Q)||r(`\u56FE\u7247 ${u.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${Q}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),p&&r(`\u5C42\u7EA7\u6700\u591A ${tt.depth} \u5C42`)});function Pt(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Pt(i,t,n+1,e)}function Wi(e){let t=[],n=new Set;return nt(e,r=>{let i=(o,a,s)=>{n.has(o)||(n.add(o),t.push({key:o,nodeId:r.id,nodeType:r.type,field:a,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==="coupon_code")&&i(r.label,"label",!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 pd(e,t,n){if(t.field==="html"){let r;return nt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=br(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 un(e){let t=Wi(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(o=>!pd(e,o,r)?.trim()).map(o=>o.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Qb(e){let t=[],n=e.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"));n&&(!e.actions.some(c=>c.type==="claim_offer")||e.actions.some(c=>c.type==="event"&&typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-")))&&t.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function r(c,p){let u=c.type==="stack"?c.bind?.coupon??p:p;if(n&&c.type==="text"&&Object.values(e.strings.locales).some(S=>S[c.text]?.includes("{{offer."))&&!u&&t.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),c.type==="button"){let S=e.actions.find(Q=>Q.id===c.action);S?.type==="claim_offer"&&u&&u!==S.couponId&&t.push(`\u9886\u53D6\u6309\u94AE ${c.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}c.type==="stack"&&c.children.forEach(S=>r(S,u))}e.pages.forEach(c=>r(c.root));let i=[],o=We.safeParse(e);o.success||t.push(...o.error.issues.map(c=>c.message));for(let c of Object.values(e.strings.locales))for(let p of Object.values(c))for(let u of gr(p))t.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${u}`);nt(e,c=>{if(c.type==="customer_data"&&Object.values(e.strings.locales).some(u=>/\{\{|\}\}/.test(u[c.title]??""))&&t.push(`\u6570\u636E\u7EC4\u4EF6 ${c.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(c.type==="text"?[c.text]:c.type==="button"?[c.label]:[]).some(u=>Object.values(e.strings.locales).some(S=>S[u]?.includes("{{")))&&!c.fallback&&t.push(`\u7EC4\u4EF6 ${c.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),c.fallback&&Object.values(e.strings.locales).some(u=>u[c.fallback]?.includes("{{"))&&t.push(`\u7EC4\u4EF6 ${c.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),c.type==="custom_html"){for(let u of Object.values(c.html))t.push(...Li(u).map(S=>`HTML ${c.id}\uFF1A${S}`));Object.values(c.html).some(u=>u.includes("{{"))&&!c.fallback&&t.push(`HTML ${c.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{|\}\}/.test(c.css)&&t.push(`HTML ${c.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}c.type==="stack"&&c.bind?.picker&&br(e,c.bind.picker)?.type!=="plan_picker"&&t.push(`\u5BB9\u5668 ${c.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});let a=un(e);for(let c of a)c.complete||(c.locale===e.strings.defaultLocale?t.push(`\u9ED8\u8BA4\u8BED\u8A00 ${c.locale} \u8FD8\u6709 ${c.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):t.push(`${c.locale} \u8FD8\u6709 ${c.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));Wi(e).length===0&&!e.pages.some(c=>fd(c.root))&&t.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let s=new Set;nt(e,c=>{c.type==="button"&&s.add(c.action)});for(let c of e.actions)!s.has(c.id)&&!e.pages.some(p=>gd(p.root,c.id))&&i.push(`\u52A8\u4F5C ${c.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:t,warnings:i}}function fd(e){let t=!1;return Pt(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function gd(e,t){let n=!1;return Pt(e,r=>{if(r.type==="custom_html")for(let i of Object.values(r.html))i.includes(`data-grow-action="${t}"`)&&(n=!0)}),n}function hd(e){return un(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Zi(e,t){return Hn(t,hd(e),e.strings.defaultLocale)}function Wb(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let a of Wi(e)){if(a.field==="html"||a.field==="src")continue;let s=n[a.key]?.trim()?n[a.key]:r[a.key];s!==void 0&&(i[a.key]=s)}let o=a=>{if(a.type==="stack")return{...a,children:a.children.map(o)};if(a.type==="custom_html"){let s=a.html[t]?.trim()?a.html[t]:a.html[e.strings.defaultLocale];return{...a,html:s===void 0?{}:{[t]:s}}}if(a.type==="image"){let{localizedSrc:s,...c}=a;return{...c,src:s?.[t]??s?.[e.strings.defaultLocale]??a.src}}return a};return{...e,pages:e.pages.map(a=>({...a,root:o(a.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function bd(e,t){let n=null;return Pt(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function br(e,t){for(let n of e.pages){let r=bd(n.root,t);if(r)return r}return null}function Zb(e){let t=$t(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function Hb(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;return nt(e,o=>{if(o.type==="plan_picker"){let s=i[o.id];typeof s=="string"&&n?.pickers[o.id]?.options.includes(s)&&(r[o.id]=s);return}if(o.type!=="stack"||!o.interaction)return;let a=Object.hasOwn(i,o.id)?i[o.id]:void 0;["select","tabs"].includes(o.interaction.type)&&typeof a=="string"&&o.children.some(s=>s.id===a)&&(r[o.id]=a),o.interaction.type==="toggle"&&typeof a=="boolean"&&(r[o.id]=a)}),r}var we={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},uc="00000000-0000-0000-0000-000000000000";var dc={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},_n=(e,t,n,r,i)=>({kind:"screen",schemaVersion:3,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...dc},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),ln=e=>({type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",children:e,style:{gap:12,padding:{top:24,right:24,bottom:24,left:24}}}),yr={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},lc=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:_n("\u672A\u547D\u540D\u5F39\u7A97",ln([{type:"text",id:"title",text:"title",variant:"heading"},{type:"button",id:"cta",label:"cta",variant:"primary",action:"dismiss",style:{width:"fill"}}]),{title:"\u6807\u9898",cta:"\u77E5\u9053\u4E86"},{title:"Title",cta:"Got it"},[yr])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:_n("\u65B0\u529F\u80FD\u516C\u544A",ln([{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{text:{color:"primary",weight:700}}},{type:"text",id:"title",text:"title",variant:"heading"},{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"learn_more",style:{width:"fill"}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}]),{eyebrow:"\u65B0\u529F\u80FD",title:"\u73B0\u5728\u53EF\u4EE5\u4E00\u952E\u5BFC\u51FA\u62A5\u8868",body:"\u5728\u4EFB\u610F\u6570\u636E\u9875\u70B9\u51FB\u53F3\u4E0A\u89D2\u300C\u5BFC\u51FA\u300D\uFF0C\u5373\u53EF\u4E0B\u8F7D CSV \u6216 PDF\u3002",cta:"\u53BB\u770B\u770B",later:"\u4EE5\u540E\u518D\u8BF4"},{eyebrow:"NEW",title:"Export reports in one click",body:"Click Export on any data page to download a CSV or PDF.",cta:"Take a look",later:"Not now"},[{id:"learn_more",type:"event",event:"announcement_clicked",properties:{},close:!0},yr])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:_n("\u5347\u7EA7\u5230 Pro",ln([{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{text:{color:"primary",weight:700}}},{type:"text",id:"title",text:"title",variant:"heading"},{type:"stack",id:"benefits",name:"\u6743\u76CA\u5217\u8868",direction:"vertical",align:"stretch",justify:"start",children:[{type:"text",id:"benefit1",text:"benefit1",variant:"body"},{type:"text",id:"benefit2",text:"benefit2",variant:"body"},{type:"text",id:"benefit3",text:"benefit3",variant:"body"}],style:{background:{type:"color",color:"surface"},shape:{type:"rect",radius:8},gap:4,padding:{top:16,right:16,bottom:16,left:16}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"upgrade",style:{width:"fill"}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}]),{eyebrow:"PRO",title:"\u89E3\u9501\u5168\u90E8\u9AD8\u7EA7\u529F\u80FD",benefit1:"\u2713 \u65E0\u9650\u9879\u76EE\u4E0E\u6210\u5458",benefit2:"\u2713 \u9AD8\u7EA7\u6570\u636E\u5206\u6790",benefit3:"\u2713 \u4F18\u5148\u5BA2\u670D\u652F\u6301",cta:"\u67E5\u770B Pro \u65B9\u6848",later:"\u7EE7\u7EED\u4F7F\u7528\u514D\u8D39\u7248"},{eyebrow:"PRO",title:"Unlock every advanced feature",benefit1:"\u2713 Unlimited projects and members",benefit2:"\u2713 Advanced analytics",benefit3:"\u2713 Priority support",cta:"See Pro plans",later:"Stay on Free"},[{id:"upgrade",type:"event",event:"checkout_requested",properties:{planId:"pro"},close:!0},yr])},{id:"offer",label:"\u9650\u65F6\u4F18\u60E0",description:"\u6E10\u53D8\u5934\u56FE + \u89D2\u6807 + \u539F\u4EF7\u5212\u7EBF\u7684\u4F18\u60E0\u4EF7\uFF0C\u9002\u5408\u9886\u5238\u5F39\u7A97\u3002",document:{..._n("\u9650\u65F6\u4F18\u60E0",{type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",children:[{type:"stack",id:"hero",name:"\u5934\u56FE",direction:"overlay",align:"start",justify:"start",children:[{type:"stack",id:"heroContent",name:"\u5934\u56FE\u5185\u5BB9",direction:"vertical",align:"center",justify:"center",children:[{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{width:"fit",padding:{top:3,right:10,bottom:3,left:10},background:{type:"color",color:"#FFFFFF2E"},shape:{type:"pill"},text:{color:"#FFFFFF",weight:700,letterSpacing:1,align:"center"}}},{type:"text",id:"title",text:"title",variant:"title",style:{text:{size:40,weight:900,color:"#FFFFFF",align:"center",lineHeight:1.1}}},{type:"text",id:"subtitle",text:"subtitle",variant:"body",style:{text:{size:14,color:"#FFFFFFD9",align:"center"}}}],style:{width:"fill",padding:{top:32,right:24,bottom:28,left:24},gap:6}},{type:"text",id:"badge",name:"\u89D2\u6807",text:"badge",variant:"caption",style:{width:"fit",margin:{top:14,right:0,bottom:0,left:14},padding:{top:4,right:10,bottom:4,left:10},background:{type:"color",color:"#FFD84D"},shape:{type:"pill"},shadow:{x:0,y:4,blur:10,spread:0,color:"#00000026"},text:{color:"#3A1D00",weight:800,size:13}}}],style:{gap:0,padding:{top:0,right:0,bottom:0,left:0},background:{type:"linear",angle:135,stops:[{color:"#FF7A45",at:0},{color:"#E8336D",at:100}]}}},{type:"stack",id:"body",name:"\u4EF7\u683C\u4E0E\u6309\u94AE",direction:"vertical",align:"stretch",justify:"start",children:[{type:"stack",id:"price",name:"\u4EF7\u683C",direction:"horizontal",align:"end",justify:"center",children:[{type:"text",id:"newPrice",text:"newPrice",variant:"title",style:{text:{size:34,weight:800,color:"#E8336D",lineHeight:1}}},{type:"text",id:"period",text:"period",variant:"body",style:{text:{color:"muted",size:14,lineHeight:1.6}}},{type:"text",id:"oldPrice",text:"oldPrice",variant:"body",style:{text:{color:"muted",size:15,decoration:"line-through",lineHeight:1.6}}}],style:{gap:8,padding:{top:0,right:0,bottom:0,left:0}}},{type:"text",id:"then",text:"then",variant:"caption",style:{text:{color:"muted",align:"center"}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"claim",style:{width:"fill",height:52,background:{type:"linear",angle:90,stops:[{color:"#FF7A45",at:0},{color:"#E8336D",at:100}]},shape:{type:"pill"},shadow:{x:0,y:10,blur:24,spread:-6,color:"#E8336D66"},text:{size:17,weight:800,color:"#FFFFFF"}}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}],style:{gap:14,padding:{top:22,right:24,bottom:22,left:24}}}],style:{gap:0,padding:{top:0,right:0,bottom:0,left:0}}},{eyebrow:"\u9650\u65F6 48 \u5C0F\u65F6",title:"\u9996\u6708 7 \u6298",subtitle:"\u65B0\u7528\u6237\u4E13\u4EAB \xB7 \u9886\u53D6\u540E 3 \u5929\u5185\u6709\u6548",badge:"-30%",newPrice:"$20.30",period:"/\u9996\u6708",oldPrice:"$29",then:"\u4E4B\u540E\u6BCF\u6708 $29\uFF0C\u53EF\u968F\u65F6\u53D6\u6D88",cta:"\u7ACB\u5373\u9886\u53D6",later:"\u6682\u4E0D\u9700\u8981"},{eyebrow:"48 HOURS ONLY",title:"30% off",subtitle:"For new members \xB7 valid 3 days after claiming",badge:"-30%",newPrice:"$20.30",period:"/first month",oldPrice:"$29",then:"Then $29/month. Cancel anytime.",cta:"Claim offer",later:"Not now"},[{id:"claim",type:"event",event:"offer_claimed",properties:{discount:30},close:!0},yr]),theme:{...dc,primary:"#E8336D",radius:"lg"}}},{id:"feedback",label:"\u6536\u96C6\u53CD\u9988",description:"\u4E24\u4E2A\u9009\u9879\u6309\u94AE\uFF0C\u8BB0\u5F55\u7528\u6237\u7684\u9009\u62E9\u3002",document:_n("\u6EE1\u610F\u5EA6\u8C03\u67E5",ln([{type:"text",id:"title",text:"title",variant:"heading",style:{text:{align:"center"}}},{type:"text",id:"body",text:"body",variant:"body",style:{text:{align:"center",color:"muted"}}},{type:"stack",id:"choices",name:"\u9009\u9879",direction:"horizontal",align:"stretch",justify:"center",children:[{type:"button",id:"yes",label:"yes",variant:"secondary",action:"positive",style:{width:"fill"}},{type:"button",id:"no",label:"no",variant:"secondary",action:"negative",style:{width:"fill"}}],style:{gap:8,padding:{top:0,right:0,bottom:0,left:0}}}]),{title:"\u8FD9\u4E2A\u529F\u80FD\u5BF9\u4F60\u6709\u5E2E\u52A9\u5417\uFF1F",body:"\u4F60\u7684\u53CD\u9988\u4F1A\u76F4\u63A5\u5F71\u54CD\u6211\u4EEC\u4E0B\u4E00\u6B65\u505A\u4EC0\u4E48\u3002",yes:"\u6709\u5E2E\u52A9",no:"\u6CA1\u5E2E\u52A9"},{title:"Was this feature helpful?",body:"Your answer shapes what we build next.",yes:"Yes",no:"No"},[{id:"positive",type:"event",event:"feedback_submitted",properties:{helpful:!0},close:!0},{id:"negative",type:"event",event:"feedback_submitted",properties:{helpful:!1},close:!0}])}];function xr(e="blank"){let t=lc.find(n=>n.id===e)??lc[0];return structuredClone(t.document)}var yd=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...ln(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...ln(n),id:`${e}_detail`,name:"\u5185\u5BB9\u4E0E\u64CD\u4F5C",style:{width:400,gap:20,padding:{top:24,right:24,bottom:24,left:24},background:{type:"color",color:"surface"},shape:{type:"rect",radius:8}}}],style:{gap:40,padding:{top:40,right:24,bottom:40,left:24}}});function Xb(e,t="blank"){let n=xr(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=xr("upgrade");r.actions=r.actions.map(o=>o.id==="upgrade"&&o.type==="event"?{...o,event:"paywall.upgrade_clicked",properties:{},close:!1}:o),r.strings.locales["zh-CN"].cta="\u4E86\u89E3\u5347\u7EA7\u65B9\u6848",r.strings.locales.en.cta="Explore upgrade options",r.strings.locales["zh-CN"].body="\u4E3A\u4F60\u7684\u5DE5\u4F5C\u533A\u9009\u62E9\u9002\u5408\u7684\u529F\u80FD\u4E0E\u534F\u4F5C\u65B9\u5F0F\u3002",r.strings.locales.en.body="Find the right features and collaboration tools for your workspace.";let i=r.pages[0].root.children;return r.pages[0].root=yd("root",[...i.slice(0,2),{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}}],i.slice(2)),{...r,surface:e,presentation:{type:"fullscreen"},name:"\u9AD8\u7EA7\u529F\u80FD\u4ED8\u8D39\u5899"}}return{...n,surface:e,presentation:{type:"fullscreen"}}}function mc(e,t){if(t!=="en"&&t!=="zh-CN")throw new Error("Unsupported blank content language");let n=t==="en"?{popup:"popup",paywall:"paywall",onboarding:"funnel",page:"page"}:{popup:"\u5F39\u7A97",paywall:"\u4ED8\u8D39\u5899",onboarding:"\u5F15\u5BFC\u6D41\u7A0B",page:"\u9875\u9762"},r=xr();return{...r,name:t==="en"?`Untitled ${n[e]}`:`\u672A\u547D\u540D${n[e]}`,surface:e,presentation:e==="popup"?{type:"modal",size:"md"}:{type:"fullscreen"},pages:[{id:"main",name:t==="en"?e==="onboarding"?"Start":"Main page":e==="onboarding"?"\u5F00\u59CB":"\u4E3B\u9875\u9762",root:{...r.pages[0].root,name:t==="en"?"Canvas":"\u753B\u5E03",style:e==="popup"?{height:280}:{},children:[]}}],strings:{defaultLocale:t,locales:{[t]:{}}},actions:[]}}import{z as q}from"zod";var Rn=q.number().int().min(0).max(1e4),oy=q.strictObject({couponId:q.uuid(),couponRevision:q.number().int().nonnegative(),audienceId:q.uuid(),audienceRevision:q.number().int().nonnegative(),audienceName:q.string().min(1).max(80),count:Rn,snapshotHash:q.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:q.iso.datetime({offset:!0})}),xd=q.strictObject({id:q.uuid(),couponId:q.uuid(),couponName:q.string().min(1).max(80),audienceId:q.uuid(),audienceName:q.string().min(1).max(80),audienceRevision:q.number().int().nonnegative(),status:q.enum(["pending","running","completed"]),total:Rn,issued:Rn,skipped:Rn,remaining:Rn,createdAt:q.iso.datetime({offset:!0}),completedAt:q.iso.datetime({offset:!0}).nullable()}).refine(e=>e.total>0&&e.total===e.issued+e.skipped+e.remaining&&e.status==="completed"==(e.completedAt!==null)&&(e.status!=="completed"||e.remaining===0)),Sd=q.strictObject({id:q.uuid(),customerId:q.uuid(),customerName:q.string().max(255),position:q.number().int().min(1).max(1e4),status:q.enum(["pending","issued","skipped"]),grantId:q.uuid().nullable(),reason:q.union([Jn,q.literal("customer_unavailable")]).nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),ay=q.strictObject({batch:xd,recipients:q.array(Sd).max(50),nextPosition:q.number().int().min(1).max(1e4).nullable()}),sy=q.discriminatedUnion("action",[q.strictObject({action:q.literal("create"),requestId:q.uuid(),couponId:q.uuid(),couponRevision:q.number().int().nonnegative(),audienceId:q.uuid(),audienceRevision:q.number().int().nonnegative(),snapshotHash:q.string().regex(/^[a-f0-9]{64}$/)}),q.strictObject({action:q.literal("process"),batchId:q.uuid()})]);import{z as En}from"zod";var Id=En.url().refine(e=>new URL(e).protocol==="https:"),ly=En.strictObject({requestId:En.uuid()}),dy=En.strictObject({url:Id,createdAt:En.iso.datetime()});import{z as me}from"zod";var pc=me.object({id:me.uuid(),key:me.string().nullable(),label:me.string().min(1).max(80),description:me.string().max(300),category:me.string().min(1).max(40),tags:me.array(me.string().max(30)).max(10),surface:Qi,source:me.enum(["official","private"]),document:We,revision:me.number().int().positive(),archived_at:me.string().nullable(),created_at:me.string()}).strict(),gy=me.object({projectId:me.uuid(),environmentId:me.uuid(),label:me.string().trim().min(1).max(80),description:me.string().trim().max(300),category:me.string().trim().min(1).max(40),document:We}).strict(),hy=me.object({projectId:me.uuid(),environmentId:me.uuid(),id:me.uuid(),revision:me.number().int().positive()}).strict();import{z as y}from"zod";import{z as W}from"zod";var zt=Me;function fc(e){let t={};for(let[n,r]of Object.entries(e.results??{})){let i=n.split(".");if(i.some(a=>["__proto__","constructor","prototype"].includes(a)))throw new Error("Reserved result path");let o=t;for(let a of i.slice(0,-1)){Object.hasOwn(o,a)||(o[a]={});let s=o[a];if(!s||typeof s!="object"||Array.isArray(s))throw new Error("Ambiguous result path");o=s}o[i[i.length-1]]=r}return{...e.attributes,parameters:e.parameters,answers:e.answers,results:t}}function Hi(e,t){return Ue(fc(t),e,t.savedGroups)}function Sr(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.attributeKey=="string"&&t.add(o.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(o)}return n(e),[...t]}import{z as Te}from"zod";var Ir=Te.discriminatedUnion("kind",[Te.object({kind:Te.literal("ledger"),cursor:sr}).strict(),Te.object({kind:Te.literal("billing"),cursor:Te.uuid()}).strict()]),wd=Te.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gt=Te.record(Te.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Te.union([Te.string().max(500),Te.boolean(),Te.array(Te.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),vd=/^(?:api_?key|authorization|password|(?:customer|run|visitor)_?token|access_?token)$/i;function Ji(e){return!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(Ji):Object.entries(e).some(([t,n])=>vd.test(t)||Ji(n)))}var Ad=/gg_(?:sk|ct|fr|fv)_[A-Za-z0-9_-]{20,}/,ht=Te.record(wd,zt).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Ji(e)&&!Ad.test(JSON.stringify(e)),"Credentials cannot be Funnel parameters");function vy(e){let t=Object.create(null);for(let[n,r]of new URL(e).searchParams)Te.string().max(500).parse(r),Object.hasOwn(t,n)||(t[n]=r);return ht.parse(t),t}var wr=W.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Yi=W.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),vr=ht.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Xi=W.record(wr,W.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),kd=W.discriminatedUnion("source",[W.strictObject({source:W.literal("literal"),value:zt}),W.strictObject({source:W.enum(["parameter","answer","attribute","result"]),key:Yi})]),gc=W.strictObject({type:W.literal("external_task"),endpointId:W.uuid(),taskKey:wr,inputs:W.record(wr,kd).refine(e=>Object.keys(e).length<=20),outputs:Xi}),eo=W.strictObject({maxAttempts:W.number().int().min(1).max(5),retryDelaySeconds:W.number().int().min(1).max(30),backoff:W.enum(["fixed","exponential"]),requestTimeoutSeconds:W.number().int().min(1).max(10),timeoutSeconds:W.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),Py={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},zy=W.strictObject({outcome:W.enum(["success","failure"]),data:vr});function _y(e,t){let n=vr.parse(t);if(Object.keys(n).length!==Object.keys(e).length||Object.entries(e).some(([r,i])=>!Object.hasOwn(n,r)||(i==="strings"?!Array.isArray(n[r]):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function Ry(e,t){let n={};for(let[r,i]of Object.entries(e))if(i.source==="literal")n[r]=i.value;else{let o=i.source==="answer"?t.answers:i.source==="parameter"?t.parameters:i.source==="attribute"?t.attributes:t.results??{};if(!Object.hasOwn(o,i.key))throw new Error("Task input is missing");n[r]=o[i.key]}return vr.parse(n)}var Ey=W.discriminatedUnion("operation",[W.strictObject({operation:W.literal("signal"),runId:W.uuid(),nodeId:Yi,eventName:wr,eventId:W.uuid(),data:vr}),W.strictObject({operation:W.literal("read_results"),runId:W.uuid()})]),Ty=W.strictObject({scope:be,runId:W.uuid(),eventId:W.uuid(),accepted:W.boolean()}),to=W.record(Yi,zt),Dy=W.strictObject({scope:be,runId:W.uuid(),results:to});import{z as V}from"zod";var hc=V.strictObject({allocationScopeId:V.uuid(),validitySeconds:V.number().int().min(1).max(2592e3).nullable()}),bc=V.discriminatedUnion("type",[V.strictObject({type:V.literal("literal"),value:Me}),V.strictObject({type:V.literal("feature"),featureKey:V.string().min(1).max(128)})]),jd=V.strictObject({requestId:V.uuid(),decisionId:V.uuid(),customerId:V.uuid(),assignmentId:V.uuid(),evaluationVersionId:V.uuid(),policyVersionId:V.uuid(),value:Me,state:V.enum(["active","expired","inactive"]),validUntil:V.iso.datetime({offset:!0}).nullable()}),qy=V.discriminatedUnion("operation",[V.strictObject({operation:V.literal("decide"),funnelId:V.uuid(),requestId:V.uuid(),customerId:V.uuid(),attributes:Je.refine(e=>!["parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"parameters, answers and results are reserved flow namespaces")}),V.strictObject({operation:V.literal("read_decision"),decisionId:V.uuid()}),V.strictObject({operation:V.literal("feature_config"),funnelId:V.uuid()}),V.strictObject({operation:V.literal("report_used"),decisionId:V.uuid(),eventId:V.uuid(),occurredAt:V.iso.datetime({offset:!0}),reference:V.string().min(1).max(128).optional()})]),Ny=V.strictObject({scope:be,decisionId:V.uuid(),requestId:V.uuid(),status:V.enum(["pending","completed","failed"]),decision:jd.nullable()}).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"),Uy=V.strictObject({scope:be,decisionId:V.uuid(),eventId:V.uuid(),source:V.literal("caller_reported")});var ie=y.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cd=y.object({x:y.number().finite(),y:y.number().finite()}).strict(),ct={id:ie,name:y.string().trim().min(1).max(80),position:Cd.optional()},yc={success:ie,cancel:ie,unavailable:ie,failure:ie},Kt=nn.options[0].shape,Od=nn.options[1].shape,Pd=y.object({type:y.literal("billing_authorization"),kind:y.enum(["auto_topup","postpaid"]),productVersionId:Kt.productVersionId,entitlementVersionId:Kt.entitlementVersionId,currency:Kt.currency,maxAmountMinorPerPeriod:Kt.maxAmountMinorPerPeriod,threshold:Kt.threshold.optional(),maxPurchasesPerDay:Kt.maxPurchasesPerDay.optional(),purchaseLimits:Kt.purchaseLimits,maxOutstandingMinor:Od.maxOutstandingMinor.optional()}).strict().superRefine((e,t)=>{let{type:n,...r}=e,i=nn.safeParse({...r,requestId:"00000000-0000-4000-8000-000000000000"});if(!i.success)for(let o of i.error.issues)t.addIssue({code:"custom",path:o.path,message:o.message})}),Dn=y.discriminatedUnion("type",[y.object({type:y.literal("fixed"),productVersionId:y.uuid()}).strict(),y.object({type:y.literal("picker"),pickerId:ie,allowedProductVersionIds:y.array(y.uuid()).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),_t=y.discriminatedUnion("type",[y.object({type:y.literal("modal"),size:y.enum(["sm","md","lg"])}).strict(),y.object({type:y.literal("sheet"),size:y.enum(["sm","md","lg"])}).strict(),y.object({type:y.literal("fullscreen")}).strict(),y.object({type:y.literal("inline")}).strict()]),no=y.discriminatedUnion("type",[Pd,gc,y.object({type:y.literal("billing_adjustment")}).strict(),y.object({type:y.literal("claim_offer"),couponId:y.uuid()}).strict(),y.object({type:y.literal("event"),event:ie}).strict(),y.object({type:y.literal("open_url"),url:y.url().refine(e=>new URL(e).protocol==="https:")}).strict(),y.object({type:y.literal("billing_portal")}).strict(),y.object({type:y.literal("change_membership"),groupId:y.uuid(),productVersionId:y.uuid(),timing:y.enum(["immediate","renewal"])}).strict(),y.object({type:y.literal("change_seats"),groupId:y.uuid(),licenseKey:ie,quantity:y.number().int().min(0).max(1e4),timing:y.enum(["immediate","renewal"])}).strict(),y.object({type:y.enum(["cancel_membership","resume_membership"]),groupId:y.uuid()}).strict()]),xc=y.string().regex(/^custom:[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ro=y.enum(["payment_verified","action_completed"]),io=y.discriminatedUnion("type",[y.object({...ct,type:y.literal("entry"),next:ie,triggers:y.array(ie).max(20),audienceId:y.uuid().nullable(),startsAt:y.iso.datetime({offset:!0}).nullable(),endsAt:y.iso.datetime({offset:!0}).nullable(),priority:y.number().int().min(0).max(1e5),cooldownSeconds:y.number().int().min(0),maxPerCustomer:y.number().int().positive().nullable()}).strict(),y.object({...ct,type:y.literal("screen"),screenId:ie,presentation:_t,outputs:y.record(ie,ie)}).strict(),y.object({...ct,type:y.literal("condition"),cases:y.array(y.object({condition:ot,target:ie}).strict()).min(1).max(50),default:ie}).strict(),y.strictObject({...ct,type:y.literal("feature"),featureKey:ie,next:ie}),y.strictObject({...ct,type:y.literal("split"),experimentId:y.uuid(),routes:y.record(ie,ie).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ie,goal:y.enum(["completed","authenticated","paid","net_revenue"])}),y.object({...ct,type:y.literal("auth"),success:ie,cancel:ie,failure:ie}).strict(),y.object({...ct,type:y.literal("checkout"),...yc,execution:eo.optional(),product:Dn,couponId:y.uuid().optional(),featureQuantities:y.record(y.uuid(),y.number().int().min(0).max(1e4)).optional(),seatQuantities:y.record(ie,y.number().int().min(0).max(1e4)).optional()}).strict(),y.object({...ct,type:y.literal("action"),...yc,execution:eo.optional(),action:no}).strict(),y.object({...ct,type:y.literal("end"),outcome:y.enum(["completed","closed","ineligible","failed"]),output:bc.optional()}).strict(),y.strictObject({...ct,type:y.literal("wait"),wait:y.discriminatedUnion("type",[y.strictObject({type:y.literal("duration"),delaySeconds:y.number().int().min(1).max(2592e3),elapsed:ie}),y.strictObject({type:y.literal("event"),eventKey:ro,timeoutSeconds:y.number().int().min(1).max(2592e3),received:ie,timeout:ie}),y.strictObject({type:y.literal("custom_event"),eventName:y.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),outputs:Xi,timeoutSeconds:y.number().int().min(1).max(2592e3),received:ie,timeout:ie})])})]),oo=y.object({version:y.literal(2),entry:ie,nodes:y.array(io).min(1).max(we.flowNodes)}).strict(),Sc=oo.superRefine((e,t)=>{zd(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Tn(e){switch(e.type){case"entry":return[e.next];case"screen":return Object.values(e.outputs);case"feature":return[e.next];case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"auth":return[e.success,e.cancel,e.failure];case"checkout":case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"end":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function zd(e,t){let n=[],r=new Map(e.nodes.map(p=>[p.id,p]));function i(p,u,S,Q){n.push(p),t?.({message:p,reason:u,path:S?["nodes",e.nodes.indexOf(S),...Q?[Q]:[]]:[]})}r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(p=>p.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),e.nodes.filter(p=>p.type==="screen").length>we.pages&&i("Screen limit exceeded","budget"),e.nodes.filter(p=>!["screen","entry","end"].includes(p.type)).length>we.logicNodes&&i("Logic node limit exceeded","budget");let o=new Set;for(let p of e.nodes){Tn(p).includes(e.entry)&&i("An entry cannot be a transition target","entryTarget",p);for(let u of Tn(p))r.has(u)||i(`Missing target ${u} from ${p.id}`,"missingTarget",p);p.type==="screen"&&(o.has(p.screenId)&&i(`Screen ${p.screenId} is used by multiple nodes`,"screenOwner",p,"screenId"),o.add(p.screenId)),p.type==="entry"&&p.startsAt&&p.endsAt&&Date.parse(p.startsAt)>=Date.parse(p.endsAt)&&i("Entry schedule ends before it starts","schedule",p,"endsAt"),p.type==="entry"&&new Set(p.triggers).size!==p.triggers.length&&i("Entry triggers must be unique","triggers",p,"triggers")}let a=new Set,s=new Set;function c(p){let u=r.get(p);if(!(!u||["screen","wait","end"].includes(u.type)||s.has(p))){if(a.has(p)){i("Automatic nodes must not form a cycle","cycle",u);return}a.add(p);for(let S of Tn(u))c(S);a.delete(p),s.add(p)}}for(let p of e.nodes)c(p.id);return[...new Set(n)]}function _d(e,t){let n=e.cases.findIndex(r=>Hi(r.condition,t));return{ruleIndex:n<0?null:n,target:n<0?e.default:e.cases[n].target}}function Jy(e,t,n,r){let i=new Map(e.nodes.map(S=>[S.id,S])),o=i.get(t.nodeId),a=[...t.history];if(!o||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let s;switch(n.type){case"wait":if(o.type!=="wait")throw new Error("Not a wait node");if(o.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid wait result");s=o.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid wait result");s=o.wait[n.result]}break;case"start":if(o.type!=="entry")throw new Error("Flow already started");s=o.next;break;case"next":if(o.type!=="screen"||!Object.hasOwn(o.outputs,n.output))throw new Error("Invalid screen output");s=o.outputs[n.output],a.push(o.id);break;case"back":if(o.type!=="screen"||!a.length)throw new Error("No previous screen");if(s=a.pop(),i.get(s)?.type!=="screen")throw new Error("Invalid screen history");break;case"result":if(o.type!=="auth"&&o.type!=="checkout"&&o.type!=="action")throw new Error("Invalid business outcome");if(n.result==="unavailable"){if(o.type==="auth")throw new Error("Invalid business outcome");s=o.unavailable}else s=o[n.result];break;case"feature":if(o.type!=="feature")throw new Error("Not a Feature node");s=o.next;break;case"assignment":if(o.type!=="split")throw new Error("Not a split node");if(n.variantId===null)s=o.notParticipating;else{let S=o.routes[n.variantId];if(!S)throw new Error("Invalid assigned variant");s=S}break}let c=new Set,p=[],u=[];for(;;){if(c.has(s))throw new Error("Automatic cycle");c.add(s);let S=i.get(s);if(!S)throw new Error("Target does not exist");if(p.push(S.id),S.type==="entry"){s=S.next;continue}if(S.type==="condition"){let ne=_d(S,r);u.push({nodeId:S.id,...ne}),s=ne.target;continue}let Q=S.type==="screen"?"running":S.type==="end"?S.outcome:"waiting";return{state:{nodeId:S.id,history:a.slice(-we.pages),status:Q},entered:p,routed:u}}}import{z as w}from"zod";import{z as Rd}from"zod";var Ar=Rd.object({provider:Ya,currency:z}).strict();var so=w.discriminatedUnion("provider",[w.strictObject({provider:w.literal("apple"),orderId:w.uuid(),receiptId:w.uuid(),signedTransaction:w.string().min(1).max(32768)}),w.strictObject({provider:w.literal("google"),orderId:w.uuid(),receiptId:w.uuid(),purchaseToken:w.string().min(1).max(4096)})]),ut=w.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),co=w.discriminatedUnion("type",[w.object({id:ut,type:w.literal("owned"),document:We.refine(e=>e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel screen presents one page and emits outputs; business actions belong to nodes")}).strict(),w.object({id:ut,type:w.literal("paywall"),paywallVersionId:w.uuid()}).strict()]),Ic={kind:w.literal("funnel"),schemaVersion:w.literal(1),name:w.string().trim().min(1).max(80),features:Zn,decisionPolicy:hc.optional(),screens:w.array(co).max(we.pages),inputs:w.array(w.object({key:ut,screenId:ut,componentId:ut,required:w.boolean()}).strict()).max(we.questions)},Ge=w.object({...Ic,graph:oo}).strict(),kr=w.object({...Ic,graph:Sc}).strict().superRefine((e,t)=>{for(let[s,c]of e.graph.nodes.entries())(c.type==="feature"||c.type==="end"&&c.output?.type==="feature")&&!Object.hasOwn(e.features,c.type==="feature"?c.featureKey:c.type==="end"&&c.output?.type==="feature"?c.output.featureKey:"")&&t.addIssue({code:"custom",path:["graph","nodes",s],message:"Unknown Feature key"}),e.decisionPolicy&&(!["entry","condition","split","feature","end"].includes(c.type)||c.type==="end"&&(!c.output||!["completed","ineligible"].includes(c.outcome)))&&t.addIssue({code:"custom",path:["graph","nodes",s],message:"Decision flows contain only entry, condition, split and output ends",params:{reason:"decisionGraph"}}),!e.decisionPolicy&&c.type==="end"&&c.output&&t.addIssue({code:"custom",path:["graph","nodes",s,"output"],message:"Decision outputs require decisionPolicy",params:{reason:"decisionPolicy"}});let n=new Map(e.graph.nodes.flatMap(s=>{let c=s.type==="action"&&s.action.type==="external_task"?s.action.outputs:s.type==="wait"&&s.wait.type==="custom_event"?s.wait.outputs:{};return Object.keys(c).map(p=>[`${s.id}.${p}`,s.id])}));for(let s of e.graph.nodes)s.type==="feature"&&n.set(s.featureKey,s.id);for(let[s,c]of e.graph.nodes.entries()){let p=c.type==="condition"?c.cases.flatMap(u=>[...Sr(u.condition).map(S=>({source:S.startsWith("results.")?"result":"attribute",key:S.startsWith("results.")?S.slice(8):S}))]):c.type==="action"&&c.action.type==="external_task"?Object.values(c.action.inputs):[];for(let u of p)u.source==="result"&&![...n].some(([S,Q])=>Q!==c.id&&(u.key===S||u.key.startsWith(S+".")))&&t.addIssue({code:"custom",message:"Result references require a declared output of another node",path:["graph","nodes",s],params:{reason:"resultReference"}})}let r=new Set(e.screens.map(s=>s.id));r.size!==e.screens.length&&t.addIssue({code:"custom",message:"Screen IDs must be unique",params:{reason:"uniqueScreens"}});let i=e.graph.nodes.filter(s=>s.type==="screen");(i.length!==e.screens.length||i.some(s=>!r.has(s.screenId)))&&t.addIssue({code:"custom",message:"Every screen belongs to exactly one screen node",params:{reason:"screenOwner"}});for(let s of i){let c=e.screens.find(u=>u.id===s.screenId);if(c?.type!=="owned")continue;un(c.document).some(u=>!u.complete)&&t.addIssue({code:"custom",message:`Screen ${s.screenId} needs complete local content`,path:["graph","nodes",e.graph.nodes.indexOf(s)],params:{reason:"translations"}});let p=new Set(c.document.actions.map(u=>u.id));Pt(c.document.pages[0].root,u=>{if(u.type==="customer_data")for(let S of Object.values(u.data.outputs??{}))p.has(S)||t.addIssue({code:"custom",message:`Component ${u.id} needs a declared screen output`,path:["graph","nodes",e.graph.nodes.indexOf(s)],params:{reason:"componentOutput",componentId:u.id}})}),(p.size!==Object.keys(s.outputs).length||Object.keys(s.outputs).some(u=>!p.has(u)))&&t.addIssue({code:"custom",message:`Every button in ${s.screenId} needs one output`,path:["graph","nodes",e.graph.nodes.indexOf(s)],params:{reason:"buttonOutputs"}})}let o=0,a=0;for(let s of e.screens)s.type==="owned"&&(Pt(s.document.pages[0].root,()=>{o++}),a+=s.document.actions.length);(o>we.components||a>we.actions)&&t.addIssue({code:"custom",message:"Funnel exceeds its component or action budget",params:{reason:"budget"}}),new Set(e.inputs.map(s=>s.key)).size!==e.inputs.length&&t.addIssue({code:"custom",message:"Input keys must be unique",params:{reason:"inputKeys"}}),new Set(e.inputs.map(s=>`${s.screenId}:${s.componentId}`)).size!==e.inputs.length&&t.addIssue({code:"custom",message:"A component has one input binding",params:{reason:"inputBinding"}});for(let s of e.inputs){let c=e.screens.find(u=>u.id===s.screenId),p=c?.type==="owned"?br(c.document,s.componentId):null;(p?.type!=="stack"||!p.interaction||!["input","toggle","select","multiselect","tabs"].includes(p.interaction.type))&&t.addIssue({code:"custom",message:`Input ${s.key} requires an interactive component on its owned screen`,path:["inputs",e.inputs.indexOf(s)],params:{reason:"inputBinding"}})}for(let s of e.graph.nodes)if(s.type==="condition")for(let c of s.cases)for(let p of Sr(c.condition))p.startsWith("answers.")&&!e.inputs.some(u=>u.key===p.slice(8))&&t.addIssue({code:"custom",message:`Unknown answer in ${s.id}`,path:["graph","nodes",e.graph.nodes.indexOf(s)],params:{reason:"answer"}});new TextEncoder().encode(JSON.stringify(e)).byteLength>we.documentBytes&&t.addIssue({code:"custom",message:"Funnel document exceeds its byte budget",params:{reason:"budget"}})}),Fn=w.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),Ed=w.discriminatedUnion("type",[w.object({type:w.literal("funnel"),id:w.uuid()}).strict(),w.object({type:w.literal("paywall"),id:w.uuid()}).strict(),w.object({type:w.literal("trigger"),key:ut}).strict()]),Rt={requestId:w.uuid(),nodeId:ut,revision:w.number().int().nonnegative(),customerToken:Fn.optional()},Td=w.object({nodeId:ut,revision:w.number().int().nonnegative(),components:w.record(ut,w.object({resourceKey:w.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:w.number().int().min(1).max(1e5),after:Ir.nullable(),filter:w.enum(["all","purchase","refund","source","usage","debt","settlement"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),m0=w.discriminatedUnion("operation",[w.object({operation:w.literal("start"),source:Ed,requestId:w.uuid(),customerToken:Fn,locale:w.string().max(35).optional(),commerce:Ar.optional(),parameters:ht.optional()}).strict(),w.object({operation:w.literal("get"),data:Td.optional(),customerToken:Fn.optional()}).strict(),w.object({operation:w.literal("resume"),requestId:w.uuid(),customerToken:Fn.optional()}).strict(),w.object({operation:w.literal("advance"),...Rt,output:ut,answers:gt}).strict(),w.object({operation:w.literal("answers"),...Rt,answers:gt}).strict(),w.object({operation:w.literal("back"),...Rt}).strict(),w.object({operation:w.literal("acknowledge"),...Rt,receiptId:w.uuid()}).strict(),w.object({operation:w.literal("execute"),...Rt,intent:w.enum(["begin","confirm","cancel","fail"]),accepted:w.literal(!0).optional(),productVersionId:w.uuid().optional(),nativeEvidence:so.optional(),nativeEvidenceDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),w.object({operation:w.literal("link"),...Rt,customerToken:Fn}).strict(),w.object({operation:w.literal("shown"),...Rt}).strict(),w.object({operation:w.literal("close"),...Rt}).strict()]);function ao(e,t){if(e.hidden)return null;if(e.id===t)return e;if(e.type!=="stack")return null;for(let n of e.children){let r=ao(n,t);if(r)return r}return null}function Dd(e,t,n,r,i){let o=e.graph.nodes.find(p=>p.id===t);if(o?.type!=="screen")throw new Error("Input is only accepted on a screen");let a=e.screens.find(p=>p.id===o.screenId),s=e.inputs.filter(p=>p.screenId===o.screenId),c={...r};for(let[p,u]of Object.entries(n)){let S=s.find(ke=>ke.key===p);if(!S||a?.type!=="owned")throw new Error("Unknown screen input");let Q=ao(a.document.pages[0].root,S.componentId);if(Q?.type!=="stack"||!Q.interaction)throw new Error("Input is unavailable");let ne=Q.interaction;switch(ne.type){case"input":if(typeof u!="string"||u.length>ne.maxLength)throw new Error("Invalid input text");if(u&&ne.keyboard==="email"&&!w.email().safeParse(u).success)throw new Error("Invalid email");if(u&&ne.keyboard==="url"&&!w.url().safeParse(u).success)throw new Error("Invalid URL");break;case"toggle":if(typeof u!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof u!="string"||!Q.children.some(ke=>ke.id===u&&!ke.hidden))throw new Error("Invalid selected option");break;case"multiselect":if(!Array.isArray(u)||new Set(u).size!==u.length||u.length>ne.max||i&&u.length<ne.min||u.some(ke=>!Q.children.some(he=>he.id===ke&&!he.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}c[p]=u}if(i)for(let p of s){let u=c[p.key];if(p.required&&(u===void 0||u===""||Array.isArray(u)&&u.length===0))throw new Error(`Required input: ${p.key}`);u!==void 0&&!Object.hasOwn(n,p.key)&&Dd(e,t,{[p.key]:u},{},!1);let S=a?.type==="owned"?ao(a.document.pages[0].root,p.componentId):null;if(S?.type==="stack"&&S.interaction?.type==="multiselect"&&Array.isArray(u)&&u.length<S.interaction.min)throw new Error("Not enough selected options")}return c}import{z as ue}from"zod";var Fd=ue.object({id:ue.uuid(),projectId:ue.uuid(),environmentId:ue.uuid(),revision:ue.number().int().nonnegative(),status:ue.enum(["draft","published","archived"]),publishedVersionId:ue.uuid().nullable(),systemManaged:ue.boolean(),updatedAt:ue.iso.datetime({offset:!0}),draft:Ge}).strict(),b0=ue.object({rows:ue.array(Fd).max(200),nextCursor:ue.uuid().nullable()}).strict(),y0=ue.discriminatedUnion("action",[ue.strictObject({action:ue.literal("create"),requestId:ue.uuid(),document:Ge}),ue.object({action:ue.literal("save"),id:ue.uuid(),revision:ue.number().int().nonnegative(),document:Ge}).strict(),ue.object({action:ue.enum(["publish","archive"]),id:ue.uuid(),revision:ue.number().int().nonnegative()}).strict()]);function x0(e){let t=e==="en",n=mc("popup",e);return n.name=t?"Welcome":"\u6B22\u8FCE",n.pages[0].root.children=[{id:"heading",type:"text",text:"heading",variant:"title"},{id:"continue_button",type:"button",label:"continue",variant:"primary",action:"continue"}],n.actions=[{id:"continue",type:"event",event:"continue",properties:{},close:!1}],n.strings.locales[e]={heading:t?"Welcome":"\u6B22\u8FCE",continue:t?"Continue":"\u7EE7\u7EED"},kr.parse({features:{},schemaVersion:1,kind:"funnel",name:t?"Untitled funnel":"\u672A\u547D\u540D\u6D41\u7A0B",inputs:[],screens:[{id:"welcome",type:"owned",document:n}],graph:{version:2,entry:"entry",nodes:[{id:"entry",name:t?"Entry":"\u5165\u53E3",type:"entry",next:"welcome",triggers:[],audienceId:null,startsAt:null,endsAt:null,priority:0,cooldownSeconds:0,maxPerCustomer:null},{id:"welcome",name:t?"Welcome":"\u6B22\u8FCE",type:"screen",screenId:"welcome",presentation:{type:"modal",size:"md"},outputs:{continue:"done"}},{id:"done",name:t?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed"}]}})}import{z as I}from"zod";var bt=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wc=I.array(I.object({key:bt,componentId:bt,required:I.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.key)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),R0=I.object({bindings:wc,answers:gt}).strict(),Bd=I.enum(["running","waiting","completed","closed","ineligible","failed"]),$d=I.discriminatedUnion("type",[I.strictObject({type:I.literal("wait"),nodeId:bt,visit:I.number().int().nonnegative(),deadlineAt:I.iso.datetime({offset:!0}),eventKey:I.union([ro,xc]).nullable()}),I.object({type:I.literal("confirm_billing_adjustment"),receiptId:I.uuid(),invoiceId:I.uuid(),originalInvoiceId:I.uuid(),currency:z,amountMinor:I.string().regex(/^[1-9]\d{0,8}$/).refine(e=>BigInt(e)<=200000000n),startsAt:I.iso.datetime({offset:!0}),endsAt:I.iso.datetime({offset:!0})}).strict(),I.object({type:I.literal("confirm_billing_authorization"),receiptId:I.uuid(),authorizationId:I.uuid(),terms:Yn,setupUrl:I.url().nullable()}).strict(),I.object({type:I.literal("authenticate")}).strict(),I.object({type:I.literal("confirm_membership_change"),changeKind:I.enum(["plan","seats"]),seat:I.object({key:bt,fromQuantity:I.number().int().min(0).max(1e4),toQuantity:I.number().int().min(0).max(1e4)}).strict().nullable(),seats:I.array(I.strictObject({key:bt,fromQuantity:I.number().int().min(0).max(1e4),toQuantity:I.number().int().min(0).max(1e4)})).max(20).refine(e=>new Set(e.map(t=>t.key)).size===e.length,"Seat keys must be unique"),receiptId:I.uuid(),productVersionId:I.uuid(),currency:I.string().regex(/^[A-Z]{3}$/),creditMinor:I.string().regex(/^(0|[1-9][0-9]{0,8})$/),debitMinor:I.string().regex(/^(0|[1-9][0-9]{0,8})$/),discountMinor:I.string().regex(/^(0|[1-9][0-9]{0,8})$/),taxMinor:I.string().regex(/^(0|[1-9][0-9]{0,8})$/),totalMinor:I.string().regex(/^(0|[1-9][0-9]{0,8})$/),effectiveAt:I.iso.datetime({offset:!0}),timing:I.enum(["immediate","renewal"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&(e.seat===null||e.seats.length===1&&e.seats[0]?.key===e.seat.key&&e.seats[0]?.fromQuantity===e.seat.fromQuantity&&e.seats[0]?.toQuantity===e.seat.toQuantity),"A seat change requires its fixed quantities"),On,I.object({type:I.literal("checkout"),receiptId:I.uuid(),productVersionId:I.uuid(),url:I.url().refine(e=>new URL(e).protocol==="https:")}).strict(),I.object({type:I.literal("open_url"),receiptId:I.uuid(),url:I.url().refine(e=>new URL(e).protocol==="https:")}).strict()]),uo=I.object({id:I.uuid(),funnelId:I.uuid(),versionId:I.uuid(),revision:I.number().int().nonnegative(),visit:I.number().int().nonnegative(),nodeId:bt,nodeType:I.enum(["entry","screen","condition","split","feature","auth","checkout","action","wait","end"]),status:Bd,canBack:I.boolean(),authenticated:I.boolean(),locale:I.string().min(1).max(35),commerce:Ar.nullable(),checkout:I.object({product:Dn,selectedProductVersionId:I.uuid().nullable()}).strict().nullable(),answers:gt,parameters:ht,screen:I.object({id:bt,document:We,presentation:_t,outputs:I.array(bt).max(250),inputs:wc,capabilities:Hs,customerData:ec,dataCursors:I.record(bt,Ir.nullable())}).strict().nullable(),instruction:$d.nullable(),pendingRequest:I.object({requestId:I.uuid(),authenticationRequired:I.boolean()}).strict().nullable(),runExpiresAt:I.iso.datetime({offset:!0}),credentialExpiresAt:I.iso.datetime({offset:!0}).nullable()}).strict(),jr=I.object({scope:be,run:uo,nativeCompletion:I.strictObject({orderId:I.uuid(),receiptId:I.uuid(),transactionIds:I.array(I.string().min(1).max(255)).min(1).max(50),membership:I.boolean()}).optional(),runToken:I.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional()}).strict();import{z as Cr}from"zod";var F0=Cr.strictObject({operation:Cr.literal("renew_run"),runId:Cr.uuid(),customerId:Cr.uuid()}),B0=jr.refine(e=>!!e.runToken,"Renewal returns a credential");import{z as v}from"zod";var vc={commands:we.flowNodes*4,receipts:we.flowNodes*2,requestBytes:we.documentBytes+1e6},Et=v.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yt={requestId:v.uuid(),nodeId:Et,revision:v.number().int().nonnegative()},Vd=v.discriminatedUnion("operation",[v.strictObject({operation:v.literal("wait"),...yt,result:v.enum(["elapsed","received","timeout"])}),v.strictObject({operation:v.literal("advance"),...yt,output:Et,answers:gt}),v.strictObject({operation:v.literal("answers"),...yt,answers:gt}),v.strictObject({operation:v.literal("back"),...yt}),v.strictObject({operation:v.literal("link"),...yt}),v.strictObject({operation:v.literal("shown"),...yt}),v.strictObject({operation:v.literal("close"),...yt}),v.strictObject({operation:v.literal("acknowledge"),...yt,receiptId:v.uuid()}),v.strictObject({operation:v.literal("execute"),...yt,intent:v.enum(["begin","confirm","cancel","fail"]),productVersionId:v.uuid().optional()})]),lo=v.enum(["success","cancel","failure","unavailable","pending"]),mo=v.strictObject({seed:v.uuid(),now:v.iso.datetime({offset:!0}),locale:v.string().min(2).max(35),currency:z,parameters:ht,attributes:v.record(Et,zt).refine(e=>Object.keys(e).length<=100),authenticated:v.boolean(),holdings:v.enum(["sample","empty"]),results:to.optional(),outcomes:v.record(Et,lo).refine(e=>Object.keys(e).length<=100),variants:v.record(Et,Et.nullable()).refine(e=>Object.keys(e).length<=100)}),qd=v.array(v.strictObject({command:Vd,authenticated:v.boolean(),outcome:lo})).max(vc.commands),Nd=v.discriminatedUnion("type",[v.strictObject({type:v.literal("draft"),document:Ge}),v.strictObject({type:v.literal("snapshot"),id:v.uuid()})]),W0=v.strictObject({previewId:v.uuid(),source:Nd,scenario:mo,journal:qd}),Z0=v.strictObject({mode:v.literal("simulation"),run:uo,traceTruncated:v.boolean(),trace:v.array(v.strictObject({nodeId:Et,visit:v.number().int().nonnegative(),type:v.enum(["entered","shown","assigned","feature_evaluated","authenticated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:v.record(v.string(),v.union([v.string(),v.number(),v.boolean(),v.null()]))})).max(2e3),receipts:v.array(v.strictObject({id:v.uuid(),nodeId:Et,visit:v.number().int().nonnegative(),outcome:lo})).max(vc.receipts)}),H0=v.strictObject({id:v.uuid(),projectId:v.uuid(),environmentId:v.uuid(),document:Ge,scenario:mo,ruleSnapshot:ui,expiresAt:v.iso.datetime({offset:!0})}),J0=v.discriminatedUnion("action",[v.strictObject({action:v.literal("create"),requestId:v.uuid(),document:Ge,scenario:mo}),v.strictObject({action:v.literal("revoke"),id:v.uuid()})]);import{z as N}from"zod";var Ud=co.options[0].shape.document,Md=N.discriminatedUnion("type",[N.object({type:N.literal("checkout"),product:Dn}).strict(),N.object({type:N.literal("close")}).strict(),N.object({type:N.literal("action"),action:no}).strict()]),Or=N.object({schemaVersion:N.literal(1),kind:N.literal("paywall"),name:N.string().trim().min(1).max(80),presentation:_t,screen:Ud,buttons:N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Md)}).strict(),rx=Or.superRefine((e,t)=>{un(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.length||e.screen.actions.some(r=>!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 checkout button"})}),Ld=N.object({id:N.uuid(),projectId:N.uuid(),environmentId:N.uuid(),funnelId:N.uuid(),revision:N.number().int().nonnegative(),status:N.enum(["draft","published","archived"]),publishedVersionId:N.uuid().nullable(),updatedAt:N.iso.datetime({offset:!0}),draft:Or}).strict(),ix=N.object({rows:N.array(Ld).max(200),nextCursor:N.uuid().nullable()}).strict(),ox=N.discriminatedUnion("action",[N.object({action:N.literal("save"),id:N.uuid().nullable(),revision:N.number().int().nonnegative(),document:Or}).strict(),N.object({action:N.enum(["publish","archive"]),id:N.uuid(),revision:N.number().int().nonnegative()}).strict()]),ax=N.object({paywalls:N.array(N.object({id:N.uuid(),paywallId:N.uuid(),version:N.number().int().positive(),name:N.string().min(1).max(80),presentation:_t,buttons:Or.shape.buttons}).strict()).max(500),limited:N.boolean()}).strict();function sx(e,t){let n=Object.entries(e.buttons);return kr.parse({features:{},schemaVersion:1,kind:"funnel",name:e.name,inputs:[],screens:[{id:"paywall",type:"paywall",paywallVersionId:t}],graph:{version:2,entry:"entry",nodes:[{type:"entry",id:"entry",name:"Entry",next:"paywall",triggers:[],audienceId:null,startsAt:null,endsAt:null,priority:0,cooldownSeconds:0,maxPerCustomer:null},{type:"screen",id:"paywall",name:e.name,screenId:"paywall",presentation:e.presentation,outputs:Object.fromEntries(n.map(([r,i],o)=>[r,i.type==="close"?"closed":`operation_${o}`]))},...n.flatMap(([,r],i)=>r.type==="close"?[]:[{id:`operation_${i}`,name:r.type==="checkout"?"Checkout":r.action.type,success:r.type==="checkout"?"completed":"paywall",cancel:"paywall",failure:"paywall",unavailable:"paywall",...r}]),{type:"end",id:"completed",name:"Completed",outcome:"completed"},{type:"end",id:"closed",name:"Closed",outcome:"closed"}]}})}import{z as Z}from"zod";var lx=Z.object({overall:Z.object({entered:Z.number(),running:Z.number(),closed:Z.number(),completed:Z.number(),authenticated:Z.number(),authReached:Z.number(),paid:Z.number(),free:Z.number()}),steps:Z.array(Z.object({node_id:Z.string(),visitors:Z.number()})),edges:Z.array(Z.object({node_id:Z.string(),target:Z.string(),visitors:Z.number()})),currencies:Z.array(Z.object({currency:Z.string(),grossCents:Z.number(),refundCents:Z.number()})),variants:Z.array(Z.object({experimentId:Z.uuid(),revision:Z.number(),variantId:Z.string(),exposed:Z.number(),completed:Z.number(),paid:Z.number(),exposedRuns:Z.number().optional(),completedRuns:Z.number().optional(),paidRuns:Z.number().optional()}))});var po={zh:["\u5168\u90E8\u4ED8\u8D39\u5957\u9910","\u6307\u5B9A\u5957\u9910","\u6240\u6709\u5BA2\u6237","\u4EC5\u9996\u8D2D","\u9700\u8981\u6807\u7B7E","\u5F00\u59CB","\u622A\u6B62","\u65E0\u622A\u6B62\u65E5\u671F","\u9886\u53D6\u540E\u6709\u6548","\u5C0F\u65F6","\u6BCF\u4EBA\u6B21\u6570","\u603B\u540D\u989D"],"zh-Hant":["\u5168\u90E8\u4ED8\u8CBB\u65B9\u6848","\u6307\u5B9A\u65B9\u6848","\u6240\u6709\u5BA2\u6236","\u50C5\u9996\u8CFC","\u9700\u8981\u6A19\u7C64","\u958B\u59CB","\u622A\u6B62","\u7121\u622A\u6B62\u65E5\u671F","\u9818\u53D6\u5F8C\u6709\u6548","\u5C0F\u6642","\u6BCF\u4EBA\u6B21\u6578","\u7E3D\u540D\u984D"],en:["All paid plans","Selected plans","All customers","First purchase only","Required tags","Starts","Ends","No end date","Valid after claim","hours","Uses per customer","Total limit"],ja:["\u5168\u6709\u6599\u30D7\u30E9\u30F3","\u5BFE\u8C61\u30D7\u30E9\u30F3","\u3059\u3079\u3066\u306E\u304A\u5BA2\u69D8","\u521D\u56DE\u8CFC\u5165\u9650\u5B9A","\u5FC5\u8981\u306A\u30BF\u30B0","\u958B\u59CB","\u7D42\u4E86","\u7D42\u4E86\u65E5\u306A\u3057","\u53D7\u53D6\u5F8C\u306E\u6709\u52B9\u671F\u9593","\u6642\u9593","\u9867\u5BA2\u3054\u3068\u306E\u5229\u7528\u56DE\u6570","\u5229\u7528\u4E0A\u9650"],ko:["\uBAA8\uB4E0 \uC720\uB8CC \uC694\uAE08\uC81C","\uC9C0\uC815 \uC694\uAE08\uC81C","\uBAA8\uB4E0 \uACE0\uAC1D","\uCCAB \uAD6C\uB9E4\uB9CC","\uD544\uC218 \uD0DC\uADF8","\uC2DC\uC791","\uC885\uB8CC","\uC885\uB8CC\uC77C \uC5C6\uC74C","\uC218\uB839 \uD6C4 \uC720\uD6A8 \uAE30\uAC04","\uC2DC\uAC04","\uACE0\uAC1D\uBCC4 \uC0AC\uC6A9 \uD69F\uC218","\uCD1D \uD55C\uB3C4"],es:["Todos los planes de pago","Planes seleccionados","Todos los clientes","Solo primera compra","Etiquetas requeridas","Inicio","Fin","Sin fecha de fin","Validez tras reclamar","horas","Usos por cliente","L\xEDmite total"],fr:["Tous les forfaits payants","Forfaits s\xE9lectionn\xE9s","Tous les clients","Premier achat uniquement","\xC9tiquettes requises","D\xE9but","Fin","Sans date de fin","Validit\xE9 apr\xE8s obtention","heures","Utilisations par client","Limite totale"],de:["Alle kostenpflichtigen Tarife","Ausgew\xE4hlte Tarife","Alle Kunden","Nur erster Kauf","Erforderliche Tags","Beginn","Ende","Kein Enddatum","G\xFCltigkeit nach Erhalt","Stunden","Nutzungen pro Kunde","Gesamtlimit"],pt:["Todos os planos pagos","Planos selecionados","Todos os clientes","Apenas primeira compra","Etiquetas necess\xE1rias","In\xEDcio","Fim","Sem data final","Validade ap\xF3s resgate","horas","Usos por cliente","Limite total"],it:["Tutti i piani a pagamento","Piani selezionati","Tutti i clienti","Solo primo acquisto","Tag richiesti","Inizio","Fine","Senza data finale","Validit\xE0 dopo il ritiro","ore","Utilizzi per cliente","Limite totale"],ru:["\u0412\u0441\u0435 \u043F\u043B\u0430\u0442\u043D\u044B\u0435 \u043F\u043B\u0430\u043D\u044B","\u0412\u044B\u0431\u0440\u0430\u043D\u043D\u044B\u0435 \u043F\u043B\u0430\u043D\u044B","\u0412\u0441\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u044B","\u0422\u043E\u043B\u044C\u043A\u043E \u043F\u0435\u0440\u0432\u0430\u044F \u043F\u043E\u043A\u0443\u043F\u043A\u0430","\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u044B\u0435 \u0442\u0435\u0433\u0438","\u041D\u0430\u0447\u0430\u043B\u043E","\u041E\u043A\u043E\u043D\u0447\u0430\u043D\u0438\u0435","\u0411\u0435\u0437 \u0434\u0430\u0442\u044B \u043E\u043A\u043E\u043D\u0447\u0430\u043D\u0438\u044F","\u0421\u0440\u043E\u043A \u043F\u043E\u0441\u043B\u0435 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F","\u0447\u0430\u0441\u043E\u0432","\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0439 \u043D\u0430 \u043A\u043B\u0438\u0435\u043D\u0442\u0430","\u041E\u0431\u0449\u0438\u0439 \u043B\u0438\u043C\u0438\u0442"],vi:["M\u1ECDi g\xF3i tr\u1EA3 ph\xED","G\xF3i \u0111\u01B0\u1EE3c ch\u1ECDn","M\u1ECDi kh\xE1ch h\xE0ng","Ch\u1EC9 l\u1EA7n mua \u0111\u1EA7u","Th\u1EBB b\u1EAFt bu\u1ED9c","B\u1EAFt \u0111\u1EA7u","K\u1EBFt th\xFAc","Kh\xF4ng c\xF3 ng\xE0y k\u1EBFt th\xFAc","Hi\u1EC7u l\u1EF1c sau khi nh\u1EADn","gi\u1EDD","L\u01B0\u1EE3t m\u1ED7i kh\xE1ch","T\u1ED5ng gi\u1EDBi h\u1EA1n"],th:["\u0E17\u0E38\u0E01\u0E41\u0E1E\u0E47\u0E01\u0E40\u0E01\u0E08\u0E41\u0E1A\u0E1A\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19","\u0E41\u0E1E\u0E47\u0E01\u0E40\u0E01\u0E08\u0E17\u0E35\u0E48\u0E40\u0E25\u0E37\u0E2D\u0E01","\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E17\u0E38\u0E01\u0E04\u0E19","\u0E40\u0E09\u0E1E\u0E32\u0E30\u0E01\u0E32\u0E23\u0E0B\u0E37\u0E49\u0E2D\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01","\u0E41\u0E17\u0E47\u0E01\u0E17\u0E35\u0E48\u0E08\u0E33\u0E40\u0E1B\u0E47\u0E19","\u0E40\u0E23\u0E34\u0E48\u0E21","\u0E2A\u0E34\u0E49\u0E19\u0E2A\u0E38\u0E14","\u0E44\u0E21\u0E48\u0E21\u0E35\u0E27\u0E31\u0E19\u0E2A\u0E34\u0E49\u0E19\u0E2A\u0E38\u0E14","\u0E2D\u0E32\u0E22\u0E38\u0E2B\u0E25\u0E31\u0E07\u0E23\u0E31\u0E1A\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C","\u0E0A\u0E31\u0E48\u0E27\u0E42\u0E21\u0E07","\u0E04\u0E23\u0E31\u0E49\u0E07\u0E15\u0E48\u0E2D\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32","\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E31\u0E49\u0E07\u0E2B\u0E21\u0E14"],id:["Semua paket berbayar","Paket terpilih","Semua pelanggan","Hanya pembelian pertama","Tag wajib","Mulai","Berakhir","Tanpa tanggal akhir","Masa berlaku setelah klaim","jam","Penggunaan per pelanggan","Batas total"],ar:["\u062C\u0645\u064A\u0639 \u0627\u0644\u062E\u0637\u0637 \u0627\u0644\u0645\u062F\u0641\u0648\u0639\u0629","\u0627\u0644\u062E\u0637\u0637 \u0627\u0644\u0645\u062D\u062F\u062F\u0629","\u062C\u0645\u064A\u0639 \u0627\u0644\u0639\u0645\u0644\u0627\u0621","\u0627\u0644\u0634\u0631\u0627\u0621 \u0627\u0644\u0623\u0648\u0644 \u0641\u0642\u0637","\u0627\u0644\u0648\u0633\u0648\u0645 \u0627\u0644\u0645\u0637\u0644\u0648\u0628\u0629","\u062A\u0628\u062F\u0623","\u062A\u0646\u062A\u0647\u064A","\u0628\u0644\u0627 \u062A\u0627\u0631\u064A\u062E \u0627\u0646\u062A\u0647\u0627\u0621","\u0627\u0644\u0635\u0644\u0627\u062D\u064A\u0629 \u0628\u0639\u062F \u0627\u0644\u0645\u0637\u0627\u0644\u0628\u0629","\u0633\u0627\u0639\u0627\u062A","\u0627\u0644\u0627\u0633\u062A\u062E\u062F\u0627\u0645\u0627\u062A \u0644\u0643\u0644 \u0639\u0645\u064A\u0644","\u0627\u0644\u062D\u062F \u0627\u0644\u0625\u062C\u0645\u0627\u0644\u064A"]};function px(e,t,n=[]){let r=$t(t)??"en",i=r.split("-")[0],o=i==="zh"&&/(?:Hant|TW|HK|MO)/.test(r)?"zh-Hant":i,a=po[o]??po.en,s=po[o]?r:"en",c=ne=>new Intl.NumberFormat(s).format(ne),p=ne=>new Intl.DateTimeFormat(s,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(ne))+" UTC",u=[e.appliesTo.type==="all"?a[0]:`${a[1]}${n.length?`: ${n.slice(0,3).join(", ")+(n.length>3?` (+${c(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?a[3]:a[2],Object.keys(e.eligibility.condition).length?`${a[4]}${Ac(e.eligibility.condition)?`: ${Ac(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),S=[e.startsAt?`${a[5]}: ${p(e.startsAt)}`:null,e.endsAt?`${a[6]}: ${p(e.endsAt)}`:a[7]].filter(Boolean).join(" \xB7 "),Q=[u,S,`${a[8]}: ${c(e.grantWindowHours)} ${a[9]}`,`${a[10]}: ${c(e.perCustomerLimit)}`,e.totalLimit===null?null:`${a[11]}: ${c(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:u,validity:S,terms:Q}}function Ac(e){let t=e.tags;if(!t||typeof t!="object"||Array.isArray(t))return"";let n=t.$all??t.$in;return Array.isArray(n)&&n.every(r=>typeof r=="string")?n.join(", "):""}var fo={"popup-coupon-welcome-ticket":{discount:"20%",zh:"\u9996\u671F\u8BA2\u9605\u4F18\u60E0",en:"Off your first subscription payment"},"popup-coupon-return-ticket":{discount:"$5",zh:"\u56DE\u6765\u7EE7\u7EED\u4F60\u7684\u8BA1\u5212",en:"Pick up where you left off"},"popup-coupon-launch-poster":{discount:"30%",zh:"\u65B0\u7248\u672C\u4E0A\u7EBF\u4F18\u60E0",en:"A special offer for our new release"},"popup-coupon-friday-poster":{discount:"40%",zh:"\u6D3B\u52A8\u671F\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for the campaign"},"popup-coupon-studio-split":{discount:"25%",zh:"\u4E3A\u521B\u4F5C\u8005\u51C6\u5907\u7684\u8BA2\u9605\u793C\u9047",en:"A subscription offer for creators"},"popup-coupon-team-split":{discount:"$10",zh:"\u56E2\u961F\u65B9\u6848\u9996\u671F\u51CF\u514D",en:"Off the first payment on a team plan"},"popup-coupon-member-letter":{discount:"20%",zh:"\u4E00\u4EFD\u4E13\u5C5E\u7684\u4F1A\u5458\u793C\u9047",en:"A membership offer just for you"},"popup-coupon-founder-letter":{discount:"30%",zh:"\u7ED9\u65E9\u671F\u652F\u6301\u8005\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for early supporters"},"popup-coupon-gift-box":{discount:"$5",zh:"\u4F60\u7684\u4E0B\u4E00\u6B21\u8BA2\u9605\u4F18\u60E0",en:"An offer for your next subscription"},"popup-coupon-birthday-box":{discount:"25%",zh:"\u751F\u65E5\u4E3B\u9898\u4F1A\u5458\u4F18\u60E0",en:"A birthday-themed membership offer"},"popup-coupon-first-receipt":{discount:"20%",zh:"\u9996\u671F\u4ED8\u6B3E\u6298\u6263",en:"A discount on the first payment"},"popup-coupon-loyalty-receipt":{discount:"$8",zh:"\u8001\u5BA2\u6237\u8BA2\u9605\u793C\u9047",en:"A subscription offer for returning customers"},"popup-coupon-upgrade-sheet":{discount:"20%",zh:"\u4E86\u89E3\u8BA2\u9605\u4F18\u60E0",en:"Explore a subscription offer"},"popup-coupon-return-sheet":{discount:"$5",zh:"\u56DE\u5F52\u8BA2\u9605\u4F18\u60E0",en:"A returning subscriber offer"},"popup-coupon-minimal-number":{discount:"20%",zh:"\u9996\u671F\u8BA2\u9605\u51CF\u514D",en:"Off the first subscription payment"},"popup-coupon-bold-number":{discount:"50%",zh:"\u6D3B\u52A8\u8BA2\u9605\u6298\u6263",en:"A campaign subscription discount"},"popup-coupon-studio-editorial":{discount:"25%",zh:"\u4E13\u4E1A\u8BA2\u9605\u65B9\u6848\u4F18\u60E0",en:"An offer on a professional subscription"},"popup-coupon-autumn-editorial":{discount:"30%",zh:"\u79CB\u5B63\u8BA2\u9605\u6D3B\u52A8",en:"An autumn subscription campaign"},"popup-coupon-vip-pass":{discount:"20%",zh:"\u4F1A\u5458\u8BA2\u9605\u793C\u9047",en:"A membership subscription offer"},"popup-coupon-beta-pass":{discount:"35%",zh:"\u65E9\u671F\u4F53\u9A8C\u8005\u4F18\u60E0",en:"An offer for early adopters"},"popup-coupon-welcome-stamp":{discount:"20%",zh:"\u9996\u6B21\u8BA2\u9605\u793C\u9047",en:"A first subscription offer"},"popup-coupon-milestone-stamp":{discount:"$5",zh:"\u7EE7\u7EED\u524D\u884C\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for your next step"},"popup-coupon-quiet-frame":{discount:"15%",zh:"\u4E13\u6CE8\u5DE5\u4F5C\u6D41\u8BA2\u9605\u4F18\u60E0",en:"An offer for a focused workflow"},"popup-coupon-premium-frame":{discount:"25%",zh:"\u7CBE\u9009\u4F1A\u5458\u65B9\u6848\u793C\u9047",en:"An offer on selected membership plans"},"popup-coupon-starter-steps":{discount:"20%",zh:"\u4E86\u89E3\u4F18\u60E0\uFF0C\u9886\u53D6\u540E\u9009\u5957\u9910",en:"Explore the offer, then choose your plan"},"popup-coupon-comeback-steps":{discount:"$5",zh:"\u4E3A\u56DE\u5F52\u51C6\u5907\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for your return"},"popup-coupon-spring-banner":{discount:"20%",zh:"\u6625\u5B63\u8BA2\u9605\u793C\u9047",en:"A spring subscription offer"},"popup-coupon-year-banner":{discount:"30%",zh:"\u65B0\u5E74\u4F1A\u5458\u8BA2\u9605\u4F18\u60E0",en:"A new-year membership offer"},"popup-coupon-mono-card":{discount:"20%",zh:"\u4E13\u4E1A\u5DE5\u5177\u8BA2\u9605\u4F18\u60E0",en:"An offer on professional tools"},"popup-coupon-night-card":{discount:"$5",zh:"\u521B\u4F5C\u5DE5\u5177\u8BA2\u9605\u4F18\u60E0",en:"An offer on creative tools"},"popup-coupon-spotlight-panel":{discount:"30%",zh:"\u4E13\u4E1A\u7248\u8BA2\u9605\u6D3B\u52A8",en:"A professional subscription campaign"},"popup-coupon-summer-panel":{discount:"25%",zh:"\u590F\u5B63\u8BA2\u9605\u4F18\u60E0",en:"A summer subscription offer"}};function kc(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function bx(e,t){let n=kc(e);if(!n||!Object.hasOwn(fo,n))return e;let r=i=>{let o={...i.root.bind,coupon:t};return i.root.bind?.coupon!==t&&delete o.promotionCode,{bind:o}};return{...e,pages:e.pages.map(i=>({...i,root:{...i.root,...r(i)}})),actions:e.actions.map(i=>i.properties.templateKey===n&&i.type!=="close"?{id:i.id,type:"claim_offer",couponId:t,event:"offer.claimed",properties:i.properties,close:i.close}:i)}}function yx(e){let t=kc(e),n=t?fo[t]:void 0;return!n||e.actions.some(r=>r.type==="claim_offer")?e:{...e,strings:{...e.strings,locales:Object.fromEntries(Object.entries(e.strings.locales).map(([r,i])=>[r,Object.fromEntries(Object.entries(i).map(([o,a])=>[o,a.replaceAll("{{offer.discount}}",n.discount).replaceAll("{{offer.headline}}",r.startsWith("zh")?n.zh:n.en).replaceAll("{{offer.terms}}",r.startsWith("zh")?"\u6F14\u793A\u91D1\u989D \xB7 \u7ED1\u5B9A\u4F18\u60E0\u5238\u540E\u81EA\u52A8\u663E\u793A\u771F\u5B9E\u6761\u6B3E":"Demo amount \xB7 Bind a coupon to show actual terms")]))]))}}}function wx(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),o=(s,c)=>i?s:c,a=(s,c,p,u,S=[])=>({id:s,label:c,value:p,status:u,detail:S,facts:[]});return nt(e,s=>{if(s.type!=="customer_data")return;let c={...tc(s.data.source),status:"ready",stale:!1,preview:!0};if(s.data.source==="credit_balance"){let p=s.data.resourceKey??n[0]?.key??"credits";c.resources=[{key:p,name:n.find(u=>u.key===p)?.label??o("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:o("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[a("sample-monthly",o("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",o("\u53EF\u7528","Available")),a("sample-pack",o("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",o("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[a("sample-usage-1",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67083\u65E5 09:42","Oct 3, 09:42")]),a("sample-usage-2",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u9884\u6263","Reserved"),[o("10\u67083\u65E5 09:30","Oct 3, 09:30")]),a("sample-usage-3",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u9000\u56DE","Refund"),[o("10\u67082\u65E5 16:10","Oct 2, 16:10")]),a("sample-usage-4",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 15:24","Oct 2, 15:24")]),a("sample-usage-5",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((p,u)=>{p.facts=[{label:o("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:["12","180","12","180","24"][u]}]})):s.data.source==="membership"?c.rows=[a("sample-plan",o("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",o("\u6709\u6548","Active"),[o("\u5F53\u524D\u5468\u671F\u7ED3\u675F \xB7 2026\u5E7411\u67081\u65E5","Current period ends \xB7 November 1, 2026")])]:s.data.source==="customer_plans"?c.rows=[a("sample-free",o("\u57FA\u7840\u7248","Starter"),o("\u514D\u8D39","Free"),o("\u53EF\u9009\u62E9","Available")),a("sample-pro",o("\u4E13\u4E1A\u7248","Pro"),o("$29 / \u6708","$29 / month"),o("\u5F53\u524D\u5957\u9910","Current plan")),a("sample-team",o("\u56E2\u961F\u7248","Team"),o("$79 / \u6708","$79 / month"),o("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[a("sample-control",o("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",o("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[o("\u4EC5\u5C55\u793A\u793A\u4F8B\uFF0C\u9884\u89C8\u4E0D\u4F1A\u542F\u7528\u81EA\u52A8\u5145\u503C\u6216\u540E\u4ED8\u8D39\u3002","Preview does not authorize auto top-ups or postpaid billing.")])]:s.data.source==="billing"?c.rows=[{...a("sample-invoice","GROW-2026-001","$29.00",o("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:o("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[a("sample-pack-small",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[o("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),a("sample-pack-large",o("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[o("5,000 \u79EF\u5206 \xB7 180 \u5929\u6709\u6548","5,000 credits \xB7 180 days validity")])].slice(0,s.data.pageSize).map((p,u)=>({...p,...s.data.allowPurchase?{purchaseId:`10000000-0000-4000-8000-${String(u+1).padStart(12,"0")}`}:{}})):s.data.source==="credit_pack_orders"?c.rows=[a("sample-order",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",o("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[a("sample-offer",o("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",o("\u53EF\u7528","Available"),[o("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as te}from"zod";import{z as U}from"zod";var Gd=U.enum(["customer","coupon","audience"]),Kd=U.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),Pr=U.object({baseRevision:U.number().int().nonnegative(),latestRevision:U.number().int().nonnegative(),mode:U.enum(["merge","use_latest"]),decisions:U.array(U.object({field:Kd,mine:U.number().int().min(0).max(1e3),latest:U.number().int().min(0).max(1e3)}).strict().refine(e=>e.mine+e.latest>0)).max(28)}).strict().refine(e=>e.latestRevision>e.baseRevision).refine(e=>new Set(e.decisions.map(t=>t.field)).size===e.decisions.length).refine(e=>e.mode!=="use_latest"||e.decisions.length===0),jc=U.number().int().nonnegative().nullable(),Qd=U.object({resource:Gd,id:U.uuid(),projectId:U.uuid(),environmentId:U.uuid(),fromRevision:jc,toRevision:jc,provenance:U.enum(["recorded","historical"]),changes:U.array(U.object({field:U.string(),redacted:U.boolean(),before:U.union([U.string(),U.number(),U.boolean(),U.null()]),after:U.union([U.string(),U.number(),U.boolean(),U.null()])})),merge:Pr.safeExtend({source:U.literal("client")}).nullable()}),Wd=U.object({createdAt:U.iso.datetime({offset:!0}),id:U.uuid()}).strict(),kx=U.object({events:U.array(U.object({id:U.uuid(),action:U.string(),actorId:U.uuid().nullable(),actorEmail:U.email().nullable(),createdAt:U.iso.datetime({offset:!0}),object:Qd})),nextCursor:Wd.nullable()});var zx={type:"condition",condition:{}},_x=te.strictObject({id:te.uuid(),name:te.string().min(1).max(80),description:te.string().max(500),config:Wn,revision:te.number().int().min(1),status:te.enum(["active","archived"]),batchable:te.boolean(),created_at:te.iso.datetime({offset:!0}),updated_at:te.iso.datetime({offset:!0})}),Rx=te.discriminatedUnion("action",[te.strictObject({action:te.literal("save"),id:te.uuid().nullable(),audit:Pr.nullable().optional(),revision:te.number().int().min(0),name:te.string().trim().min(1).max(80),description:te.string().max(500),config:Wn}),te.strictObject({action:te.literal("archive"),id:te.uuid(),audit:Pr.nullable().optional(),revision:te.number().int().min(1)})]),Zd=te.object({id:te.uuid(),name:te.string().nullable(),external_user_id:te.string(),attributes:Je,created_at:te.iso.datetime({offset:!0})}),Ex=te.object({customers:Zd.array(),hasMore:te.boolean(),offset:te.number().int().min(0),limit:te.number().int().min(1),evaluatedAt:te.iso.datetime({offset:!0}),revision:te.number().int().min(1)});import{z as Bn}from"zod";var Bx=Bn.object({defaultLocale:ft,locales:Bn.record(ft,Bn.object({name:Bn.string().max(80),description:Bn.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"})});function $x(e,t){let n=e.displayCopy;if(!n)return{name:e.name,description:""};let r=Object.keys(n.locales).filter(s=>n.locales[s].name.trim()),i=Hn([t],r,n.defaultLocale),o=n.locales[i],a=n.locales[n.defaultLocale];return{name:o?.name.trim()?o.name:a?.name.trim()?a.name:e.name,description:o?.description.trim()?o.description:a?.description.trim()?a.description:""}}var Cc="#172033",zr="#667085",Hd="#E2E6EE",Jd="#2C3C96",Fe=e=>({top:e,right:e,bottom:e,left:e}),ze=e=>({type:"color",color:e}),Ke=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,o=zr,a={}){return this.zh[t]=n,this.en[t]=r,{id:t,type:"text",text:t,variant:i>=30?"title":"body",style:{text:{size:i,color:o,weight:i>=30?600:400,lineHeight:1.35,...i>=30?{letterSpacing:-1.2}:{}},...a}}}stack(t,n,r={},i=!1){return{id:t,type:"stack",direction:i?"horizontal":"vertical",align:"stretch",justify:"start",children:n,style:{gap:i?40:24,...r}}}widget(t,n,r,i,o=!1,a={}){let s=t+"_title";return this.zh[s]=r,this.en[s]=i,{id:t,type:"customer_data",title:s,data:{source:n,layout:o?"compact":"full",pageSize:n==="credit_transactions"?5:4,showSources:n==="credit_balance"&&!o,allowPurchase:n==="credit_packs"},style:a}}rule(t,n=Hd){return{id:t,type:"divider",style:{background:ze(n),height:1}}}header(t,n,r,i,o,a=!1){return this.stack("account_header",[this.stack("intro",[this.text("eyebrow","\u5DE5\u4F5C\u7A7A\u95F4 / \u8D26\u6237","WORKSPACE / ACCOUNT",11,a?"#A9B4CB":zr,{text:{size:11,color:a?"#A9B4CB":zr,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,a?"#FFFFFF":Cc),this.text("description",r,i,14,a?"#A9B4CB":zr)],{gap:12,width:660,grow:!0}),...o?[o]:[]],{gap:32},!0)}document(t,n=!1){return We.parse({kind:"screen",schemaVersion:3,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:Jd,background:n?"#101A30":"#F5F6FA",text:Cc,radius:"md",font:"system",...this.design.theme},pages:[{id:"account_page",name:this.name,root:{...this.stack("root",[this.stack("content",t,{width:this.design.width??1200,gap:this.design.gap??32})],{padding:this.design.padding??{top:40,right:24,bottom:36,left:24}}),align:"center"}}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":this.zh,en:this.en}},actions:[]})}};var Rr="#19202E",Yd="#667080",go="#2C3C96",Oc="#DDE2E9",Pc="#F0F3FA",Xd=(e=72,t=Rr)=>({text:{size:e,color:t,weight:600,font:"system"}}),_r=(e,t=1)=>({width:e,grow:t}),em={background:ze("#FFFFFF"),shape:{type:"rect",radius:10}};function tm(e){return new Ke(e,{theme:{background:"#FFFFFF",text:Rr,primary:go},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function nm(e,t,n,r,i){let o=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,go,{text:{size:13,color:go,weight:700,letterSpacing:.8}});return e.stack("page_header",[o,e.text("heading",t,n,40,Rr,{text:{size:40,color:Rr,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,Yd)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function zc(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new Ke("\u8D26\u6237\u4E00\u89C8",{theme:{background:e,text:t,primary:n,radius:"none"},width:1120,gap:36,padding:{top:32,right:24,bottom:48,left:24}}),o=(a,s,c)=>i.text(a,s,c,12,n,{text:{size:12,color:n,font:"mono",weight:500,letterSpacing:1.1}});return i.document([i.stack("journal_masthead",[i.stack("journal_identity",[i.text("wordmark","GROW","GROW",22,t,{text:{size:22,color:t,weight:700,letterSpacing:-1}}),o("edition","\u8D26\u6237 / ACCOUNT","ACCOUNT / JOURNAL")],{gap:16},!0),i.rule("masthead_rule",t),i.stack("journal_intro",[i.text("heading","\u8D26\u6237\u4E00\u89C8","Your account.",64,t,{width:720,grow:2,text:{size:64,color:t,font:"serif",weight:400,lineHeight:1.12,letterSpacing:-2}}),i.stack("intro_note",[o("intro_index","\u4E3A\u4F60\u7684\u4E0B\u4E00\u6B21\u521B\u4F5C","FOR YOUR NEXT CHAPTER"),i.text("description",`\u4F60\u7684\u4F1A\u5458\u3001\u79EF\u5206\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C
|
|
18
|
-
\u5728\u4E00\u5904\u4ECE\u5BB9\u638C\u63E1\u3002`,`Membership, credits and purchases.
|
|
19
|
-
A little clarity for what's next.`,14,r)],{width:300,grow:1,gap:12,padding:{top:8,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("account_summary",[i.stack("member_column",[o("member_index","01 / \u4F1A\u5458","01 / MEMBERSHIP"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:t,font:"serif",size:40,weight:400}})],{width:660,grow:2,gap:16}),i.stack("balance_column",[o("balance_index","02 / \u79EF\u5206","02 / CREDITS"),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:t,font:"serif",size:64,weight:400}})],{width:340,grow:1,gap:16})],{gap:48,padding:{top:12,right:0,bottom:12,left:0}},!0),i.rule("records_rule","#D9CFC1"),i.stack("account_records",[i.stack("purchase_column",[o("purchase_index","03 / \u8D2D\u4E70\u8BB0\u5F55","03 / PURCHASES"),i.widget("orders","credit_pack_orders","\u6BCF\u4E00\u7B14\u8D2D\u4E70","Your purchases",!1,{text:{color:t}})],{width:660,grow:2,gap:16}),i.stack("offer_column",[o("offer_index","04 / \u4E13\u5C5E\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u53EF\u7528\u4F18\u60E0","Available offers",!0,{text:{color:t}})],{width:340,grow:1,gap:16})],{gap:48},!0),i.rule("catalog_rule","#D9CFC1"),i.stack("account_catalog",[o("catalog_index","05 / \u65B9\u6848","05 / PLANS"),i.widget("plans","customer_plans","\u63A2\u7D22\u9002\u5408\u4F60\u7684\u65B9\u6848","Find your next plan",!0,{text:{color:t}})],{gap:16}),i.text("journal_footer","GROW / \u8BA9\u521B\u4F5C\u7EE7\u7EED","GROW / KEEP CREATING",11,r,{text:{size:11,color:r,font:"mono",letterSpacing:1}})])}function _c(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new Ke("\u79EF\u5206\u5DE5\u4F5C\u53F0",{theme:{background:"#EDF1F7",text:e,primary:"#244F9E",radius:"sm"},width:1200,gap:24,padding:{top:24,right:24,bottom:40,left:24}}),i=(o,a,s)=>r.text(o,a,s,11,t,{text:{size:11,color:t,font:"mono",weight:500,letterSpacing:1}});return r.document([r.stack("terminal_header",[i("wordmark","GROW / \u79EF\u5206\u5DE5\u4F5C\u53F0","GROW / CREDIT WORKSPACE"),r.stack("terminal_intro",[r.text("heading","\u79EF\u5206\u4E0E\u7528\u91CF","Credits & usage",36,e,{width:780,grow:2,text:{size:36,color:e,weight:600,letterSpacing:-1.2,lineHeight:1.15}}),r.text("description","\u4F59\u989D\u3001\u5230\u671F\u6765\u6E90\u4E0E\u6BCF\u4E00\u7B14\u4F7F\u7528\u3002","Balance, expiry and every transaction.",13,t,{width:340,grow:1})],{gap:32},!0)],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),r.stack("terminal_workspace",[r.stack("ledger_workspace",[r.stack("credit_summary",[i("balance_index","01 / \u8D26\u6237\u4F59\u989D","01 / BALANCE"),r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{text:{size:80,color:e,font:"mono",weight:500}})],{gap:16,padding:Fe(28),background:ze("#E0E8F4")}),r.stack("ledger_panel",[i("activity_index","02 / \u8D26\u76EE\u660E\u7EC6","02 / ACTIVITY"),r.widget("activity","credit_transactions","\u79EF\u5206\u6D41\u6C34","Credit history",!1,{text:{color:e}})],{gap:16,padding:Fe(28),background:ze("#FFFFFF")})],{width:820,grow:2,gap:2}),r.stack("purchase_rail",[r.stack("plan_context",[i("membership_index","\u8D26\u6237 / \u65B9\u6848","ACCOUNT / PLAN"),r.widget("membership","membership","\u5F53\u524D\u65B9\u6848","Current plan",!0,{text:{color:e}})],{gap:16,padding:Fe(24),background:ze("#FFFFFF")}),r.stack("purchase_panel",[i("purchase_index","03 / \u8865\u5145\u79EF\u5206","03 / TOP UP"),r.widget("packs","credit_packs","\u8D2D\u4E70\u79EF\u5206","Buy credits",!0,{text:{color:e}}),r.text("purchase_note","\u8D2D\u4E70\u524D\u67E5\u770B\u79EF\u5206\u6570\u91CF\u4E0E\u6709\u6548\u671F\u3002","Check the credit amount and validity before purchase.",12,t)],{gap:16,padding:Fe(24),background:ze("#FFFFFF")}),r.stack("orders_panel",[i("orders_index","04 / \u8D2D\u4E70\u8BB0\u5F55","04 / PURCHASES"),r.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0,{text:{color:e}})],{gap:16,padding:Fe(24),background:ze("#FFFFFF")})],{width:348,grow:1,gap:2})],{gap:24},!0),r.rule("terminal_rule",n),i("terminal_footer","GROW / \u6309\u8D44\u6E90\u67E5\u770B\u4F59\u989D \xB7 \u6309\u8BB0\u5F55\u6838\u5BF9\u4F7F\u7528","GROW / RESOURCE BALANCES \xB7 TRANSACTION RECORDS")])}function Rc(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new Ke("\u4F1A\u5458\u4FF1\u4E50\u90E8",{theme:{background:t,text:e,primary:e,radius:"none"},width:1160,gap:32,padding:{top:28,right:24,bottom:48,left:24}}),o=(a,s,c,p=n)=>i.text(a,s,c,12,p,{text:{size:12,color:p,font:"mono",letterSpacing:1,weight:500}});return i.document([i.stack("club_masthead",[i.stack("club_identity",[i.text("wordmark","GROW CLUB","GROW CLUB",22,e,{text:{size:22,color:e,weight:700,letterSpacing:-.6}}),o("club_edition","\u4F1A\u5458 / MEMBERSHIP","MEMBERSHIP / YOUR SPACE")],{gap:20},!0),i.rule("club_rule",e),i.stack("club_intro",[i.text("heading","\u4F1A\u5458\u4E0E\u65B9\u6848","Room to grow.",64,e,{width:752,grow:2,text:{size:64,color:e,font:"serif",weight:400,lineHeight:1.1,letterSpacing:-2}}),i.stack("club_description",[o("club_intro_label","\u4E3A\u6301\u7EED\u7684\u521B\u9020\u529B","FOR WHAT COMES NEXT"),i.text("description",`\u67E5\u770B\u4F60\u7684\u4F1A\u5458\u72B6\u6001\uFF0C
|
|
20
|
-
\u627E\u5230\u9002\u5408\u4E0B\u4E00\u6B65\u7684\u65B9\u6848\u3002`,`Your membership, at a glance.
|
|
21
|
-
A plan for what comes next.`,14,n)],{width:320,grow:1,gap:12,padding:{top:10,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("membership_summary",[i.stack("member_spread",[o("member_index","01 / \u4F60\u7684\u4F1A\u5458","01 / YOUR MEMBERSHIP","#CCD9CA"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:"#FFFFFF",font:"serif",size:52,weight:400}})],{width:744,grow:2,gap:20,padding:Fe(32),background:ze(e)}),i.stack("balance_inset",[o("balance_index","02 / \u521B\u4F5C\u4F59\u989D","02 / CREDIT BALANCE",e),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:e,size:60,weight:500}})],{width:376,grow:1,gap:20,padding:Fe(28),background:ze(r)})],{gap:0},!0),i.stack("plan_comparison",[o("plans_index","03 / \u9009\u62E9\u4F60\u7684\u4E0B\u4E00\u6B65","03 / YOUR NEXT STEP"),i.widget("plans","customer_plans","\u627E\u5230\u9002\u5408\u4F60\u7684\u65B9\u6848","A plan to make it yours",!1,{text:{color:e,font:"serif"}})],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),i.rule("benefits_rule","#C8CEC2"),i.stack("benefit_records",[i.stack("member_offers",[o("offers_index","04 / \u4F60\u7684\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u4F1A\u5458\u4F18\u60E0","Member offers",!1,{text:{color:e}})],{width:556,grow:1,gap:16}),i.stack("member_purchases",[o("orders_index","05 / \u8D2D\u4E70\u8BB0\u5F55","05 / PURCHASES"),i.widget("orders","credit_pack_orders","\u8D2D\u4E70\u4E0E\u8BB0\u5F55","Purchases & records",!1,{text:{color:e}})],{width:556,grow:1,gap:16})],{gap:48},!0),i.rule("footer_rule","#C8CEC2"),o("club_footer","GROW CLUB / \u7559\u51FA\u521B\u9020\u7684\u7A7A\u95F4","GROW CLUB / ROOM FOR WHAT'S NEXT")])}function Ec(){let e=tm("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([nm(e,"\u521B\u4F5C\u5DE5\u4F5C\u533A","Your workspace","\u79EF\u5206\u3001\u4F1A\u5458\u548C\u4F7F\u7528\u8BB0\u5F55\uFF0C\u90FD\u5728\u8FD9\u91CC\u3002","Your credits, membership and activity."),e.stack("studio_summary",[e.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{..._r(784,2),...Xd(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{..._r(328),background:ze(Pc),padding:Fe(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",Oc),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,_r(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",Oc),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{..._r(328),...em,padding:Fe(24),gap:24,background:ze(Pc)})],{gap:48},!0)])}function Tc(){return Ec()}var lt=(e,t=1)=>({width:e,grow:t}),Er=(e=16)=>({shape:{type:"rect",radius:e}}),ve=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),xt=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function rm(e,t,n,r,i="system"){return e.text("heading",t,n,28,r,{text:{size:28,font:i,weight:600,color:r,lineHeight:1.2,letterSpacing:-.8}})}function im(e,t,n,r,i){return e.text(t,n,r,11,i,{text:{size:11,font:"system",weight:500,color:i,letterSpacing:.6}})}function $n(e,t,n,r,i,o="system"){let a=e.stack("masthead",[rm(e,t,n,r,o),im(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return a.justify="between",a.align="center",a}function Dc(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,ve(t));return i.data.pageSize=r,i}function om(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new Ke("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:xt(32,24,48)});return i.document([$n(i,"\u79EF\u5206\u8D26\u6237","Credits",t,n),i.rule("header_rule","#354039"),i.stack("wallet_workspace",[i.stack("wallet_primary",[i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,ve(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,ve(t))],{...lt(680,2),gap:32,padding:xt(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,ve(e))],{...lt(328),background:ze(r),padding:Fe(24),...Er(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),Dc(i,t,!1,4)])}function am(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new Ke("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:xt(40,24,48)});return r.document([$n(r,"\u8D26\u6237\u6863\u6848","Account journal",e,t,"serif"),r.rule("header_rule",e),r.stack("statement",[r.stack("balance_column",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,ve(e,96,"serif"))],{...lt(628,2),padding:xt(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,ve(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,ve(e))],{...lt(356),gap:20,padding:xt(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,ve(e))])}function sm(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new Ke("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:xt(32,24,48)});return i.document([$n(i,"\u4F1A\u5458\u4E2D\u5FC3","Membership",e,t),i.stack("current_membership",[i.stack("member_credential",[i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,ve("#F4F7F0"))],{...lt(640,2),gap:24,background:ze(n),padding:Fe(32),...Er(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,ve(e,64))],{...lt(400),background:ze("#E9EFE5"),padding:Fe(28),...Er(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,ve(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,ve(e))])}function cm(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new Ke("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:xt(32,24,48)});return r.document([$n(r,"\u7528\u91CF\u4E0E\u8BB0\u5F55","Usage & history",e,t),r.rule("header_rule",e),r.stack("account_context",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{...lt(688,2),...ve(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...lt(372),...ve(e)})],{gap:72,padding:xt(4,0,8)},!0),r.rule("activity_rule",n),Dc(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,ve(e))])}function um(){let e="#3F3029",t="#8B766A",n="#A34525",r=new Ke("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:xt(32,24,48)});return r.document([$n(r,"\u8865\u5145\u79EF\u5206","Add credits",e,t),r.rule("header_rule","#E8DDD3"),r.stack("purchase_workspace",[r.stack("account_context",[r.widget("balance","credit_balance","\u73B0\u6709\u79EF\u5206","Current credits",!0,ve(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,ve(e))],{...lt(304),gap:28,padding:Fe(24),background:ze("#F1E5D9"),...Er(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,ve(e))],{...lt(800,2),gap:24})],{gap:32},!0),r.rule("orders_rule","#E8DDD3"),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Recent purchases",!1,ve(e))])}function Fc(){return[{key:"page-credits-midnight",label:"\u6697\u7EFF\u79EF\u5206\u53F0 \xB7 \u591C\u95F4\u6A21\u5F0F",description:"\u4EE5\u5B9E\u65F6\u4F59\u989D\u4E3A\u4E3B\u89C6\u89C9\uFF0C\u6D45\u7EFF\u8D2D\u4E70\u533A\u4E0E\u5B8C\u6574\u6D41\u6C34\u5F62\u6210\u660E\u786E\u64CD\u4F5C\u987A\u5E8F\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u6697\u8272","\u79EF\u5206","\u8D2D\u4E70","\u684C\u9762"],create:om},{key:"page-account-journal",label:"\u8D26\u6237\u6863\u6848 \xB7 \u7EB8\u611F\u6392\u7248",description:"\u7EB8\u611F\u8D26\u76EE\u3001\u886C\u7EBF\u4F59\u989D\u3001\u8FB9\u680F\u4F1A\u5458\u4E0E\u4F18\u60E0\uFF0C\u4FDD\u7559\u6E05\u6670\u7684\u8D2D\u4E70\u8BB0\u5F55\u3002",category:"\u8D26\u6237\u7A7A\u95F4",tags:["\u7EB8\u611F","\u886C\u7EBF","\u8D26\u6237","\u8BB0\u5F55"],create:am},{key:"page-membership-sage",label:"\u4F1A\u5458\u7A7A\u95F4 \xB7 \u677E\u7EFF",description:"\u677E\u7EFF\u4F1A\u5458\u51ED\u8BC1\u4E0E\u4F59\u989D\u5E76\u6392\uFF0C\u4E0B\u65B9\u5C55\u793A\u5F53\u524D\u5BA2\u6237\u53EF\u89C1\u7684\u65B9\u6848\u4E0E\u4EF7\u683C\u3002",category:"\u4F1A\u5458\u4E0E\u65B9\u6848",tags:["\u677E\u7EFF","\u4F1A\u5458","\u65B9\u6848","\u684C\u9762"],create:sm},{key:"page-wallet-violet",label:"\u521B\u4F5C\u5DE5\u4F5C\u533A \xB7 \u79EF\u5206\u4E0E\u8BB0\u5F55",description:"\u8D26\u6237\u72B6\u6001\u3001\u5B8C\u6574\u4F7F\u7528\u8BB0\u5F55\u548C\u4FA7\u680F\u79EF\u5206\u8D2D\u4E70\uFF0C\u96C6\u4E2D\u5728\u6E05\u6670\u7684\u5DE5\u4F5C\u533A\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u5DE5\u4F5C\u533A","\u521B\u4F5C","\u79EF\u5206","\u8BB0\u5F55"],create:Tc},{key:"page-usage-ledger",label:"\u7528\u91CF\u8D26\u518C \xB7 \u9ED1\u767D",description:"\u7D27\u51D1\u8D26\u6237\u72B6\u6001\u3001\u5BBD\u5E45\u6D41\u6C34\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C\u9002\u5408\u7528\u91CF\u5BC6\u96C6\u7684\u4EA7\u54C1\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u9ED1\u767D","\u7B49\u5BBD","\u6D41\u6C34","\u684C\u9762"],create:cm},{key:"page-topup-orange",label:"\u79EF\u5206\u8865\u7ED9 \xB7 \u6696\u6A59",description:"\u5546\u54C1\u4EF7\u683C\u4E0E\u8D2D\u4E70\u5165\u53E3\u5E76\u6392\u5448\u73B0\uFF0C\u65C1\u8FB9\u4FDD\u7559\u5B9E\u65F6\u4F59\u989D\u548C\u4F1A\u5458\u72B6\u6001\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u6696\u6A59","\u8D2D\u4E70","\u79EF\u5206\u5305","\u8BA2\u5355"],create:um}].map(({create:e,...t})=>({...t,document:e()}))}function lm(){return _c()}function dm(){return zc()}function mm(){return Rc()}function Jx(){return[...Fc(),{key:"page-credit-center-wallet",label:"\u79EF\u5206\u5DE5\u4F5C\u53F0 \xB7 Terminal",description:"\u84DD\u7070\u8D26\u76EE\u5DE5\u4F5C\u53F0\uFF1A\u7CBE\u786E\u4F59\u989D\u4E0E\u5B8C\u6574\u6D41\u6C34\u4E3A\u4E3B\uFF0C\u65B9\u6848\u3001\u79EF\u5206\u8D2D\u4E70\u4E0E\u8BA2\u5355\u7F6E\u4E8E\u72EC\u7ACB\u64CD\u4F5C\u680F\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u79EF\u5206","\u6D41\u6C34","\u771F\u5B9E\u6570\u636E","\u684C\u9762"],document:lm()},{key:"page-account-overview",label:"\u8D26\u6237\u4E00\u89C8 \xB7 Journal",description:"\u6696\u7EB8\u8272\u4E0E\u886C\u7EBF\u5B57\u4F53\u7684\u6742\u5FD7\u5F0F\u8D26\u6237\u9875\uFF1A\u4F1A\u5458\u4E0E\u79EF\u5206\u5C55\u5F00\u5448\u73B0\uFF0C\u8D2D\u4E70\u3001\u4F18\u60E0\u548C\u65B9\u6848\u5206\u533A\u9605\u8BFB\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u8D26\u6237","\u4F1A\u5458","\u4F18\u60E0","\u771F\u5B9E\u6570\u636E"],document:dm()},{key:"page-membership-catalog",label:"\u4F1A\u5458\u4FF1\u4E50\u90E8 \xB7 Club",description:"\u68EE\u6797\u7EFF\u4E0E\u8C61\u7259\u767D\u7684\u54C1\u724C\u4F1A\u5458\u9875\uFF1A\u5F3A\u5B57\u4F53\u3001\u5BF9\u6BD4\u8272\u4F1A\u5458\u533A\u3001\u5F00\u653E\u5F0F\u65B9\u6848\u6BD4\u8F83\u4E0E\u5B8C\u6574\u8D26\u6237\u8BB0\u5F55\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u4F1A\u5458","\u5957\u9910","\u8D44\u683C","\u771F\u5B9E\u6570\u636E"],document:mm()}]}import{z as Ne}from"zod";var Bc=Ne.object({id:Ne.string().min(1).max(64),name:Ne.string().min(1).max(80),type:Ne.enum(["entry","condition"])}).strict(),pm=Ne.object({id:Ne.uuid(),name:Ne.string().min(1).max(80),status:Ne.enum(["draft","published","archived"]),draftNodes:Ne.array(Bc).max(500),publishedNodes:Ne.array(Bc).max(500),runningVersions:Ne.number().int().nonnegative()}).strict().refine(e=>e.draftNodes.length>0||e.publishedNodes.length>0||e.runningVersions>0,"A Funnel usage must have a current reference or an unfinished run"),eS=Ne.object({rows:Ne.array(pm).max(50),nextCursor:Ne.uuid().nullable()}).strict();import{z as G}from"zod";var Vc=G.strictObject({version:G.number().int().positive(),nodeId:G.string().min(1).max(64)}),aS=G.strictObject({versionId:G.uuid().nullable(),experimentId:G.uuid().nullable(),bucketVersion:G.number().int().nonnegative().nullable(),from:G.iso.datetime({offset:!0}).nullable(),to:G.iso.datetime({offset:!0}).nullable(),after:Vc.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),_e=G.number().int().nonnegative(),$c=G.object({currency:z,grossMinor:G.string().regex(/^\d+$/),refundMinor:G.string().regex(/^\d+$/),netMinor:G.string().regex(/^-?\d+$/)}).strict(),sS=G.object({funnelId:G.uuid(),snapshotAt:G.iso.datetime({offset:!0}),versions:G.array(G.strictObject({id:G.uuid(),version:G.number().int().positive(),createdAt:G.iso.datetime({offset:!0})})).max(100),versionsLimited:G.boolean(),history:G.array(G.strictObject({versionId:G.uuid(),version:G.number().int().positive(),createdAt:G.iso.datetime({offset:!0}),node:io,experiment:ci})).max(50),nextCursor:Vc.nullable(),overall:G.object({started:_e,completed:_e,closed:_e,authenticated:_e,paid:_e}).strict(),revenue:G.array($c).max(100),decisions:G.strictObject({queries:_e,completed:_e,allocations:_e,reportedUsed:_e,unknownUsage:_e,pending:_e,failed:_e}),experiments:G.array(G.object({nodeId:G.string(),versionId:G.uuid(),experimentId:G.uuid(),bucketVersion:G.number().int().nonnegative(),variantKey:G.string().nullable(),goal:G.enum(["completed","authenticated","paid","net_revenue"]),participants:_e,runs:_e,completed:_e,authenticated:_e,paid:_e,revenue:G.array($c).max(100)}).strict()).max(2500)}).strict();import{z as St}from"zod";var mS=St.object({requestId:St.uuid(),coupon:oa,audienceId:St.uuid().nullable(),productVersionId:St.uuid(),trigger:St.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),presentation:_t,locale:St.enum(["en","zh-CN"])}).strict(),pS=St.object({couponId:St.uuid(),funnelId:St.uuid()}).strict();import{z as Y}from"zod";var Re=Y.number().int().nonnegative(),Tr=Y.string().regex(/^-?\d+$/),fm=Y.object({currency:z,grossMinor:Tr,refundMinor:Tr,netMinor:Tr,purchases:Re,refunds:Re}).strict(),bS=Y.object({snapshotAt:Y.iso.datetime({offset:!0}),customers:Y.object({total:Re,created:Re,paid:Re}).strict(),memberships:Y.object({active:Re,trial:Re,pastDue:Re,ended:Re}).strict(),runs:Y.object({started:Re,completed:Re,closed:Re,paid:Re}).strict(),revenue:Y.array(fm).max(100),unknownMoney:Re,funnels:Y.array(Y.object({id:Y.uuid(),name:Y.string(),started:Re,completed:Re,paid:Re}).strict()).max(50),daily:Y.array(Y.object({date:Y.iso.date(),currency:z,netMinor:Tr}).strict()).max(9e3)}).strict(),yS=Y.object({customerId:Y.uuid(),rows:Y.array(Y.object({id:Y.string().regex(/^\d+$/),funnelId:Y.uuid(),funnelName:Y.string(),versionId:Y.uuid(),runId:Y.uuid(),nodeId:Y.string(),experimentId:Y.uuid(),round:Y.number().int().positive(),variantId:Y.string().nullable(),mode:Y.enum(["experiment","winner"]),assignedAt:Y.iso.datetime({offset:!0}),runStatus:Y.string()}).strict()).max(50),nextCursor:Y.string().regex(/^\d+$/).nullable()}).strict();import{z as Ze}from"zod";var AS=Ze.strictObject({operation:Ze.literal("native_receipt"),requestId:Ze.uuid(),customerToken:Ze.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:Ze.uuid(),receiptId:Ze.uuid(),nativeEvidence:so.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),kS=Ze.strictObject({scope:be,requestId:Ze.uuid(),orderId:Ze.uuid(),receiptId:Ze.uuid(),orderStatus:Ze.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Ze.boolean(),nativeCompletion:jr.shape.nativeCompletion});import{z as gm}from"zod";var hm=pc.extend({document:gm.union([We.refine(e=>e.pages.length===1,"Use a single owned screen template"),Ge.refine(e=>e.screens.length>0&&e.screens.every(t=>t.type==="owned"),"Flow templates own their screens")])}).superRefine((e,t)=>{if((e.document.kind==="funnel"?e.surface!=="onboarding":e.surface!==e.document.surface)&&t.addIssue({code:"custom",message:"Template category does not match its document"}),e.document.kind==="funnel"){let n=e.document,r=n.graph.nodes.filter(i=>i.type==="screen");(new Set(n.screens.map(i=>i.id)).size!==n.screens.length||new Set(n.graph.nodes.map(i=>i.id)).size!==n.graph.nodes.length||r.length!==n.screens.length||n.screens.some(i=>r.filter(o=>o.screenId===i.id).length!==1))&&t.addIssue({code:"custom",message:"Every template screen requires one unique flow node"})}});function TS(e,t=0){if(e.document.kind==="screen")return e.document;let n=e.document.screens[t];if(n?.type!=="owned")throw new Error("Owned template screen required");let r=e.document.graph.nodes.find(i=>i.type==="screen"&&i.screenId===n.id);if(r?.type!=="screen")throw new Error("Template screen node required");return{...n.document,presentation:r.presentation.type==="inline"?{type:"fullscreen"}:r.presentation}}function bm(e,t){let n=structuredClone(hm.parse(e).document);if(n.kind==="funnel"){let p=function(u){if(Array.isArray(u)){u.forEach(p);return}if(!u||typeof u!="object")return;let S=u;S.type==="experiment-ref"&&(S.experimentId=c),S.$savedGroup&&typeof S.$savedGroup=="object"&&(S.$savedGroup.id=c),typeof S.$inGroup=="string"&&(S.$inGroup=c),typeof S.$notInGroup=="string"&&(S.$notInGroup=c),Object.values(S).forEach(p)};var s=p;let c="00000000-0000-0000-0000-000000000000";p(n.features);for(let u of n.graph.nodes)u.type==="condition"&&u.cases.forEach(S=>p(S.condition));for(let u of n.screens)u.type==="owned"&&qc(u.document);return Ge.parse({...n,name:e.label,screens:n.screens.map(u=>u.type==="owned"?{...u,document:{...u.document,strings:{...u.document.strings,defaultLocale:Zi(u.document,[t])}}}:u),graph:{...n.graph,nodes:n.graph.nodes.map(u=>u.type==="entry"?{...u,triggers:[],audienceId:null,startsAt:null,endsAt:null}:u.type==="split"?{...u,experimentId:"00000000-0000-0000-0000-000000000000"}:u.type==="checkout"?{...u,product:{type:"fixed",productVersionId:uc},couponId:void 0}:u)}})}let r={...n,strings:{...n.strings,defaultLocale:Zi(n,[t])}},i=[{id:"entry",type:"entry",name:t==="en"?"Entry":"\u5165\u53E3",next:"screen",triggers:[],audienceId:null,startsAt:null,endsAt:null,priority:0,cooldownSeconds:0,maxPerCustomer:null},{id:"done",name:t==="en"?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed"},{id:"closed",name:t==="en"?"Closed":"\u5173\u95ED",type:"end",outcome:"closed"}],o={};r.actions=r.actions.map((c,p)=>{let u=`action_${p}`;return o[c.id]=c.close?"closed":"done",c.type==="open_url"?(o[c.id]=u,i.push({id:u,name:c.id,type:"action",action:{type:"open_url",url:c.url},success:"done",cancel:"closed",unavailable:"closed",failure:"closed"})):c.type==="claim_offer"&&(o[c.id]="unconnected"),{id:c.id,type:"event",event:c.id,properties:{},close:!1}}),qc(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:o});let a=new Set(i.flatMap(Tn));return Ge.parse({features:{},kind:"funnel",schemaVersion:1,name:e.label,inputs:[],screens:[{id:"screen",type:"owned",document:r}],graph:{version:2,entry:"entry",nodes:i.filter(c=>c.type!=="end"||a.has(c.id))}})}function DS(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=bm(t,n),i=`tpl_${crypto.randomUUID().replaceAll("-","").slice(0,16)}_`,o=u=>u==="unconnected"?u:i+u,a=r.graph.nodes.slice().sort((u,S)=>+(S.type==="screen")-+(u.type==="screen")).filter(u=>u.type!=="entry").map(u=>u.type==="screen"?{...u,id:o(u.id),screenId:o(u.screenId),outputs:Object.fromEntries(Object.entries(u.outputs).map(([S,Q])=>[S,o(Q)]))}:u.type==="checkout"||u.type==="action"?{...u,id:o(u.id),success:o(u.success),cancel:o(u.cancel),unavailable:o(u.unavailable),failure:o(u.failure)}:{...u,id:o(u.id)}),s=Ge.parse({...e,screens:[...e.screens,...r.screens.map(u=>({...u,id:o(u.id)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...a]}}),c=0,p=0;for(let u of s.screens)u.type==="owned"&&(nt(u.document,()=>{c++}),p+=u.document.actions.length);if(c>we.components||p>we.actions||new TextEncoder().encode(JSON.stringify(s)).byteLength>we.documentBytes)throw new Error("Template exceeds the flow capacity");return s}function qc(e){nt(e,t=>{t.type==="stack"&&t.bind?(delete t.bind.plan,delete t.bind.coupon,delete t.bind.promotionCode,Object.keys(t.bind).length||delete t.bind):t.type==="plan_picker"&&(delete t.planIds,delete t.defaultPlan)})}function ym(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function BS(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function Nc(e){return ym(e)?e.intervalCount??1:1}function $S(e,t){return e.interval===t.interval&&Nc(e)===Nc(t)}function VS(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0],i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}import{z as se}from"zod";var Uc=se.enum(["membership","trial","topup","manual","rollover","seat"]),Mc=se.enum(["scheduled","active","expired","revoked","unavailable"]),MS=se.strictObject({customerId:se.uuid().nullable(),entityId:se.uuid().nullable(),entitlementId:se.uuid().nullable(),reason:Uc.nullable(),status:Mc.nullable(),after:se.uuid().nullable(),limit:se.number().int().min(1).max(50)}),LS=se.strictObject({snapshotAt:se.iso.datetime({offset:!0}),rows:se.array(se.strictObject({id:se.uuid(),customerId:se.uuid(),fundingCustomerId:se.uuid(),entityId:se.uuid().nullable(),entitlementId:se.uuid(),entitlementVersionId:se.uuid(),version:se.number().int().positive(),key:se.string().min(1).max(64),name:se.string().min(1).max(120),kind:se.enum(["access","metered","credit"]),reason:Uc,status:Mc,unlimited:se.boolean(),granted:ye,available:ye,held:ye,spent:ye,revoked:ye,transferred:ye,startsAt:se.iso.datetime({offset:!0}),expiresAt:se.iso.datetime({offset:!0}).nullable(),grantId:se.uuid().nullable(),membershipId:se.uuid().nullable(),seatPoolId:se.uuid().nullable()})).max(50),nextCursor:se.uuid().nullable()});import{z as L}from"zod";var Lc=L.strictObject({property:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/),datatype:L.enum(["boolean","string","number","enum","string[]","number[]","object","array","json"]),enumValues:L.array(L.string()).min(1).nullable(),format:L.enum(["","version","date","isoCountryCode"]),hashAttribute:L.boolean(),stored:L.boolean(),description:L.string().max(2e3),status:L.enum(["active","archived"])}).superRefine((e,t)=>{["parameters","answers","results","__proto__","constructor","prototype"].includes(e.property)&&t.addIssue({code:"custom",message:"Reserved attribute property"}),(e.datatype==="enum"!=(e.enumValues!==null)||e.hashAttribute&&!["string","number","enum"].includes(e.datatype))&&t.addIssue({code:"custom",message:"Hash attributes must be scalar strings or numbers; enums require values"})}),Gc=L.strictObject({name:L.string().min(1).max(128),label:L.string().min(1).max(80),description:L.string().max(2e3),status:L.enum(["active","inactive"]),hashAttribute:L.string().min(1).max(128),seed:L.string().min(1).max(128)}),ho={id:L.uuid(),revision:L.number().int().positive()},ZS=L.strictObject({experiments:L.array(L.strictObject({...ho,configuration:Yt,archivedAt:L.iso.datetime({offset:!0}).nullable()})),namespaces:L.array(L.strictObject({...ho,configuration:Gc})),attributes:L.array(L.strictObject({...ho,configuration:Lc})),truncated:L.boolean()}),bo={id:L.uuid().nullable(),revision:L.number().int().min(0)},HS=L.discriminatedUnion("resource",[L.strictObject({...bo,resource:L.literal("experiment"),configuration:Yt.safeExtend({archivedAt:L.iso.datetime({offset:!0}).nullable()})}),L.strictObject({...bo,resource:L.literal("namespace"),configuration:Gc}),L.strictObject({...bo,resource:L.literal("attribute"),configuration:Lc})]),JS=L.strictObject({operation:L.literal("evaluate"),attributes:Je,condition:ot.optional(),features:Zn,featureKey:L.string().min(1).max(128)});var Dr=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function xm(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!Dr(n.condition,r.condition)||!Dr(n.savedGroups,r.savedGroups))&&i.push("targeting"),r.coverage<n.coverage&&i.push("coverage"),r.namespace&&(!n.namespace||n.namespace.id!==r.namespace.id)&&i.push("namespace"),r.namespace&&n.namespace?.id===r.namespace.id&&n.namespace.ranges.some(([c,p])=>{let u=c;for(let[S,Q]of[...r.namespace.ranges].sort((ne,ke)=>ne[0]-ke[0]))S<=u&&Q>u&&(u=Q);return u<p})&&i.push("namespaceRange"),(!Dr(n.variationWeights,r.variationWeights)||!Dr(e.variations.map(c=>c.key),t.variations.map(c=>c.key)))&&i.push("weights"),(e.disableStickyBucketing!==t.disableStickyBucketing||n.seed!==r.seed)&&i.push("identity");let o=i.some(c=>["namespace","namespaceRange","weights","identity"].includes(c)),a=!t.disableStickyBucketing,s=o||i.length>0&&!a?"new-phase":a?"same-phase-sticky":"same-phase-everyone";return{reasons:i,disableSamePhase:o,recommended:s,risk:i.length?o?"danger":"warning":"safe"}}function eI(e,t,n,r,i){let o=structuredClone(t),a=o.phases.at(-1),s=!o.disableStickyBucketing;if(n==="same-phase-sticky"&&!s||n==="new-phase-block-sticky"&&!s)throw Error("Sticky bucketing is required");if(xm(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");return o.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),o.minBucketVersion=n==="new-phase-block-sticky"?o.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")&&(o.phases=structuredClone(e.phases),o.phases[o.phases.length-1].dateEnded=r,o.phases.push({...a,name:a.name,reason:a.reason,dateStarted:r,dateEnded:null,seed:i})),Yt.parse(o)}import{z as Sm}from"zod";var rI=Sm.enum(["owner","admin","developer","sales","member"]),Im=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],Kc=Im.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),Qc={owner:Kc,admin:Kc,developer:["organisation:read","customers:write","features:write","plans:write","rewards:write","balances:write","billing:write","migrations:write","analytics:read","apiKeys:write","platform:write"],sales:["customers:write","features:read","plans:read","rewards:write","balances:write","billing:write","analytics:read"],member:["organisation:read","customers:read","features:read","plans:read","rewards:read","balances:read","billing:read","analytics:read","apiKeys:read","platform:read"]};function iI(e,t){if(!e||!Object.hasOwn(Qc,e))return!1;let n=Qc[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}export{Zc as a,vm as b,Am as c,km as d,Vn as e,Fr as f,qn as g,So as h,xo as i,Br as j,Hc as k,Nn as l,It as m,z as n,Ft as o,Rm as p,Em as q,Io as r,Bm as s,wo as t,Yc as u,Xc as v,$m as w,Vr as x,je as y,_ as z,qr as A,mn as B,Ce as C,jo as D,Nr as E,Ur as F,Mr as G,Gm as H,Lr as I,Gr as J,Kr as K,tu as L,nu as M,Co as N,ru as O,Ym as P,Wr as Q,be as R,He as S,cp as T,Oo as U,up as V,Po as W,iu as X,zo as Y,lp as Z,dp as _,ou as $,_o as aa,Zr as ba,mp as ca,pp as da,No as ea,Ue as fa,Lo as ga,Go as ha,Me as ia,Je as ja,ot as ka,Wn as la,vu as ma,Jo as na,ku as oa,ju as pa,Zn as qa,Cu as ra,Yt as sa,qp as ta,Xo as ua,Np as va,Up as wa,ci as xa,ui as ya,Pu as za,Mp as Aa,Lp as Ba,ft as Ca,$t as Da,Hn as Ea,Ru as Fa,Qp as Ga,Jp as Ha,Eu as Ia,Tu as Ja,ra as Ka,rf as La,Xt as Ma,at as Na,ia as Oa,Du as Pa,oa as Qa,of as Ra,af as Sa,sf as Ta,cf as Ua,uf as Va,lf as Wa,pi as Xa,Jn as Ya,ua as Za,en as _a,tn as $a,Bu as ab,$u as bb,Vu as cb,qu as db,vt as eb,la as fb,da as gb,nn as hb,Yn as ib,Xn as jb,ma as kb,pa as lb,fa as mb,ga as nb,Uu as ob,ha as pb,Mu as qb,Lu as rb,Gu as sb,ba as tb,fi as ub,Ku as vb,yn as wb,ya as xb,xa as yb,Sa as zb,Ia as Ab,wa as Bb,Sn as Cb,In as Db,Nt as Eb,hi as Fb,va as Gb,er as Hb,bi as Ib,Qu as Jb,Aa as Kb,ka as Lb,Ut as Mb,tr as Nb,ja as Ob,Ca as Pb,Of as Qb,Pf as Rb,zf as Sb,Wu as Tb,Zu as Ub,_f as Vb,Rf as Wb,Hu as Xb,Ef as Yb,Tf as Zb,Df as _b,xi as $b,Vf as ac,qf as bc,Ju as cc,Yu as dc,Xu as ec,el as fc,Lf as gc,Gf as hc,Kf as ic,za as jc,Si as kc,eg as lc,tg as mc,tl as nc,Ra as oc,nl as pc,ag as qc,sg as rc,rr as sc,An as tc,Ii as uc,Ea as vc,ir as wc,Ta as xc,or as yc,rl as zc,Ba as Ac,wi as Bc,$a as Cc,Va as Dc,qa as Ec,il as Fc,Na as Gc,vi as Hc,Ua as Ic,vg as Jc,Ma as Kc,Ag as Lc,kg as Mc,ar as Nc,La as Oc,kn as Pc,ye as Qc,Ga as Rc,Ka as Sc,sr as Tc,Qa as Uc,ul as Vc,Wa as Wc,Za as Xc,Ha as Yc,Ai as Zc,ll as _c,Ja as $c,Vg as ad,Ya as bd,Xa as cd,Ug as dd,Mg as ed,On as fd,es as gd,Mt as hd,ts as id,ki as jd,cr as kd,ns as ld,ji as md,ml as nd,pl as od,fl as pd,rs as qd,Ci as rd,Oi as sd,is as td,Pi as ud,nh as vd,os as wd,ur as xd,gl as yd,Pn as zd,lr as Ad,as as Bd,_i as Cd,ch as Dd,ss as Ed,cs as Fd,Ri as Gd,ls as Hd,ds as Id,mr as Jd,pr as Kd,bl as Ld,yl as Md,xl as Nd,ms as Od,ps as Pd,fs as Qd,gs as Rd,hs as Sd,bs as Td,ys as Ud,xs as Vd,Is as Wd,Ti as Xd,ws as Yd,vs as Zd,As as _d,Sl as $d,ks as ae,Il as be,Gt as ce,js as de,Os as ee,Ps as fe,zs as ge,_s as he,Rs as ie,vl as je,Al as ke,Es as le,Fi as me,Ts as ne,kl as oe,jl as pe,qh as qe,Nh as re,Bi as se,Fs as te,Bs as ue,$s as ve,Vs as we,qs as xe,Uh as ye,Mh as ze,Ol as Ae,Lh as Be,Gh as Ce,$i as De,Vi as Ee,Ui as Fe,Ns as Ge,sn as He,Us as Ie,Pl as Je,zl as Ke,Mi as Le,Ms as Me,Ls as Ne,Gs as Oe,_l as Pe,wb as Qe,k as Re,Rl as Se,El as Te,Tl as Ue,vb as Ve,Ab as We,A as Xe,kb as Ye,Dl as Ze,Zs as _e,Ws as $e,Hs as af,fr as bf,gr as cf,Pb as df,zb as ef,Fl as ff,Js as gf,Ys as hf,$l as if,ec as jf,Tb as kf,tc as lf,Li as mf,nc as nf,Bb as of,Vl as pf,tt as qf,oc as rf,de as sf,ql as tf,Nl as uf,Ki as vf,rc as wf,zn as xf,ic as yf,Ul as zf,Ml as Af,sc as Bf,Ll as Cf,Gl as Df,Kl as Ef,Ql as Ff,Wl as Gf,cn as Hf,Zl as If,Hl as Jf,Jl as Kf,Yl as Lf,Xl as Mf,ed as Nf,td as Of,nd as Pf,rd as Qf,id as Rf,od as Sf,ad as Tf,cc as Uf,sd as Vf,ud as Wf,ld as Xf,Qi as Yf,Lb as Zf,dd as _f,Gb as $f,nt as ag,Kb as bg,We as cg,Pt as dg,Wi as eg,pd as fg,un as gg,Qb as hg,hd as ig,Zi as jg,Wb as kg,bd as lg,br as mg,Zb as ng,Hb as og,we as pg,uc as qg,dc as rg,lc as sg,xr as tg,Xb as ug,mc as vg,oy as wg,xd as xg,Sd as yg,ay as zg,sy as Ag,ly as Bg,dy as Cg,pc as Dg,gy as Eg,hy as Fg,zt as Gg,fc as Hg,Hi as Ig,Sr as Jg,Ir as Kg,gt as Lg,ht as Mg,vy as Ng,vr as Og,Xi as Pg,kd as Qg,gc as Rg,eo as Sg,Py as Tg,zy as Ug,_y as Vg,Ry as Wg,Ey as Xg,Ty as Yg,to as Zg,Dy as _g,hc as $g,bc as ah,jd as bh,qy as ch,Ny as dh,Uy as eh,Pd as fh,Dn as gh,_t as hh,no as ih,xc as jh,ro as kh,io as lh,oo as mh,Sc as nh,Tn as oh,zd as ph,_d as qh,Jy as rh,Ar as sh,so as th,co as uh,Ge as vh,kr as wh,Td as xh,m0 as yh,Dd as zh,Fd as Ah,b0 as Bh,y0 as Ch,x0 as Dh,wc as Eh,R0 as Fh,Bd as Gh,$d as Hh,uo as Ih,jr as Jh,F0 as Kh,B0 as Lh,vc as Mh,Vd as Nh,lo as Oh,mo as Ph,qd as Qh,Nd as Rh,W0 as Sh,Z0 as Th,H0 as Uh,J0 as Vh,Or as Wh,rx as Xh,Ld as Yh,ix as Zh,ox as _h,ax as $h,sx as ai,lx as bi,px as ci,kc as di,bx as ei,yx as fi,wx as gi,Gd as hi,Kd as ii,Pr as ji,Qd as ki,Wd as li,kx as mi,zx as ni,_x as oi,Rx as pi,Zd as qi,Ex as ri,Bx as si,$x as ti,lm as ui,dm as vi,mm as wi,Jx as xi,Bc as yi,pm as zi,eS as Ai,Vc as Bi,aS as Ci,sS as Di,mS as Ei,pS as Fi,fm as Gi,bS as Hi,yS as Ii,AS as Ji,kS as Ki,hm as Li,TS as Mi,bm as Ni,DS as Oi,ym as Pi,BS as Qi,Nc as Ri,$S as Si,VS as Ti,Uc as Ui,Mc as Vi,MS as Wi,LS as Xi,Lc as Yi,Gc as Zi,ZS as _i,HS as $i,JS as aj,xm as bj,eI as cj,rI as dj,Im as ej,Qc as fj,iI as gj};
|