@tinkerlandai/indiana-sdk 0.7.0 → 0.8.1

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/README.md +73 -25
  3. package/README.zh-CN.md +77 -25
  4. package/dist/ai-usage-JoM7ZWk-.d.ts +247 -0
  5. package/dist/{ai-usage-BsrSG955.d.ts → api-JVC7x2FV.d.ts} +337 -386
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-56AYS7RS.js +1 -0
  8. package/dist/{chunk-6MO6Y24B.js → chunk-6HG7U6AU.js} +1 -1
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-AEUFCOFG.js +1 -0
  11. package/dist/chunk-F767CM3T.js +7 -0
  12. package/dist/chunk-KSNOXNTC.js +1 -0
  13. package/dist/{chunk-4AWSZWZD.js → chunk-USLZX2ZA.js} +1 -1
  14. package/dist/{chunk-YAFMBXIE.js → chunk-X747SY26.js} +1 -1
  15. package/dist/chunk-X7JJAEQQ.js +350 -0
  16. package/dist/chunk-YWFNWK7C.js +1 -0
  17. package/dist/{configuration-sync-Bvd956GL.d.ts → configuration-sync-BexM2qbg.d.ts} +17 -18
  18. package/dist/content-YNL2CRJZ.js +1 -0
  19. package/dist/{customer-page-B4LkIr5q.d.ts → customer-page-WUQVK_tp.d.ts} +276 -3
  20. package/dist/{funnel-runtime-start-ChVYbLzV.d.ts → funnel-local-client-D1Fe7CZ6.d.ts} +2507 -8137
  21. package/dist/funnel-runtime-host-CAMI6BJS.js +1 -0
  22. package/dist/index.d.ts +13578 -13442
  23. package/dist/index.js +1 -1
  24. package/dist/native-shell.js +1 -1
  25. package/dist/openrouter.d.ts +5 -3
  26. package/dist/openrouter.js +1 -1
  27. package/dist/page.d.ts +4 -4
  28. package/dist/page.js +1 -1
  29. package/dist/paywall-MXRMMF3R.js +1 -0
  30. package/dist/popup.d.ts +3 -271
  31. package/dist/popup.js +1 -350
  32. package/dist/react-native.d.ts +7 -7
  33. package/dist/react-native.js +1 -1
  34. package/dist/{screen-iFngkxaL.d.ts → screen-i6eHL11m.d.ts} +120 -117
  35. package/dist/screen-renderer-P7MLBHY5.js +1 -0
  36. package/dist/server.d.ts +4645 -8
  37. package/dist/server.js +1 -1
  38. package/dist/src-G7UQB3QE.js +1 -0
  39. package/dist/visual.d.ts +5 -2
  40. package/dist/visual.js +2 -2
  41. package/package.json +3 -9
  42. package/dist/chunk-3SONNXFG.js +0 -1
  43. package/dist/chunk-467Z5ISI.js +0 -11
  44. package/dist/chunk-4K25DELJ.js +0 -1
  45. package/dist/chunk-HD74AAFS.js +0 -1
  46. package/dist/chunk-J4RHVU3W.js +0 -1
  47. package/dist/chunk-NOFNOHUI.js +0 -1
  48. package/dist/chunk-QO4YQLZ4.js +0 -1
  49. package/dist/chunk-U6S6AZM6.js +0 -1
  50. package/dist/chunk-WCFVNF5D.js +0 -1
  51. package/dist/client-F6UPJMHR.js +0 -1
  52. package/dist/controls-XG46TKUU.js +0 -2
  53. package/dist/funnel-runtime-host-26QI2W3S.js +0 -1
  54. package/dist/iam.d.ts +0 -131
  55. package/dist/iam.js +0 -1
  56. package/dist/paywall-WKOHBYW7.js +0 -1
  57. package/dist/src-UHLPVD6E.js +0 -1
  58. /package/dist/{chunk-6X42DWOM.js → chunk-DSPLGTQI.js} +0 -0
  59. /package/dist/{chunk-S5TVMQRC.js → chunk-EXCPE2XH.js} +0 -0
@@ -0,0 +1 @@
1
+ import{a as ue}from"./chunk-RRII2DMC.js";import{z as A}from"zod";var te=A.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Sr=A.enum([...te.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),xr=A.enum([...te.options,"stale_revision"]),ot=A.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),at=A.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Ee={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function _r(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}var Ie={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function st(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Ie,e)){let i=Ie[e];return{retryable:i==="retry_same_request",recovery:i}}let n=te.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Ee[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Ir(e,t){let n=te.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Ee[n.data].status===t;let i={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(i,e)&&(i[e]?.includes(t)??!1)}function ct(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let a=Number(n);return Number.isSafeInteger(a)?a:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let i=Date.parse(n);return Number.isFinite(i)?Math.max(0,Math.ceil((i-t)/1e3)):void 0}var Ae=A.object({retryable:A.boolean(),recovery:ot,reason:at.optional(),retryAfterSeconds:A.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),lt=A.object({requestId:A.uuid().optional(),error:A.object({code:A.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:A.string(),...Ae.partial().shape})}),Er=A.object({error:lt.shape.error.extend({requestId:A.uuid().optional()})}),Ar=A.object({error:A.string(),code:A.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:A.uuid(),...Ae.shape});function Nr(e,t,n={}){let i=st(e,t),a=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??i.recovery,c=i.retryable&&n.retryable!==!1&&a!=="recover_operation",l=c?ct(n.retryAfter??null):void 0;return{...i,retryable:c,recovery:a,...l===void 0?{}:{retryAfterSeconds:l},...n.reason?{reason:n.reason}:{}}}import{z as ut}from"zod";var pt=["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"],O=ut.enum(pt);function pe(e){let t=O.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function kr(e,t){let n=pe(t),i=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!i?.[1]||(i[2]?.length??0)>n)throw new Error("Amount has invalid currency precision");let a=BigInt(i[1])*BigInt(10**n)+BigInt((i[2]??"").padEnd(n,"0")||"0");if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(a)}function Cr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=pe(t),i=String(e).padStart(n+1,"0");return n?`${i.slice(0,-n)}.${i.slice(-n)}`:i}function Lr(e,t,n="en",i={}){let a=O.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as _}from"zod";var re=_.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),E=_.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),mt=_.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}),me=E.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ne=_.string().min(1).max(64),V=_.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Re=_.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),L=_.record(Ne,_.union([_.string().max(120),_.number().finite(),_.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)]))),Oe=_.record(Ne,_.union([_.string().max(120),_.number().finite(),_.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),q=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,i=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let a=BigInt(n)*BigInt("1000000")+BigInt(i.padEnd(6,"0"));return t?-a:a},ke=_.array(_.object({upTo:me.nullable(),cost:E}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let i=e[n-1]?.upTo;return t.upTo!==null&&(n===0||i!=null&&q(t.upTo)>q(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),dt=_.object({key:Re,match:Oe,priority:_.number().int().default(0),cost:E.optional(),tiers:ke.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),ft=_.object({key:Re,match:Oe,factor:me.optional(),add:mt.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),gt=_.object({units:me.default("1"),cost:E,tiers:ke.optional(),dimensions:_.array(dt).max(12).optional(),multipliers:_.array(ft).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],i=e.multipliers??[];(new Set(n.map(l=>l.key)).size!==n.length||new Set(i.map(l=>l.key)).size!==i.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[l,d]of n.entries())for(let g of n.slice(l+1))Object.keys(d.match).length===Object.keys(g.match).length&&d.priority===g.priority&&!Object.keys(d.match).some(s=>g.match[s]!==void 0&&g.match[s]!==d.match[s])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let a=[e.cost,...(e.tiers??[]).map(l=>l.cost),...n.flatMap(l=>[...l.cost===void 0?[]:[l.cost],...(l.tiers??[]).map(d=>d.cost)])],c=q(e.units);for(let l of a)for(let d=0;d<1<<i.length;d++){let g=i.filter((v,R)=>d&1<<R);if(g.some((v,R)=>g.slice(R+1).some(_e=>Object.keys(v.match).some(le=>_e.match[le]!==void 0&&_e.match[le]!==v.match[le]))))continue;let s=q(l),p=BigInt("1"),b=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=q(R.factor??"1"),p*=BigInt("1000000"),b+=q(R.add??"0"));let h=(s+b*p)*BigInt("1000000"),w=p*c;(h<BigInt("0")||h%w!==BigInt("0")||h/w>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"})}}),Dr=gt.safeExtend({featureKey:V});import{z as bt}from"zod";var Le=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,M=bt.string().max(16).regex(Le,"\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 de(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:i,region:a}=new Intl.Locale(t),c=[n,i,a].filter(Boolean).join("-");return Le.test(c)?c:null}catch{return null}}var yt=new Set(["TW","HK","MO"]);function Ce(e){let[t,n,i]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let a=n?.length===4?n:void 0,c=n?.length===4?i:n;return a?`zh-${a}`:c&&yt.has(c)?"zh-Hant":"zh-Hans"}function Te(e,t,n){let i=t.map(a=>({code:M.parse(a),normalized:a}));for(let a of e){let c=de(a);if(!c)continue;let l=i.find(p=>p.normalized===c);if(l)return l.code;let d=Ce(c),g=i.filter(p=>Ce(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return n}var ht=[{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 wr(e){return ht.find(t=>t.code===e)?.label??e}import{z as u}from"zod";var $=E.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),H=u.string().min(1).max(120),ne=u.enum(["cap","overflow"]),k=(e,t)=>{let[n,i=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(i.padEnd(t,"0"))},K=e=>{try{return e()}catch{return!1}},$r=u.discriminatedUnion("operation",[u.object({operation:u.literal("quote"),overageBehavior:ne.optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L}).strict(),u.object({operation:u.literal("consume"),overageBehavior:ne.optional(),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:E,properties:L,idempotencyKey:H}).strict(),u.object({operation:u.literal("reserve"),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L,idempotencyKey:H,expiresInSeconds:u.number().int().min(1).max(86400)}).strict(),u.object({operation:u.literal("confirm"),operationId:u.uuid(),quantity:$,properties:L.optional(),idempotencyKey:H}).strict(),u.object({operation:u.literal("refund"),operationId:u.uuid(),quantity:$,idempotencyKey:H}).strict(),u.object({operation:u.literal("release"),operationId:u.uuid(),idempotencyKey:H}).strict()]),St=u.object({internal_credit_feature_id:u.uuid().nullable(),internal_metered_feature_id:u.uuid(),dimension:u.string().min(1).max(64),counterKey:u.string().min(1).max(240),cycleStart:u.iso.datetime({offset:!0}),unitCost:E,units:$,amount:re,tier:u.number().int().min(1).max(12).nullable()}).strict(),Q=u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function je(e,t){let n=e.reduce((i,a)=>i+k(a.units,12),0n)-k(t,12);return e.some(i=>i.funding==="balance")?n>=-100n&&n<=100n:n===0n}var De=u.discriminatedUnion("funding",[u.strictObject({funding:u.literal("balance"),sourceId:u.uuid(),rolloverId:u.uuid().nullable(),units:Q.refine(e=>/[1-9]/.test(e)),amount:re}),u.strictObject({funding:u.literal("unbilled"),units:Q.refine(e=>/[1-9]/.test(e))}),u.object({funding:u.literal("prepaid"),sourceId:u.uuid(),units:$,amount:re,pricing:u.array(St).min(1).max(12)}).strict().refine(e=>K(()=>e.pricing.reduce((t,n)=>t+k(n.units,6),0n)===k(e.units,6)&&e.pricing.reduce((t,n)=>t+k(n.amount,12),0n)===k(e.amount,12)&&e.pricing.every(t=>k(t.unitCost,6)*k(t.units,6)===k(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),u.object({funding:u.literal("postpaid"),invoiceLineId:u.uuid().nullable(),units:$,authorizationId:u.uuid()}).strict()]),ie=u.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Br=u.object({allowed:u.boolean(),internal_feature_id:u.uuid(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),reason:ie.nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.allowed?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),qr=u.object({id:u.uuid(),internal_feature_id:u.uuid(),kind:u.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:u.uuid().nullable(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),accepted:u.boolean(),reason:u.enum([...ie.options,"expired"]).nullable(),createdAt:u.iso.datetime({offset:!0}),reservationStatus:u.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:u.iso.datetime({offset:!0}).nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.accepted?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(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 T}from"zod";var xt=T.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),_t=T.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ze=T.strictObject({internal_feature_id:T.uuid(),entityId:T.uuid().nullable()}),Gr=ze.extend({quantity:E,expectedRevision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:T.string().min(1).max(120),properties:L.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Pe=ze.extend({operationId:T.uuid().nullable(),usage:E,capacity:xt.nullable(),remaining:_t.nullable(),withinLimit:T.boolean(),revision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:T.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=i=>{let a=i.startsWith("-"),[c,l=""]=(a?i.slice(1):i).split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(c)*10n**12n+BigInt(l.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"})});import{z as o}from"zod";var P=o.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),j=o.iso.datetime({offset:!0}),It=o.enum(["access","metered","credit"]),W={internal_feature_id:o.uuid(),key:V,name:o.string().min(1).max(120),kind:It},Jr=o.object({customerId:o.uuid(),snapshotAt:j,memberships:o.array(o.object({id:o.uuid(),productId:o.string().min(1).max(255),productVersionId:o.uuid(),billingProductVersionId:o.uuid(),version:o.number().int().positive(),key:o.string().min(1).max(64),name:o.string().min(1).max(120),groupId:o.string().max(255).nullable(),membershipType:o.enum(["main","addon"]),status:o.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:o.boolean(),accessEnabled:o.boolean(),renewalChange:o.object({productVersionId:o.uuid(),name:o.string().min(1).max(120),version:o.number().int().positive(),effectiveAt:j,benefitsAppliedAt:j.nullable(),timing:o.enum(["immediate","renewal"]),changeKind:o.enum(["plan","seats","quantity"]),feature:o.strictObject({internal_feature_id:o.uuid(),name:o.string().min(1).max(80),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).optional(),seat:o.object({key:o.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).strict().nullable(),status:o.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:o.object({phase:o.enum(["paid","trial"]),startsAt:j,endsAt:j.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:o.boolean(),balances:o.array(o.object({...W,usageType:o.enum(["consumable","non_consumable"]).nullable(),accessible:o.boolean(),unlimited:o.boolean(),available:P,held:P,debt:P,nextExpiresAt:j.nullable(),usage:Pe.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:o.boolean()}).strict(),we=o.enum(["source","usage","transaction","invoice","debt","settlement"]),oe=o.object({at:j,id:o.uuid(),type:we}).strict(),en=o.object({type:we.nullable(),resourceKey:V.optional(),kind:o.enum(["purchase","refund"]).optional(),topup:o.boolean().optional(),from:o.iso.date().nullable(),to:o.iso.date().nullable(),after:oe.nullable(),limit:o.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),F={id:o.uuid(),occurredAt:j},Et=o.discriminatedUnion("type",[o.strictObject({...F,type:o.literal("invoice"),status:o.string().min(1).max(80),paid:P,refunded:P,currency:O,externalId:o.string().nullable()}),o.object({...F,...W,type:o.literal("source"),reason:o.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:P,unlimited:o.boolean(),status:o.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:j,expiresAt:j.nullable(),orderId:o.uuid().nullable(),parentSourceId:o.uuid().nullable()}).strict(),o.object({...F,type:o.literal("usage"),internal_feature_id:o.uuid(),name:o.string().min(1).max(120),kind:o.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:o.uuid().nullable(),quantity:E,accepted:o.boolean(),reason:o.enum([...ie.options,"expired"]).nullable(),properties:L,reservationStatus:o.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:j.nullable(),charges:o.array(o.discriminatedUnion("funding",[o.strictObject({funding:o.literal("balance"),sourceId:o.uuid(),rolloverId:o.uuid().nullable(),units:Q,amount:P}),o.strictObject({funding:o.literal("unbilled"),units:Q}),o.object({...W,funding:o.literal("prepaid"),amount:P}).strict(),o.object({funding:o.literal("postpaid"),invoiceId:o.uuid(),invoiceLineId:o.uuid(),authorizationId:o.uuid(),units:E,currency:O}).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"),o.object({...F,type:o.literal("transaction"),purpose:o.enum(["product","invoice"]),productVersionId:o.uuid().nullable(),productName:o.string().min(1).max(120).nullable(),productVersion:o.number().int().positive().nullable(),invoiceId:o.uuid().nullable(),orderId:o.uuid(),originalId:o.uuid().nullable(),kind:o.enum(["purchase","refund"]),amountMinor:o.number().int().nonnegative().max(2e8).nullable(),currency:O.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"),o.object({...F,...W,type:o.literal("debt"),sourceId:o.uuid(),transactionId:o.uuid(),amount:P}).strict(),o.object({...F,...W,type:o.literal("settlement"),sourceId:o.uuid(),debtId:o.uuid(),kind:o.enum(["payment","usage_refund","payment_return"]),amount:P}).strict()]),tn=o.object({customerId:o.uuid(),rows:o.array(Et).max(50),nextCursor:oe.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 Z}from"zod";var ve=Z.enum(["stripe","apple","google"]),on=Z.enum(["membership","credit_pack","lifetime"]),an=Z.enum(["active","grace","suspended","inactive","revoked"]),sn=Z.strictObject({currency:Z.string().regex(/^[A-Z]{3}$/),micros:Z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as At}from"zod";var Ue=At.object({provider:ve,currency:O}).strict();import{z as x}from"zod";var Ve=x.strictObject({internal_feature_id:x.uuid(),quantity:E.refine(e=>/[1-9]/.test(e)),properties:L,entityId:x.uuid().optional()}),yn=x.strictObject({requirement:Ve,commerce:Ue.optional(),paywallId:x.uuid().optional()}),Nt=x.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Rt=x.strictObject({productId:x.string().min(1),productVersionId:x.string().min(1),name:x.string().min(1).max(120),action:x.enum(["purchase","upgrade","addon","topup"]),membershipId:x.string().min(1).nullable(),currency:O,amountMinor:x.string().regex(/^(0|[1-9]\d{0,8})$/),interval:x.enum(["free","week","month","year","one_time"]),intervalCount:x.number().int().min(1).max(156)}),$e=x.strictObject({internal_feature_id:x.string().min(1),name:x.string().min(1).max(120),kind:x.enum(["access","metered","credit"]),quantity:E,allowed:x.boolean(),reason:Nt.nullable(),preview:x.strictObject({scenario:x.enum(["feature_flag","usage_limit"]),candidates:x.array(Rt).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),hn=x.strictObject({paywallId:x.uuid(),requirement:Ve});import{z as f}from"zod";var Ot=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],fe=f.object({plan:f.string().min(1).max(200).optional(),coupon:f.uuid().optional(),promotionCode:f.uuid().optional(),picker:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Be=f.object({text:f.string().optional(),label:f.string().optional(),alt:f.string().optional(),html:f.string().max(32768).optional(),price:f.object({current:f.string(),original:f.string().nullable(),period:f.string()}).optional(),code:f.string().optional(),countdownAt:f.iso.datetime().optional(),planId:f.string().min(1).max(200).optional(),planVersionId:f.string().min(1).max(200).optional(),currency:O.optional(),couponId:f.uuid().optional(),offerId:f.uuid().optional(),unavailable:f.boolean().optional(),unavailableReason:f.string().optional(),missing:f.array(f.string()).optional()}).strict(),En=f.object({paywall:$e.optional(),nodes:f.record(f.string(),f.object({base:Be,picker:f.string().optional(),byPlan:f.record(f.string(),Be).optional()}).strict()),plans:f.record(f.string(),f.object({id:f.string().min(1).max(200),versionId:f.string().min(1).max(200),available:f.boolean(),name:f.string(),price:f.string(),period:f.string(),currency:O.optional()}).strict()),pickers:f.record(f.string(),f.object({options:f.array(f.string().min(1).max(200)).max(20),selected:f.string().min(1).max(200).nullable()}).strict()),diagnostics:f.array(f.object({nodeId:f.string(),message:f.string()}).strict())}).strict();function ae(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function se(e){let t=ae(e).filter(i=>!Ot.includes(i)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(i)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function An(e,t,n,i=!1){let a=ae(e).filter(c=>!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(c)&&t[c]===void 0);return a.length&&!i?{value:n,missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(c,l)=>t[l.trim()]??c),missing:a}}function Nn(e,t,n={}){let i=e?.nodes[t];if(!i)return;let a=i.picker?n[i.picker]??e?.pickers[i.picker]?.selected:void 0;return typeof a=="string"?i.byPlan?.[a]??i.base:i.base}function qe(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function ce(e){let t={};function n(i){if(qe(i)){let a=t[i.interaction.pickerId]??={ids:[],defaultId:null};for(let l of i.children){let d=l.type==="stack"?l.bind?.plan:void 0;d&&!a.ids.includes(d)&&a.ids.push(d)}let c=i.children[i.interaction.defaultIndex];!a.defaultId&&c?.type==="stack"&&(a.defaultId=c.bind?.plan??null)}i.type==="stack"&&i.children.forEach(n)}return e.pages.forEach(i=>n(i.root)),t}function Me(e,t,n){let i={};function a(g){if(g.hidden)return;if(g.type==="plan_picker"){let b=n.pickers[g.id];i[g.id]={ids:b?.options??[],defaults:b?.selected?[b.selected]:[],remembered:[]};return}if(g.type!=="stack")return;let s=g.children.filter(b=>!b.hidden),p=g.interaction;if(qe(g)){let b=i[g.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},h=n.pickers[g.interaction.pickerId]?.options??[];for(let v of s){let R=v.type==="stack"?v.bind?.plan:void 0;R&&h.includes(R)&&!b.ids.includes(R)&&b.ids.push(R),R&&v.id===t[g.id]&&b.remembered.push(R)}let w=g.children[g.interaction.defaultIndex];w?.type==="stack"&&!w.hidden&&w.bind?.plan&&b.defaults.push(w.bind.plan)}if(p?.type==="tabs"){let b=s.find(h=>h.id===t[g.id])??g.children[p.defaultIndex];b&&a(b)}else if(p?.type==="toggle"){let b=typeof t[g.id]=="boolean"?t[g.id]:p.defaultEnabled,h=g.children[b?0:1];h&&a(h)}else s.forEach(a)}let c=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,l=e.pages.find(g=>g.id===c);l&&a(l.root);let d={};for(let[g,s]of Object.entries(i)){let p=t[g],b=s.remembered[0]??(s.ids.includes(n.pickers[g]?.selected??"")?n.pickers[g]?.selected:s.defaults[0]);d[g]=typeof p=="string"?s.ids.includes(p)?p:"":b&&s.ids.includes(b)?b:""}for(let g of Object.keys(ce(e)))d[g]??="";return d}import{z as U}from"zod";var Fe=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ze=U.strictObject({tiers:U.array(U.strictObject({id:Fe,name:U.string().trim().min(1).max(80)})).min(1).max(8),assignments:U.array(U.strictObject({productVersionId:U.string().min(1).max(200),tierId:Fe,period:U.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(i=>i.id);(new Set(n).size!==n.length||new Set(e.assignments.map(i=>i.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(i=>`${i.tierId}:${i.period}`)).size!==e.assignments.length||e.assignments.some(i=>!n.includes(i.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Ge(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as m}from"zod";var kt=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],He=m.enum(kt),Ke=m.object({source:He,layout:m.enum(["full","compact"]),resourceKey:V.optional(),pageSize:m.number().int().min(1).max(50),showSources:m.boolean(),allowPurchase:m.boolean(),outputs:m.object({billing_adjustment:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:m.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"})}),N=m.string().max(2e3),Qe=m.object({id:m.string().max(100),label:N,detail:m.array(N).max(12),value:N.optional(),status:N.optional(),facts:m.array(m.object({label:N,value:N}).strict()).max(1e3),purchaseId:m.uuid().optional(),invoiceUrl:m.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:m.array(m.strictObject({action:m.literal("invoice_open"),label:N})).max(1).optional(),membershipActions:m.array(m.object({value:m.string().max(100),label:N}).strict()).max(3).optional()}).strict(),Ct=m.object({key:V,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:m.array(Qe).max(50),sourceCount:m.number().int().nonnegative(),sourcePage:m.number().int().positive(),hasNextSources:m.boolean(),hasPreviousSources:m.boolean()}).strict(),Lt=m.object({source:He,status:m.enum(["idle","loading","ready","error"]),stale:m.boolean(),preview:m.boolean(),errorCode:m.string().max(80).optional(),errorMessage:N.optional(),resources:m.array(Ct).max(500),rows:m.array(Qe).max(50),hasNext:m.boolean(),hasPrevious:m.boolean(),page:m.number().int().positive(),filter:m.string().max(40),updatedAt:m.iso.datetime().optional(),buyingId:m.uuid().optional(),membershipBusy:m.boolean().optional(),billingBusy:m.boolean().optional(),membershipReview:m.object({title:N,note:N,facts:m.array(m.object({label:N,value:N}).strict()).max(100)}).strict().optional(),membershipResult:N.optional()}).strict(),jn=m.object({nodes:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Lt)}).strict(),Dn=m.object({nodeId:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:m.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:m.string().max(100).optional()}).strict();function zn(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function ge(e){let t=se(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 i=n;if(e.startsWith("<!--",n)){let a=e.indexOf("-->",n+4);n=a<0?e.length:a+2}else{let a="";for(n++;n<e.length;n++){let c=e[n];if(a)c===a&&(a="");else if(c==='"'||c==="'")a=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(i,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 We(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function vn(e,t,n,i=!1){let a=ge(e);if(a.length)throw new Error(a[0]);let c=[...new Set(ae(e).filter(l=>!l.startsWith("variables.")&&t[l]===void 0))];return c.length&&!i?{value:We(n),missing:c}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(l,d)=>t[d.trim()]===void 0?l:We(t[d.trim()])),missing:c}}import{z as r}from"zod";var Tt=4,z={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},X=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),S=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),jt=r.enum(["none","xs","sm","md","lg","xl"]),Dt=r.enum(["none","sm","md","lg","full"]),be=r.string().regex(/^#[0-9a-fA-F]{6}$/),Je=r.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"),ye=r.union([Je,r.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),r.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),r.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ye=r.object({primary:be,background:be,text:be,radius:Dt,font:r.enum(["system","serif","rounded","mono"])}).strict(),J=r.union([r.enum(["primary","text","muted","background","surface"]),r.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),y=(e,t)=>r.number().int().min(e).max(t),Xe=r.union([r.enum(["fit","fill"]),y(1,1200)]),zt=r.object({top:y(0,200),right:y(0,200),bottom:y(0,200),left:y(0,200)}).strict(),Pt=r.object({top:y(-100,200),right:y(-100,200),bottom:y(-100,200),left:y(-100,200)}).strict(),et=r.object({x:y(0,100),y:y(0,100)}).strict(),wt=r.discriminatedUnion("type",[r.object({type:r.literal("color"),color:J}).strict(),r.object({type:r.literal("linear"),angle:y(0,360),stops:r.array(r.object({color:J,at:y(0,100)}).strict()).min(2).max(4)}).strict(),r.object({type:r.literal("image"),src:ye,fit:r.enum(["cover","contain"]),position:et.optional()}).strict()]),vt=r.discriminatedUnion("type",[r.object({type:r.literal("rect"),radius:r.union([y(0,200),r.object({topLeft:y(0,200),topRight:y(0,200),bottomRight:y(0,200),bottomLeft:y(0,200)}).strict()])}).strict(),r.object({type:r.literal("pill")}).strict()]),Ut=r.object({width:y(0,12),color:J,style:r.enum(["solid","dashed"])}).strict(),Vt=r.object({x:y(-40,40),y:y(-40,40),blur:y(0,80),spread:y(-20,40),color:J}).strict(),$t=r.object({font:r.enum(["system","serif","rounded","mono"]),size:y(8,96),weight:r.number().int().min(100).max(900).multipleOf(100),lineHeight:r.number().min(.8).max(3),letterSpacing:r.number().min(-5).max(20),color:J,align:r.enum(["start","center","end"]),italic:r.boolean(),decoration:r.enum(["none","underline","line-through"]),transform:r.enum(["none","uppercase"])}).strict().partial(),B=r.object({width:Xe,height:Xe,padding:zt,margin:Pt,gap:y(0,120),grow:r.union([r.boolean(),r.number().min(0).max(12)]),background:wt,opacity:r.number().min(0).max(1),clipContent:r.boolean(),shape:vt,border:Ut,shadow:Vt,text:$t}).strict().partial(),C={id:X,name:r.string().trim().min(1).max(60).optional(),hidden:r.boolean().optional(),style:B.optional(),fallback:S.optional()},Bt=r.object({...C,type:r.literal("text"),productField:r.enum(["name","price","trial","period"]).optional(),feature:r.object({id:r.uuid(),field:r.enum(["name","allowance"])}).strict().optional(),text:S,variant:r.enum(["title","heading","body","caption"])}).strict(),qt=r.object({...C,type:r.literal("image"),src:ye,localizedSrc:r.record(M,ye).optional(),alt:S,aspect:r.enum(["auto","1:1","4:3","16:9","3:1"]),fit:r.enum(["cover","contain"]),position:et.optional()}).strict(),Mt=r.object({...C,type:r.literal("button"),label:S,variant:r.enum(["primary","secondary","link"]),action:S,purpose:r.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Ft=r.object({...C,type:r.literal("divider")}).strict(),Zt=r.object({...C,type:r.literal("customer_data"),title:S,data:Ke}).strict(),Gt=r.object({...C,type:r.literal("spacer"),size:jt}).strict(),Ht=r.object({...C,type:r.literal("custom_html"),html:r.record(M,r.string().max(z.customHtml)),css:r.string().max(z.customCss)}).strict(),Kt=r.object({...C,type:r.literal("price"),fallback:S,parts:r.object({current:B.optional(),original:B.optional(),period:B.optional()}).strict().optional()}).strict(),Qt=r.object({...C,type:r.literal("coupon_code"),label:S,fallback:S}).strict(),Wt=r.object({...C,type:r.literal("countdown"),source:r.enum(["offer.ends_at","offer.expires_at","fixed"]),at:r.iso.datetime().optional(),granularity:r.enum(["day","hour","minute","second"]),expired:S,fallback:S}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Yt=r.object({...C,type:r.literal("plan_picker"),label:S,fallback:S,planIds:r.array(r.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:r.string().min(1).max(200).optional(),grouping:Ze.safeExtend({monthLabel:S,yearLabel:S,unavailableLabel:S}).optional(),states:r.object({selected:B.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ge(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Xt=r.discriminatedUnion("type",[r.object({type:r.literal("input"),label:S,keyboard:r.enum(["text","email","tel","url"]),maxLength:y(1,500)}).strict(),r.object({type:r.literal("multiselect"),label:S,min:y(0,50),max:y(1,50)}).strict(),r.object({type:r.literal("select"),label:S,defaultIndex:y(0,49),purpose:r.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:B.optional()}).strict(),r.object({type:r.literal("tabs"),label:S,defaultIndex:y(0,49),purpose:r.literal("tier").optional()}).strict(),r.object({type:r.literal("toggle"),label:S,defaultEnabled:r.boolean()}).strict(),r.object({type:r.literal("carousel"),label:S}).strict()]),D={...C,type:r.literal("stack"),direction:r.enum(["vertical","horizontal","overlay"]),align:r.enum(["start","center","end","stretch"]),justify:r.enum(["start","center","end","between"]),productSlot:r.object({index:y(0,19),period:r.enum(["month","year"]).optional(),requireBinding:r.boolean().optional()}).strict().optional(),interaction:Xt.optional(),states:r.object({selected:B.optional()}).strict().optional(),purpose:r.literal("benefits").optional(),purchaseAction:S.optional(),buttonVariant:r.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},tt=r.lazy(()=>r.object({...C,type:D.type,direction:D.direction,align:D.align,justify:D.justify,children:r.array(Jt).max(z.children),productSlot:D.productSlot,interaction:D.interaction,states:D.states,purpose:D.purpose,purchaseAction:D.purchaseAction,buttonVariant:D.buttonVariant,bind:D.bind}).strict()),Jt=r.lazy(()=>r.union([tt,Bt,qt,Mt,Ft,Gt,Ht,Kt,Qt,Wt,Yt,Zt])),er=r.union([r.string().max(500),r.number().finite(),r.boolean(),r.null()]),Y={id:S,event:S,properties:r.record(S,er).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},tr=r.discriminatedUnion("type",[r.object({...Y,type:r.literal("navigate"),close:r.literal(!1),pageId:X}).strict(),r.object({...Y,type:r.literal("event"),close:r.boolean()}).strict(),r.object({...Y,type:r.literal("close"),close:r.literal(!0)}).strict(),r.object({...Y,type:r.literal("open_url"),close:r.boolean(),url:Je}).strict(),r.object({...Y,type:r.literal("claim_offer"),close:r.boolean(),couponId:r.uuid()}).strict()]),rr=r.object({defaultLocale:M,locales:r.record(M,r.record(S,r.string().max(z.stringLength)))}).strict(),nr=r.enum(["popup","paywall","onboarding","page","banner"]),Gn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages",banner:"/workspace/banners"},ir=r.discriminatedUnion("type",[r.object({type:r.literal("modal"),size:r.enum(["sm","md","lg"])}).strict(),r.object({type:r.literal("sheet"),size:r.enum(["sm","md","lg"])}).strict(),r.object({type:r.literal("fullscreen")}).strict(),r.object({type:r.literal("inline")}).strict()]),Hn={sm:360,md:420,lg:560},or=r.object({kind:r.literal("screen"),schemaVersion:r.literal(Tt),name:r.string().trim().min(1).max(80),surface:nr,initialPageId:X.optional(),presentation:ir,theme:Ye,pages:r.array(r.object({id:X,name:r.string().trim().min(1).max(60),root:tt,theme:Ye.optional(),editorPosition:r.object({x:r.number().finite().min(-1e5).max(1e5),y:r.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:rr,actions:r.array(tr).max(z.actions)}).strict();function G(e,t){for(let n of e.pages)ee(n.root,t)}function Kn(e,t){return{...e,pages:e.pages.map((n,i)=>i===0?{...n,root:t}:n)}}var ar=or.superRefine((e,t)=>{let n=z;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(p=>p.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let p of e.actions)p.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(b=>b.id===p.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let i=p=>t.addIssue({code:"custom",message:p}),a=Object.keys(e.strings.locales);a.includes(e.strings.defaultLocale)||i("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),a.length>z.locales&&i(`\u6700\u591A ${z.locales} \u79CD\u8BED\u8A00`);let c=new Set;for(let p of e.actions)c.has(p.id)&&i(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${p.id}`),c.add(p.id);let l=new Set;for(let p of e.pages)["next","back"].includes(p.id)&&i(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${p.id}`),l.has(p.id)&&i(`\u9875\u9762 id \u91CD\u590D\uFF1A${p.id}`),l.add(p.id);let d=new Set,g=0,s=!1;G(e,(p,b)=>{if(g++,b>z.depth&&(s=!0),d.has(p.id)&&i(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${p.id}`),d.add(p.id),p.type==="button"&&!c.has(p.action)&&i(`\u6309\u94AE ${p.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${p.action}`),p.type==="custom_html")for(let h of Object.keys(p.html))a.includes(h)||i(`\u81EA\u5B9A\u4E49 HTML ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`);if(p.type==="image")for(let h of Object.keys(p.localizedSrc??{}))a.includes(h)||i(`\u56FE\u7247 ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`)}),g>n.nodes&&i(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),s&&i(`\u5C42\u7EA7\u6700\u591A ${z.depth} \u5C42`)});function ee(e,t,n=1,i=null){if(t(e,n,i)!==!1&&e.type==="stack")for(let a of e.children)ee(a,t,n+1,e)}function Se(e){let t=[],n=new Set;return G(e,i=>{let a=(c,l,d)=>{n.has(c)||(n.add(c),t.push({key:c,nodeId:i.id,nodeType:i.type,field:l,required:d}))};i.type==="stack"&&i.interaction&&a(i.interaction.label,"label",!0),i.fallback&&a(i.fallback,"text",!0),i.type==="text"&&a(i.text,"text",!0),i.type==="customer_data"&&a(i.title,"title",!0),(i.type==="plan_picker"||i.type==="coupon_code")&&a(i.label,"label",!0),i.type==="plan_picker"&&i.grouping&&(a(i.grouping.monthLabel,"label",!0),a(i.grouping.yearLabel,"label",!0),a(i.grouping.unavailableLabel,"text",!0)),i.type==="countdown"&&a(i.expired,"text",!0),i.type==="button"&&a(i.label,"label",!0),i.type==="image"&&(a(`image:${i.id}`,"src",!1),a(i.alt,"alt",!1)),i.type==="custom_html"&&a(`html:${i.id}`,"html",!0)}),t}function sr(e,t,n){if(t.field==="html"){let i;return G(e,a=>{a.id===t.nodeId&&a.type==="custom_html"&&(i=a.html[n])}),i}if(t.field==="src"){let i=he(e,t.nodeId);return i?.type==="image"?i.localizedSrc?.[n]??(n===e.strings.defaultLocale?i.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function rt(e){let t=Se(e).filter(i=>i.required);return Object.keys(e.strings.locales).sort((i,a)=>i===e.strings.defaultLocale?-1:a===e.strings.defaultLocale?1:0).map(i=>{let a=t.filter(c=>!sr(e,c,i)?.trim()).map(c=>c.key);return{locale:i,total:t.length,filled:t.length-a.length,missing:a,complete:a.length===0}})}function Qn(e){return nt(e,!0)}function Wn(e){return nt(e,!1)}function nt(e,t){let n=[],i=t&&e.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"));i&&(!e.actions.some(s=>s.type==="claim_offer")||e.actions.some(s=>s.type==="event"&&typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-")))&&n.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 a(s,p){let b=s.type==="stack"||s.type==="button"?s.bind?.coupon??p:p;if(i&&s.type==="text"&&Object.values(e.strings.locales).some(h=>h[s.text]?.includes("{{offer."))&&!b&&n.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"),s.type==="button"){let h=e.actions.find(w=>w.id===s.action);h?.type==="claim_offer"&&b&&b!==h.couponId&&n.push(`\u9886\u53D6\u6309\u94AE ${s.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}s.type==="stack"&&s.children.forEach(h=>a(h,b))}e.pages.forEach(s=>a(s.root));let c=[],l=ar.safeParse(e);l.success||n.push(...l.error.issues.map(s=>s.message));for(let s of Object.values(e.strings.locales))for(let p of Object.values(s))for(let b of se(p))n.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${b}`);G(e,s=>{if(s.type==="customer_data"&&Object.values(e.strings.locales).some(b=>/\{\{|\}\}/.test(b[s.title]??""))&&n.push(`\u6570\u636E\u7EC4\u4EF6 ${s.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(s.type==="text"?[s.text]:s.type==="button"?[s.label]:[]).some(b=>Object.values(e.strings.locales).some(h=>h[b]?.includes("{{")))&&!s.fallback&&n.push(`\u7EC4\u4EF6 ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),s.fallback&&Object.values(e.strings.locales).some(b=>b[s.fallback]?.includes("{{"))&&n.push(`\u7EC4\u4EF6 ${s.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),s.type==="custom_html"){for(let b of Object.values(s.html))n.push(...ge(b).map(h=>`HTML ${s.id}\uFF1A${h}`));Object.values(s.html).some(b=>b.includes("{{"))&&!s.fallback&&n.push(`HTML ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(s.css)&&n.push(`HTML ${s.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(s.type==="stack"||s.type==="button")&&s.bind?.picker&&he(e,s.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(ce(e),s.bind.picker)&&n.push(`\u5BB9\u5668 ${s.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let s of Object.keys(ce(e)))he(e,s)||n.push(`Product selection scope ${s} must reference a UI node`);let d=rt(e);for(let s of d)s.complete||(s.locale===e.strings.defaultLocale?n.push(`\u9ED8\u8BA4\u8BED\u8A00 ${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):n.push(`${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));Se(e).length===0&&!e.pages.some(s=>cr(s.root))&&n.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let g=new Set;G(e,s=>{s.type==="button"&&g.add(s.action)});for(let s of e.actions)!g.has(s.id)&&!e.pages.some(p=>lr(p.root,s.id))&&c.push(`\u52A8\u4F5C ${s.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:n,warnings:c}}function cr(e){let t=!1;return ee(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function lr(e,t){let n=!1;return ee(e,i=>{if(i.type==="custom_html")for(let a of Object.values(i.html))a.includes(`data-grow-action="${t}"`)&&(n=!0)}),n}function ur(e){return rt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Yn(e,t){return Te(t,ur(e),e.strings.defaultLocale)}function Xn(e,t){let n=e.strings.locales[t]??{},i=e.strings.locales[e.strings.defaultLocale]??{},a={};for(let l of Se(e)){if(l.field==="html"||l.field==="src")continue;let d=n[l.key]?.trim()?n[l.key]:i[l.key];d!==void 0&&(a[l.key]=d)}let c=l=>{if(l.type==="stack")return{...l,children:l.children.map(c)};if(l.type==="custom_html"){let d=l.html[t]?.trim()?l.html[t]:l.html[e.strings.defaultLocale];return{...l,html:d===void 0?{}:{[t]:d}}}if(l.type==="image"){let{localizedSrc:d,...g}=l;return{...g,src:d?.[t]??d?.[e.strings.defaultLocale]??l.src}}return l};return{...e,pages:e.pages.map(l=>({...l,root:c(l.root)})),strings:{defaultLocale:t,locales:{[t]:a}}}}function pr(e,t){let n=null;return ee(e,i=>{if(n)return!1;i.id===t&&(n=i)}),n}function he(e,t){for(let n of e.pages){let i=pr(n.root,t);if(i)return i}return null}function Jn(e){let t=de(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function ei(e,t,n){let i={};if(!t||typeof t!="object"||Array.isArray(t))return i;let a=t;if(G(e,c=>{if(c.type==="plan_picker"){let d=a[c.id];typeof d=="string"&&(i[c.id]=n?.pickers[c.id]?.options.includes(d)?d:"");return}if(c.type!=="stack"||!c.interaction)return;let l=Object.hasOwn(a,c.id)?a[c.id]:void 0;["select","tabs"].includes(c.interaction.type)&&typeof l=="string"&&c.children.some(d=>d.id===l)&&(i[c.id]=l),c.interaction.type==="toggle"&&typeof l=="boolean"&&(i[c.id]=l)}),e.surface==="paywall"&&typeof a.__page=="string"&&e.pages.some(c=>c.id===a.__page)&&(i.__page=a.__page),n){let c={...i};for(let[l,d]of Object.entries(a))(typeof d=="string"||typeof d=="boolean")&&(c[l]=d);Object.assign(i,Me(e,c,n))}return i}import{z as I}from"zod";var oi=I.discriminatedUnion("kind",[I.object({kind:I.literal("ledger"),cursor:oe}).strict(),I.object({kind:I.literal("billing"),cursor:I.uuid()}).strict()]),mr=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),dr=I.record(I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),I.union([I.string().max(500),I.boolean(),I.array(I.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),fr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function xe(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>xe(n,t+1)):Object.entries(e).some(([n,i])=>["__proto__","constructor","prototype"].includes(n)||fr.test(n)||xe(i,t+1)))}var gr=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,br=I.record(mr,ue).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!xe(e)&&!gr.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function ai(e){let t=Object.create(null);for(let[n,i]of new URL(e).searchParams)I.string().max(500).parse(i),Object.hasOwn(t,n)||(t[n]=i);return br.parse(t),t}var it=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yr=I.array(I.object({variable:it,componentId:it,required:I.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),si=I.object({bindings:yr,answers:dr,values:I.record(I.string(),ue).optional()}).strict();export{te as a,Sr as b,xr as c,ot as d,at as e,Ee as f,_r as g,Ie as h,st as i,Ir as j,ct as k,Ae as l,lt as m,Er as n,Ar as o,Nr as p,pt as q,O as r,pe as s,kr as t,Cr as u,Lr as v,re as w,E as x,mt as y,V as z,L as A,ke as B,dt as C,ft as D,gt as E,Dr as F,M as G,de as H,Te as I,ht as J,wr as K,ne as L,$r as M,St as N,Q as O,De as P,ie as Q,Br as R,qr as S,ze as T,Gr as U,Pe as V,P as W,Jr as X,we as Y,oe as Z,en as _,Et as $,tn as aa,ve as ba,on as ca,an as da,sn as ea,Ue as fa,Ve as ga,yn as ha,Nt as ia,Rt as ja,$e as ka,hn as la,Ot as ma,fe as na,Be as oa,En as pa,ae as qa,se as ra,An as sa,Nn as ta,qe as ua,ce as va,Me as wa,Ze as xa,Ge as ya,kt as za,He as Aa,Ke as Ba,Lt as Ca,jn as Da,Dn as Ea,zn as Fa,ge as Ga,We as Ha,vn as Ia,Tt as Ja,z as Ka,X as La,S as Ma,jt as Na,Dt as Oa,ye as Pa,Ye as Qa,J as Ra,Xe as Sa,zt as Ta,Pt as Ua,et as Va,wt as Wa,vt as Xa,Ut as Ya,Vt as Za,$t as _a,B as $a,Bt as ab,qt as bb,Mt as cb,Ft as db,Zt as eb,Gt as fb,Ht as gb,Kt as hb,Qt as ib,Wt as jb,Yt as kb,Xt as lb,tt as mb,Jt as nb,tr as ob,rr as pb,nr as qb,Gn as rb,ir as sb,Hn as tb,G as ub,Kn as vb,ar as wb,ee as xb,Se as yb,sr as zb,rt as Ab,Qn as Bb,Wn as Cb,ur as Db,Yn as Eb,Xn as Fb,pr as Gb,he as Hb,Jn as Ib,ei as Jb,oi as Kb,dr as Lb,br as Mb,ai as Nb,yr as Ob,si as Pb};
@@ -0,0 +1 @@
1
+ import{a as rn,b as on,c as an,d as sn}from"./chunk-YWFNWK7C.js";import{a as ge}from"./chunk-KSNOXNTC.js";import{a as te}from"./chunk-AEUFCOFG.js";import{Bg as $e,Dg as Ke,Ej as en,Fj as nn,Hi as Ze,Hj as tn,Ii as We,Qd as Me,bg as z,ei as X,ge as ke,he as Ue,ke as qe,mg as Ge,mi as Qe,mj as Xe,og as U,pg as Je,tg as Pe,ti as pe,ug as x,vg as Be,wg as je,wi as Ye,xg as ze,yg as He}from"./chunk-F767CM3T.js";import{a as d}from"./chunk-6HG7U6AU.js";import{b as xe,h as me}from"./chunk-AE4CUTUE.js";import{a as ne}from"./chunk-EXCPE2XH.js";import{b as Se}from"./chunk-RRII2DMC.js";import{h as Le,l as Ve}from"./chunk-KQCTDXVD.js";function Tn(n){let e=null,t=null,f=0,u=0,m=new Set,o=null,a=null,r=new Set,s=()=>{for(let i of r)try{i()}catch{}},p={attributes:Se.parse(n.attributes??{}),onFeatureUsage:n.onFeatureUsage?(i,v)=>{!m.has(i)&&(!e||!("analyticsConfig"in e)||e.analyticsConfig.featureUsageEnabled)&&n.onFeatureUsage(i,structuredClone(v))}:void 0,onExperimentViewed:n.onExperimentViewed?(i,v)=>(!e||!("analyticsConfig"in e)||e.analyticsConfig.experimentViewsEnabled)&&n.onExperimentViewed(structuredClone(i),structuredClone(v)):void 0,stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:n.saveStickyBucketAssignmentDoc?i=>n.saveStickyBucketAssignmentDoc(structuredClone(i)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function F(i,v=new Set){return m.has(i)?!o||!o.features[i]||["unknownFeature","cyclicPrerequisite"].includes(o.features[i].source):v.has(i)?!1:(v.add(i),(e?.features[i]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(S=>S.experiment.parentConditions??[])].some(S=>F(S.id,v))))}let E=i=>{if(n.assertUsable?.(e?.generation),!e)throw new Error("Initialize the Feature client before evaluation");if(e.expiresAt&&Date.parse(e.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,p.features=e.features),m.has(i)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?w():structuredClone(o.features[i]??w()):F(i)?w():structuredClone(Ve(i,p))};async function O(){if(!e||!m.size)return;if(!n.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let i=u;if(a?.revision===i)return a.loading;let v=f,P=e,S=[...m],R=(async()=>{let N=qe.parse(await n.evaluateRemote({attributes:structuredClone(p.attributes),features:S}));if(!(v!==f||i!==u||P!==e)){if(n.assertUsable?.(P.generation),N.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(S.some(T=>!Object.hasOwn(N.features,T))||Object.keys(N.features).some(T=>!m.has(T)))throw new Error("Invalid remote Feature results");o=structuredClone(N),p.features={...P.features,...Object.fromEntries(Object.entries(o.features).map(([T,V])=>[T,{defaultValue:V.value}]))},s()}})();a={revision:i,loading:R};try{await R}finally{a?.loading===R&&(a=null)}}function l(){O().catch(i=>{try{n.onError?.(i)}catch{}})}async function y(){if(t)return t;let i=f,v=(async()=>{let P=await n.load(),S="remoteFeatures"in P?ke.parse(P):null,R=S??me.parse(P);if(R.scope.projectId!==n.scope.projectId||R.scope.environment!==n.scope.environment)throw new Error("Feature payload scope changed");if(i!==f)throw new Error("Feature client was reset");if(n.assertUsable&&e?.generation===R.generation){let{evaluatedAt:T,expiresAt:V,...J}=e,{evaluatedAt:B,expiresAt:Y,...q}=R;if(x(J)!==x(q))throw new Error("Immutable Feature generation changed content");return e.evaluatedAt=R.evaluatedAt,e.expiresAt=R.expiresAt,s(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&l(),structuredClone(e)}let N=new Set(S?.remoteFeatures??[]);if([...N].some(T=>Object.hasOwn(R.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return e&&"analyticsConfig"in e&&"analyticsConfig"in R&&!e.analyticsConfig.experimentViewsEnabled&&S?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),e=structuredClone(R),m=N,o=null,a=null,u++,p.features=e.features,p.savedGroups=Le(e.savedGroups),p.trackedFeatureUsage={},s(),l(),structuredClone(e)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:y,refresh:y,refreshRemote:O,get generation(){return e?.generation??null},get expiresAt(){return e?.expiresAt??null},subscribe(i){return r.add(i),()=>{r.delete(i)}},setAttributes(i){p.attributes=Se.parse(i),u++,o=null,a=null,p.features=e?.features??{},p.trackedFeatureUsage={},s(),l()},evalFeature:E,isOn(i){return E(i).on},isOff(i){return E(i).off},getFeatureValue(i,v){let P=E(i).value;return structuredClone(P===null?v:P)},reset(){f++,u++,t=null,a=null,e=null,o=null,m.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),s()}}}function un(n){let e,t,f=()=>new d("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(e=n.storage??globalThis.localStorage,t=n.locks??globalThis.navigator?.locks,!e||!t||!globalThis.crypto?.subtle)throw f();let a=new TextEncoder().encode(JSON.stringify([new URL(n.baseUrl??ne).href,n.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return"indiana.funnel.commands.v1."+Array.from(r,s=>s.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function m(a){try{let r=await u;return await t.request(r,{mode:"exclusive"},()=>a(r))}catch(r){throw r instanceof d?r:f()}}function o(a){let r=e.getItem(a);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw f();let s=JSON.parse(r);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw f();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>m(o),write:(a,r)=>m(s=>{if(o(s).revision!==a)return null;if(!Number.isSafeInteger(a+1))throw f();return e.setItem(s,JSON.stringify({revision:a+1,entry:r})),a+1})}}async function ye(n,e){let{funnelRuntimeDeliverySchema:t}=await import("./src-G7UQB3QE.js"),f=t.safeParse(e);if(!f.success)throw new d("INVALID_RESPONSE","Funnel response contract changed");let u=f.data;if(n.scope&&(u.scope.projectId!==n.scope.projectId||u.scope.environment!==n.scope.environment))throw new d("SCOPE_MISMATCH","Funnel scope changed");return u}async function be(n,e,t){if(Number(n.headers.get("content-length"))>e)throw t.error("limit");let f=n.body?.getReader();if(!f)throw t.error("missing");let u=[],m=0;try{for(;;){t.signal?.throwIfAborted();let r=await f.read();if(r.done)break;if(m+=r.value.length,m>e)throw t.error("limit");u.push(r.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let o=new Uint8Array(m),a=0;for(let r of u)o.set(r,a),a+=r.length;return o}async function ln(n,e,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await be(n,e,t))}function we(n,e){let t=typeof n=="string"?new TextEncoder().encode(n):n;return t.byteLength===e.byteLength&&Be(t)===e.sha256}async function he(n,e){let t=$e.parse(e),{artifact:f,environmentId:u}=t.content,m=new URL(n.baseUrl??ne).origin,o=new URL(f.url,m);if(o.origin!==m||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new d("INVALID_RESPONSE","Public Paywall locator is not trusted");let a=new AbortController,r=setTimeout(()=>a.abort(),U.initializationMs);try{let s=await(n.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:a.signal});if(!s.ok||!s.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(s.headers.get("content-length"))>f.byteLength)throw new d("INVALID_RESPONSE","Public Paywall is unavailable");let p=await be(s,f.byteLength,{signal:a.signal,error:w=>new d("INVALID_RESPONSE",w==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!we(p,f))throw new d("INVALID_RESPONSE","Public Paywall digest or size changed");return Ke(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p)))}finally{clearTimeout(r)}}var se=(n,e)=>new d(n,e);function $n(n){return en(n,se)}async function cn(n,e,{predict:t=!0}={}){let f=e.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!n)throw new d("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(n.scope.environmentId!==f.environmentId)throw new d("SCOPE_MISMATCH","Evaluation environment changed");let u=null,m;if(t)try{let o=await n.funnel(e.source.id,e.source.versionId);m=o.manifest.generation,u=Sn(n,e,o)}catch{u=null}return m??=n.snapshot?.generation??(await n.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:m},prediction:u}}function Sn(n,e,t){let f=e.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:m,...o}=t.growth,a=Ze({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:e.source.id,versionId:e.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:me.parse(o)}),r=Pn(a,t.document,{...e,...f}),s=r.steps.at(-1),p=r.boundary??(s?.result.port==="value"?{nodeId:s.nodeId,visit:e.visit+r.steps.length-1}:null);return p?{runId:e.id,from:{nodeId:e.nodeId,visit:e.visit,revision:e.revision},nodeId:p.nodeId,visit:p.visit,terminal:!r.boundary}:null}function Pn(n,e,t){return tn(n,e,t,se)}import{z as G}from"zod";var dn=z.refine(n=>!["start","get","review"].includes(n.operation)&&!("customerToken"in n),"Persist only the original mutation, without credentials").transform(n=>{if(n.operation==="start"||n.operation==="get"||n.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");return n}),fn=G.strictObject({schemaVersion:G.literal(1),scope:xe,runId:G.uuid(),funnelId:G.uuid(),versionId:G.uuid(),command:dn.optional(),closeCommand:dn.refine(n=>n.operation==="close").optional(),purchase:G.strictObject({receiptId:G.uuid(),operationId:G.uuid(),generation:G.number().int().nonnegative()}).optional(),closed:G.literal(!0).optional()}).refine(n=>!n.closeCommand||n.command&&n.command.operation!=="close"&&n.command.requestId!==n.closeCommand.requestId,"Close requires a separate request identity").refine(n=>n.command!==void 0||n.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new d("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ie=(n,e)=>JSON.stringify(n)===JSON.stringify(e);function mn(n){let e=0,t=null,f=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),u=Promise.resolve();async function m(){let r=await n.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new d("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:fn.parse(r.entry)}}function o(r){let s=u.then(r);return u=s.catch(()=>{}),s}async function a(r){for(let s=0;s<4;s++){let p=await m();if(p.entry&&t!==null&&f(p.entry)!==t)throw M();let w=r(p.entry,p.revision);if(Ie(p.entry,w)){e=p.revision;return}let F=await n.write(p.revision,w);if(F!==null){if(!Number.isSafeInteger(F)||F<=p.revision)throw M();e=F;return}}throw M()}return{bind(r){let s=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(t!==null&&t!==s)throw M();t=s},async load(){let r=await m();return e=r.revision,t=r.entry?f(r.entry):null,r.entry},retain(r){let s=fn.parse(r),p=s.command;return!p||t!==null&&f(s)!==t?Promise.reject(M()):(t??=f(s),o(()=>a((w,F)=>{if(w&&!Ie(f(w),f(s)))throw M();if(!w){if(F!==e&&p.operation!=="close")throw M();return s}if(!w.command)return{...w,command:p,...p.operation==="close"?{closed:!0}:{}};if(p.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===p.requestId||w.closeCommand&&!Ie(w.closeCommand,p))throw M();return{...w,closeCommand:p,closed:!0}}if(!Ie(w.command,p))throw M();return w})))},observePurchase(r,s,p){return o(()=>a((w,F)=>{if(!w&&F!==e||w&&f(w)!==f({...r,schemaVersion:1}))throw M();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw M();return p?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...r,...w,purchase:s}}))},settle(r){return o(()=>a(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===r?s.closeCommand?{...s,command:s.closeCommand,closeCommand:void 0}:s.purchase?{...s,command:void 0}:null:s.closeCommand&&"requestId"in s.closeCommand&&s.closeCommand.requestId===r?{...s,closeCommand:void 0}:s:null))}}}function rt(n,e){return e.type==="id"?n.customerId===e.value:n.externalUserId===e.value}function re(n,e){if(n===e)return!0;if(Array.isArray(n)||Array.isArray(e))return Array.isArray(n)&&Array.isArray(e)&&n.length===e.length&&n.every((u,m)=>re(u,e[m]));if(!n||!e||typeof n!="object"||typeof e!="object")return!1;let t=Object.entries(n),f=Object.entries(e);return t.length===f.length&&t.every(([u,m])=>Object.hasOwn(e,u)&&re(m,Reflect.get(e,u)))}function pn(n){let e=null,t=0,f=!1,u,m=0,o=new Set;return{get view(){return e},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return m},nextRead(){return++m},assertCurrent(a,r="Run identity changed during the request"){if(a!==t||f)throw new d("IDENTITY_CHANGED",r)},assertRun(a){if(e&&(a.id!==e.id||a.source.type!==e.source.type||a.source.id!==e.source.id||a.source.versionId!==e.source.versionId||a.locale!==e.locale||!re(a.parameters,e.parameters)))throw new d("INVALID_RESPONSE","Run version changed");if(n&&a.source.id!==n)throw new d("INVALID_RESPONSE","Run belongs to another Funnel")},publish(a,r,s,p,w){if(!(a.operation==="review"&&e&&e!==s&&r.run.revision<=e.revision)&&!(e&&r.run.revision===e.revision&&p!==void 0&&p<m)&&(a.operation==="review"&&!r.run.stopped&&["running","waiting"].includes(r.run.status)&&e&&r.run.nodeId===e.nodeId&&r.run.visit===e.visit&&r.run.revision===e.revision&&(r.run.screen=e.screen,(e.paywall?.quote?.operationId===r.review?.activeOperationId||!e.paywall?.quote&&r.review?.activeOperationId===null)&&(r.run.paywall=e.paywall)),!(e?.paywall&&r.run.paywall&&e.paywall.receiptId===r.run.paywall.receiptId&&(r.run.paywall.selectionGeneration??0)<(e.paywall.selectionGeneration??0)))){if(!e||r.run.revision>=e.revision)e=r.run;else if(!w)return;if(e)for(let F of o)try{F(structuredClone(e))}catch{}}},identify(a){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(a))throw new d("INVALID_TOKEN","Customer credential required");t++,u=a},subscribe(a){return o.add(a),()=>o.delete(a)},reset(){f=!0,t++,u=void 0,e=null,o.clear()}}}function K(n){let{customerToken:e,...t}=n;return t}var bn=n=>!(n instanceof d)||n.status===void 0||n.status>=500||[401,425].includes(n.status);function gn({options:n,journal:e,state:t,call:f}){let u=null,m=null,o=!1,a={command:null,close:null},r=!1,s,p=null,w=e?e.load().then(y=>{if(t.disposed)throw new d("IDENTITY_CHANGED","Controller was reset during command restoration");if(p=y,!y)return;if(n.scope&&(y.scope.projectId!==n.scope.projectId||y.scope.environment!==n.scope.environment))throw new d("SCOPE_MISMATCH","Pending command belongs to another scope");if(s=y.purchase,o=y.closed===!0,!y.command)return;let i=z.parse(y.command);if(i.operation==="start"||i.operation==="get"||i.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");u=i,y.closeCommand&&(m=y.closeCommand,o=!0),i.operation==="close"&&(o=!0),r=!0}):Promise.resolve();w.catch(()=>{});async function F(y=u){if(e&&await w,!y)throw new d("INVALID_REQUEST","No command is pending");let i=y,v=t.generation;if(e){if(!t.view||!n.scope)throw new d("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:K(i)})}if(v!==t.generation||u!==i&&m!==i)throw new d("IDENTITY_CHANGED","Run changed before command dispatch");let P={...i,...t.customerToken?{customerToken:t.customerToken}:{}},S=r;r=!0;try{return await f(P,R=>{if(!R.settlement)throw new d("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==i.requestId)throw new d("INVALID_RESPONSE","Command settlement identity changed");if(v===t.generation&&(u===i||m===i)&&R.run.pendingRequest?.requestId!==i.requestId&&R.settlement.state==="settled"&&(!o||i.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let N=()=>v!==t.generation||u!==i&&m!==i?!1:(u===i&&(u=null),m===i&&(m=null),r=u!==null,p=null,!0);return e?e.settle(i.requestId).then(N):N()}return!1})}catch(R){throw v===t.generation&&u===i&&!S&&!bn(R)&&(e&&await e.settle(i.requestId),v===t.generation&&u===i&&(u=null,r=!1,p=null)),R}}function E(y){let i=z.parse(y);if(i.operation==="start"||i.operation==="get"||i.operation==="review")throw new d("INVALID_REQUEST","Mutation required");if(o&&i.operation!=="close"){if(u?.requestId===i.requestId)return l(i.requestId);throw new d("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(i.operation==="close"&&u?.operation!=="close"){if(o=!0,m&&JSON.stringify(K(m))!==JSON.stringify(K(i)))throw new d("COMMAND_PENDING","Retry the original Close");return m??=i,a.close?a.close:O(m,"close")}if(u){if(JSON.stringify(K(u))!==JSON.stringify(K(i)))throw new d("COMMAND_PENDING","Retry the original command before sending another");if(a.command)return a.command}else u=i,r=!1;return O(u,"command")}function O(y,i){let v=F(y);a[i]=v;let P=()=>{a[i]===v&&(a[i]=null)};return v.then(P,P),v}async function l(y){let i=await f({operation:"get",settlementRequestId:y,...t.customerToken?{customerToken:t.customerToken}:{}});if(i.settlement?.requestId!==y)throw new d("INVALID_RESPONSE","Exact command settlement is missing");return i.settlement.state==="settled"&&(e&&await e.settle(y),u?.requestId===y&&(u=null,r=!1),m?.requestId===y&&(m=null)),i}return{ready:w,get pending(){return u},get closing(){return m},get closeRequested(){return o},get inFlight(){return a.command},get closeFlight(){return a.close},get purchase(){return s},assertBinding(y){if(p&&(y.run.id!==p.runId||y.run.source.id!==p.funnelId||y.run.source.versionId!==p.versionId))throw new d("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(y,i,v,P){e?.bind({scope:i.scope,runId:i.run.id,funnelId:i.run.source.id,versionId:i.run.source.versionId}),e&&!n.scope&&(n.scope=i.scope);let S=i.run.paywall,R=S??i.purchase,N=R?.operation,T=i.settlement&&(!S||S.purchaseRequestId===i.settlement.requestId)&&(!s||s.operationId===i.settlement.operationId)?i.settlement:void 0,V=N?.operationId??R?.quote?.operationId??T?.operationId,J=R?.receiptId??T?.receiptId,B=S?.selectionGeneration??s?.generation??0;if(e&&V&&J&&y.operation!=="review"&&(!t.view||i.run.revision>=t.view.revision)&&(P===void 0||P>=t.readSequence)&&(!s||B>=s.generation)){let Y={receiptId:J,operationId:V,generation:B},q=N?.status==="complete"||R?.canReselect===!0;return e.observePurchase({scope:i.scope,runId:i.run.id,funnelId:i.run.source.id,versionId:i.run.source.versionId},Y,q).then(()=>{t.assertCurrent(v),q?s?.operationId===Y.operationId&&(s=void 0):s=Y})}},stop(){o=!0},submit:E,executePending:F,settle:l,reset(){u=null,m=null,a.close=null,r=!1,a.command=null}}}function yn(n){if(n={...n},typeof n.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(n.runToken))throw new d("INVALID_TOKEN","Run credential required");if(n.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.serverKey)))throw new d("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let e=te({...n,...n.serverKey?{fetch:(l,y)=>{let i=new Headers(y?.headers),v=typeof y?.body=="string"?JSON.parse(y.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||i.set(Ye,n.serverKey),(n.fetch??globalThis.fetch)(l,{...y,headers:i})}}:{},timeoutMs:n.timeoutMs??35e3});e.identify(n.runToken);let t=pn(n.funnelId),f=null,u=n.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?un(n):void 0),m=u&&mn(u),o=gn({options:n,journal:m,state:t,call:a});async function a(l,y,i){let v=t.generation,P=()=>t.assertCurrent(v);m&&await o.ready,P();let S=t.view,R=pe.parse(await ye(n,await e.request("funnels",z.parse(l))));if(l.operation==="review"&&!R.review)throw new d("INVALID_RESPONSE","Historical projection is missing");if(P(),R.runToken&&R.runToken!==n.runToken)throw new d("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&R.settlement?.requestId!==N)throw new d("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run);let T=o.observePurchase(l,R,v,i);if(T&&await T,!R.run.stopped&&["running","waiting"].includes(R.run.status)&&l.operation==="get"&&l.settlementRequestId)return R;let V=y?.(R),J=typeof V=="boolean"?V:V?await V:!1;return P(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(l,R,S,i,J),R}let r=o.submit,s=null,p=new WeakMap;function w(l){let y=p.get(l);if(y)return y;let i=E(l);return p.set(l,i),i}let F=!1;async function E(l){let y=await l;if(y.run.instruction?.type!=="evaluate_segment")return y;if(s)return s;F=!0;let i=t.generation,v=(async()=>{for(let P=0;P<32&&y.run.instruction?.type==="evaluate_segment";P++){if(o.pending||o.closeRequested)return y;let S=y.run;if(y.run.instruction?.type==="evaluate_segment"){let{advance:N,prediction:T}=await cn(n.configuration,S);if(i!==t.generation)throw new d("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return y;if(t.view&&(t.view.revision!==S.revision||t.view.visit!==S.visit||t.view.nodeId!==S.nodeId))return a({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});f=T;try{y=await r({operation:"commit_segment",requestId:Qe(S.id,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,...N})}finally{f===T&&(f=null)}}}return y})();s=v;try{return await v}finally{s===v&&(s=null)}}let O={get configuration(){return F?n.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(K(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(K(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get prediction(){return f?structuredClone(f):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(l){return he(n,l)},review(l){return a({operation:"review",...l?{receiptId:l}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(l,y){m&&await o.ready,y??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let i=t.nextRead();return w(a({operation:"get",...l?{data:l}:{},...y?{purchase:y}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,i))},resume(l=t.view?.pendingRequest?.requestId){return l?o.closeRequested?O.settle(l):o.pending?.requestId===l?w(r(o.pending)):w(r({operation:"resume",requestId:l})):Promise.reject(new d("INVALID_REQUEST","No interrupted command is available"))},submit(l){return w(r(l))},retry(){return o.closeFlight?o.closeFlight:o.closing?o.executePending(o.closing):o.closeRequested&&o.pending?O.settle(o.pending.requestId):o.inFlight?w(o.inFlight):o.pending?w(r(o.pending)):Promise.reject(new d("INVALID_REQUEST","No command is pending"))},identify(l){t.identify(l),e.identify(n.runToken)},subscribe:t.subscribe,reset(){t.reset(),o.reset(),f=null,e.reset()}};return O}async function Et(n,e){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(e.customerToken))throw new d("INVALID_TOKEN","A verified Customer credential is required");let t=te(n);t.identify(e.customerToken);let f=X.resolvePaywall.request.parse({funnelId:e.funnelId,funnelVersionId:e.funnelVersionId,selector:e.paywallVersionId?{type:"version",versionId:e.paywallVersionId}:{type:"paywall",paywallId:e.paywallId},commerce:e.commerce,locale:e.locale,...e.requirement?{requirement:e.requirement}:{}}),u=null,m=!1,o=null,a=null,r=null,s=null;async function p(){if(m)throw new d("IDENTITY_CHANGED","Paywall is closed");let E=X.resolvePaywall,O=await ge(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),l={paywall:await he(n,O.paywall)};if(m)throw new d("IDENTITY_CHANGED","Paywall is closed");if(e.paywallVersionId?l.paywall.id!==e.paywallVersionId:l.paywall.paywallId!==e.paywallId)throw new d("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!rn(l.paywall,u)||l.paywall.paywallId!==u.paywallId))throw new d("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=l.paywall,structuredClone(u)}async function w(E){if(!o)throw new d("INVALID_REQUEST","A quoted purchase is required");let O=E==="read"?X.readSubscriptionOperation:X.attach,l=await ge(t.request,O,{operationId:o.operationId,...E==="read"?{}:{intent:E}});return on(l.operation,{operationId:o.operationId,currency:f.commerce.currency},"The purchase operation changed"),a=sn(a,l.operation),structuredClone(a)}let F={get view(){return u?structuredClone(u):null},get quote(){return o?structuredClone(o):null},get operation(){return a?structuredClone(a):null},get webViewUrl(){return"bundled"},refresh:p,async preview(E){if(!u)throw new d("INVALID_REQUEST","Load the Paywall first");let O=u.document.buttons[E.actionId];if(O?.type!=="checkout")throw new d("INVALID_REQUEST","Choose an authored purchase action");let l=Me(O.product,E.selection,u.capabilities);if(!l)throw new d("PRODUCT_UNAVAILABLE","Choose an available Product");let y=X.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:l}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),i=JSON.stringify(y);if(r&&r!==i&&(!a||a.status==="pending"))throw new d("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(r===i){if(s)return s;if(o)return structuredClone(o)}r=i;let v=(async()=>{let P=X.previewAttach,S=await ge(t.request,P,y);return an(S.quote,{productVersionId:l,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=S.quote,a=null,structuredClone(o)})();s=v;try{return await v}finally{s===v&&(s=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){m=!0,t.reset(),u=null,o=null,a=null,r=null}};return await p(),F}import{z as Nn}from"zod";import{z as ue}from"zod";var Fn=ue.record(ue.string().regex(/^[a-f0-9]{64}$/),ue.strictObject({at:ue.number(),text:ue.string()})),wn=2*1048576,En=100;function An(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function hn(n,e){let t=e===void 0?An():e,f=Promise.resolve();async function u(o){if(!t)return null;let a;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(o)),new Promise(r=>{a=setTimeout(()=>r(null),En)})])}catch{return null}finally{clearTimeout(a)}}async function m(){try{let o=await u(`${n}:artifacts`);if(o&&o.length<=wn)return Fn.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return u(n)},writeManifest(o){Promise.resolve().then(()=>t?.setItem(n,o)).catch(()=>{})},async readArtifact(o){let a=(await m())[o];return a&&Date.now()>=a.at&&Date.now()-a.at<=U.retentionMs?a.text:void 0},writeArtifact(o,a){t&&(f=f.catch(()=>{}).then(async()=>{let r=await m(),s=Date.now();r[o]={at:s,text:a};let p={},w=2,F=0;for(let[E,O]of Object.entries(r).sort(([,l],[,y])=>y.at-l.at)){if(O.at>s||s-O.at>U.retentionMs)continue;let l=new TextEncoder().encode(JSON.stringify({[E]:O})).byteLength;w+l>wn||F>=128||(p[E]=O,w+=l,F++)}await t.setItem(`${n}:artifacts`,JSON.stringify(p))}).catch(()=>{}))}}}var C=(n,e)=>new d(n,e),Q=()=>performance.now(),In=n=>{typeof n=="object"&&"unref"in n&&n.unref()};function kt(n){let e=Je.parse(n.scope),t=new URL(n.origin??ne);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw C("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(n.assetOrigins??[]).map(g=>{let c=new URL(g);if(c.protocol!=="https:"||c.username||c.password||c.search||c.hash||c.pathname!=="/")throw C("INVALID_URL","Invalid configuration asset origin");return c.origin})]),u=n.fetch??globalThis.fetch.bind(globalThis),m=`/api/v1/configuration/${e.environmentId}`,o=`indiana:configuration:1:${t.origin}:${x(e)}`,a=hn(o,n.storage),r,s=0,p=0,w=!1,F=!1,E=0,O=0,l,y,i,v,P=0,S=new Set,R=new Set,N=new Map,T=new Map,V=0,J=!1;function B(){for(let g of S)try{g()}catch{}}function Y(g){try{n.onError?.(g)}catch{}}let q=()=>!F&&!w&&!!r&&Q()<s&&Date.now()<p;function oe(){if(!q())throw C("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Fe(g,c){let h=new TextEncoder().encode(c).byteLength;if(!N.has(g)){for(;N.size&&(N.size>=128||V+h>U.maxCacheBytes);){let I=N.entries().next().value;V-=new TextEncoder().encode(I[1]).byteLength,N.delete(I[0])}N.set(g,c),V+=h}}function Ee(g,c,h){return ln(g,c,{signal:h,error:I=>C("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ae(g){let c=new URL(g,t);if(!f.has(c.origin)||c.username||c.password||c.hash||c.search)throw C("INVALID_URL","Configuration artifact origin is not trusted");return c.href}async function ve(g,c,h=!1){let I=await u(Ae(g),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:c,headers:{}});if(I.status===429){let b=I.headers.get("retry-after")??"";P=/^\d+$/.test(b)?Number(b)*1e3:Math.max(0,Date.parse(b)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw C(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Rn(g,c,h){let I=Date.parse(g.headers.get("x-indiana-config-validated-at")??""),b=Date.parse(g.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(g.headers.get("date")??""),A=g.headers.get("age"),k=A!==null&&/^\d+(\.\d+)?$/.test(A)?Number(A)*1e3:NaN;if(![I,b,_,k].every(Number.isFinite)||b<=I||b-I>U.maxControlAgeMs||I>_+1e3)throw C("INVALID_RESPONSE","Configuration freshness evidence is invalid");let D=Math.min(b-I,h.maxControlAgeSeconds*1e3,U.maxControlAgeMs)-Math.max(k,_-I,0)-(Q()-c);if(D<=0)throw C("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Q()+D}function Re(){if(clearTimeout(i),clearTimeout(v),F||!S.size)return;q()&&(v=setTimeout(()=>{q()?Re():B()},Math.max(1,s-Q())),In(v));let g=O?Math.min(15e3,1e3*2**Math.min(O-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);i=setTimeout(()=>{ee().catch(Y)},Math.max(P,g*(.8+Math.random()*.2))),In(i)}async function ee(){if(F)throw C("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(l)return l;let g=E,c=new AbortController;y=c;let h=(async()=>{if(!J){J=!0;try{let fe=await a.readManifest();if(fe&&!r){let j=Pe.parse(JSON.parse(fe));x(j.scope)===x(e)&&(r=j)}}catch{}}c.signal.throwIfAborted();let A=r,k=Q(),L=await ve(m,c.signal);L.status===304&&(!A||!L.headers.has("x-indiana-config-validated-at")||!L.headers.has("x-indiana-config-valid-until")||!L.headers.has("age"))&&(L=await ve(m,c.signal));let D=L.status===304?A:Pe.parse(JSON.parse(await Ee(L,U.maxManifestBytes,c.signal))),{generation:H,...$}=D,Z=L.headers.get("etag");if(x(D.scope)!==x(e)||je($)!==H||Z!==`"${H}"`&&Z!==`W/"${H}"`)throw C("INVALID_RESPONSE","Configuration scope or content identity changed");if(A&&(D.revision<A.revision||D.revision===A.revision&&D.generation!==A.generation))throw C("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[fe,j]of Object.entries(A?.funnels??{})){let W=D.funnels[fe];if(W&&(W.controlRevision<j.controlRevision||W.evaluationRevision<j.evaluationRevision||W.controlRevision===j.controlRevision&&W.state!==j.state||W.evaluationRevision===j.evaluationRevision&&W.evaluationMode!==j.evaluationMode))throw C("INVALID_RESPONSE","Funnel control revision changed identity")}let De=Rn(L,k,D.policy);if(c.signal.throwIfAborted(),g!==E)throw C("CONFIGURATION_DISPOSED","Configuration scope changed");return r=D,s=De,p=Date.now()+Math.max(0,De-Q()),w=!1,O=0,P=0,a.writeManifest(x(D)),B(),structuredClone(D)})(),I=setTimeout(()=>c.abort(C("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),U.initializationMs),b=new Promise((A,k)=>c.signal.addEventListener("abort",()=>k(c.signal.reason),{once:!0})),_=Promise.race([h,b]).catch(A=>{throw O++,(A instanceof Nn.ZodError||A instanceof SyntaxError||A instanceof d&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(A.code))&&(s=0,w=!0,B()),A}).finally(()=>{clearTimeout(I),l===_&&(l=void 0),Re()});return l=_,_}async function le(g){let c=g.sha256,h=H=>we(H,g);Ae(g.url);let I=N.get(c);if(I&&h(I))return N.delete(c),N.set(c,I),I;if(T.has(c))return T.get(c);let b=new AbortController;R.add(b);let _=E,A=(async()=>{try{let Z=await a.readArtifact(c);if(Z&&h(Z))return Fe(c,Z),Z}catch{}b.signal.throwIfAborted();let H=await ve(g.url,b.signal,!0),$=await Ee(H,g.byteLength,b.signal);if(!h($))throw C("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(F||_!==E)throw C("CONFIGURATION_DISPOSED","Configuration scope changed");return Fe(c,$),a.writeArtifact(c,$),$})(),k=setTimeout(()=>b.abort(C("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),U.initializationMs),L=new Promise((H,$)=>b.signal.addEventListener("abort",()=>$(b.signal.reason),{once:!0})),D=Promise.race([A,L]).finally(()=>{clearTimeout(k),R.delete(b),T.delete(c)});return T.set(c,D),D}async function ce(){return q()||await ee(),oe(),r}async function ie(g){let c,h=new Promise((I,b)=>{c=setTimeout(()=>b(C("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),U.initializationMs)});try{return await Promise.race([g(),h])}finally{clearTimeout(c)}}function ae(g,c){if(oe(),r?.generation!==g.generation)throw C("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(c&&r.funnels[c]?.state!=="active")throw C("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ne(g){let c=g.gb.features;if(!c)throw C("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=g.artifacts[c];if(h.formatVersion!==1)throw C("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Ue.parse(JSON.parse(await le(h)));if(x(I.scope)!==x({projectId:e.projectId,environment:e.environment})||I.generation!==h.generation||I.remoteFeatures.some(b=>Object.hasOwn(I.features,b)))throw C("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(g),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-Q())).toISOString()}}async function Oe(g,c){let h=await ce(),I=h.funnels[g];c&&(!I||I.evaluationMode==="local"&&!I.versions[c])&&(l&&await l,h=await ee()),ae(h,g);let b=h.funnels[g];if(b.evaluationMode!=="local")throw C("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let _=c??b.currentVersionId,A=b.versions[_];if(!A)throw C("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[A.artifact].formatVersion!==3)throw C("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[k,L]=await Promise.all([le(h.artifacts[A.artifact]).then(D=>He(JSON.parse(D))),b.evaluationMode==="local"?Ne(h):void 0]);if(L&&x(ze(k,L))!==x(A.dependencies))throw C("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(h,g),{document:k,growth:L,versionId:_,control:structuredClone(b),manifest:structuredClone(h)}}async function Te(g,c){try{return await Oe(g,c)}catch(h){if(!(h instanceof d)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&q()))throw h;let I=r?.generation;if(l&&await l,await ee(),h.code!=="CONFIGURATION_CHANGED"&&r?.generation===I)throw h;return Oe(g,c)}}function Ce(){w=!0,B(),ee().catch(Y)}let de=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Cn(g){if(F)throw C("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(g),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",de),document.addEventListener("visibilitychange",de)),Re()),()=>{S.delete(g),S.size||(clearTimeout(i),clearTimeout(v),_e())}}function _e(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",de),document.removeEventListener("visibilitychange",de))}return{scope:Object.freeze({...e}),refresh:ee,subscribe:Cn,assertFresh:oe,assertFeatures(g){oe();let c=r.gb.features;if(!c)throw C("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(g!==void 0&&r.artifacts[c].generation!==g)throw C("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return q()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return q()?Math.max(0,s-Q()):0},async features(){return ie(async()=>Ne(await ce()))},pageExperiments:()=>ie(async()=>{let g=await ce(),c=g.gb.pageExperiments;if(!c)throw C("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=g.artifacts[c];if(h.formatVersion!==1)throw C("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=Xe.parse(JSON.parse(await le(h)));if(I.environmentId!==e.environmentId||I.generation!==h.generation)throw C("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(g),I}),funnel:(g,c)=>ie(()=>Te(g,c)),paywall:(g,c)=>ie(async()=>{let h=await ce(),I=h.paywalls?.[g];if(!I||!c&&I.state!=="published")throw C("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let b=c??I.currentVersionId,_=I.versions[b],A=_&&h.artifacts[_.artifact];if(!A||A.kind!=="paywall"||A.formatVersion!==1)throw C("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let k=Ge.parse(JSON.parse(await le(A)));return ae(h),{document:k,versionId:b,version:_.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(g,c){let h=await ie(()=>Te(g,c));if(!h.growth)throw C("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:b,..._}=h.growth;return We({scope:{projectId:e.projectId,environment:e.environment},funnelId:g,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:_})},assertFunnel(g,c,h){oe();let I=r.funnels[g];if(!I||I.state!=="active")throw C("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw C("EVALUATION_MODE","This Funnel now executes at Indiana");if(c!==void 0&&I.controlRevision!==c)throw C("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw C("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!F){F=!0,E++,s=0,y?.abort(C("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(i),clearTimeout(v),_e(),B(),S.clear();for(let g of R)g.abort(C("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),V=0}}}}function Jt(n,e,t){return nn(n,e,t,se)}function vn(n){let e=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey);if(typeof window<"u"&&!e)throw new d("SERVER_ONLY","Funnel starts are issued by your backend");if(!e&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new d("INVALID_TOKEN","A customer credential or server API key is required");let t=te({...n,timeoutMs:n.timeoutMs??35e3});return t.identify(n.apiKey),{async start(f){let u=z.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(e?u.data.customer!==void 0:u.data.customer===void 0))throw new d("INVALID_REQUEST","Invalid current Funnel start");let m=u.data,o=pe.safeParse(await ye(n,await t.request("funnels",m)));if(!o.success||!o.data.runToken)throw new d("INVALID_RESPONSE","Funnel start credentials are missing");let a=o.data;if(a.run.source.id!==m.funnelId||a.run.locale!==(m.locale??"en")||!re(a.run.parameters,m.parameters??{})||(m.customer?!a.customerId||m.customer.type==="id"&&a.customerId!==m.customer.value:a.customerId!==void 0))throw new d("INVALID_RESPONSE","Funnel start contract changed");return{...a,runToken:a.runToken}}}}async function Xt(n){n={...n};let e=n.configuration;if(!e)throw new d("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:e.scope.projectId,environment:e.scope.environment};if(n.scope&&x(t)!==x(n.scope))throw new d("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await e.funnel(n.funnelId)).control.evaluationMode!=="local")throw new d("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.credential);if(u?!n.customerId:n.customerId!==void 0)throw new d("INVALID_REQUEST","Only Server-Key starts name their Customer");let m=vn({...n,scope:t,apiKey:n.credential}),o=a=>{let r=yn({...n,scope:t,runToken:a,...u?{serverKey:n.credential}:{}});return u||r.identify(n.credential),r};return{async start(a){let r=await m.start({...a,funnelId:n.funnelId,...u?{customer:{type:"id",value:n.customerId}}:{}}),s=o(r.runToken),p=await s.get();return{...r,...p,controller:s}},async restore(a){let r=o(a),s=await r.get();if(s.run.source.id!==n.funnelId)throw r.reset(),new d("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:a,controller:r}}}}export{Tn as a,ye as b,se as c,$n as d,Pn as e,un as f,rt as g,re as h,yn as i,Et as j,kt as k,Jt as l,vn as m,Xt as n};
@@ -1 +1 @@
1
- import{K as o}from"./chunk-HD74AAFS.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
1
+ import{p as o}from"./chunk-3BQFJANQ.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
@@ -0,0 +1 @@
1
+ import{a as u,c as d}from"./chunk-RRII2DMC.js";import{z as b}from"zod";var z=b.enum(["sandbox","live"]),k=b.object({projectId:b.string().min(1),environment:z}).strict();import{z as t}from"zod";var f=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([n,g])=>n<=g),C=t.strictObject({attribute:t.string().optional(),seed:t.string(),hashVersion:t.literal(2),ranges:t.array(f).max(100)}),E=t.strictObject({id:t.string().min(1).max(255),condition:d,gate:t.boolean().optional()}),H=t.strictObject({key:t.string().optional(),name:t.string().optional(),passthrough:t.boolean().optional()}),M={condition:d.optional(),parentConditions:t.array(E).max(100).optional(),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),hashAttribute:t.string().optional(),fallbackAttribute:t.string().optional(),hashVersion:t.literal(2).optional(),disableStickyBucketing:t.boolean().optional(),bucketVersion:t.number().int().nonnegative().optional(),minBucketVersion:t.number().int().nonnegative().optional(),filters:t.array(C).max(100).optional(),ranges:t.array(f).max(20).optional(),meta:t.array(H).max(20).optional(),seed:t.string().optional(),name:t.string().optional(),phase:t.string().optional()},y=t.strictObject({...M,key:t.string().min(1).max(255),variations:t.tuple([u,u]).rest(u).refine(n=>n.length<=20),urlPatterns:t.array(t.strictObject({include:t.boolean(),type:t.enum(["regex","simple"]),pattern:t.string()})).max(100).optional(),force:t.number().int().nonnegative().optional(),active:t.boolean().optional(),persistQueryString:t.boolean().optional()}),N=t.strictObject({value:u,variationId:t.number().int(),key:t.string(),name:t.string().optional(),bucket:t.number().optional(),passthrough:t.boolean().optional(),inExperiment:t.boolean(),hashUsed:t.boolean().optional(),hashAttribute:t.string(),hashValue:t.string(),featureId:t.string().nullable(),stickyBucketUsed:t.boolean().optional()}),U=t.strictObject({...M,id:t.string().max(255).optional(),force:u.optional(),variations:t.array(u).min(2).max(20).optional(),key:t.string().optional(),range:f.optional(),tracks:t.array(t.strictObject({experiment:y,result:N})).max(100).optional()}),D=t.strictObject({defaultValue:u.optional(),rules:t.array(U).max(500).optional()}),h=t.record(t.string(),t.union([t.strictObject({type:t.literal("hashed"),attributeKey:t.string(),values:t.array(t.string().regex(/^[a-f0-9]{64}$/))}),t.strictObject({type:t.literal("list"),attributeKey:t.string(),values:t.array(t.union([t.string(),t.number()]))}),t.strictObject({type:t.literal("condition"),condition:d})])),te=t.strictObject({scope:k,generation:t.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}).nullable(),features:t.record(t.string(),D),savedGroups:h,experiments:t.record(t.uuid(),y)});import{z as a}from"zod";import{z as e}from"zod";import{z as r}from"zod";var P=r.strictObject({schemaVersion:r.literal(1),renderKey:r.string().min(1).max(256),routeTemplate:r.string().startsWith("/").max(2048),selectors:r.array(r.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:r.array(r.number().int().min(0)).min(1),absent:r.array(r.number().int().min(0))}).superRefine((n,g)=>{let s=[...n.present,...n.absent];(new Set(n.selectors).size!==n.selectors.length||new Set(s).size!==s.length||s.length!==n.selectors.length||s.some(o=>o>=n.selectors.length))&&g.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),w=r.strictObject({renderKey:r.string().min(1).max(256),routeKey:r.string().min(1).max(256),stateKey:r.string().min(1).max(256),documentKey:r.string().min(1).max(256),documentHash:r.string().regex(/^[a-f0-9]{64}$/),compositionKey:r.string().min(1).max(256),entryMode:r.enum(["hard","soft"]),match:r.strictObject({present:r.array(r.number().int().min(0)),absent:r.array(r.number().int().min(0))})});import{z as m}from"zod";var B={"enterprise-internal-indiana-test":"indiana-admin-vercel@enterprise-internal-490516.iam.gserviceaccount.com","tinkerland-indiana-prod":"indiana-admin-vercel@tinkerland-indiana.iam.gserviceaccount.com"},x="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",T=m.string().regex(new RegExp(`^${x}/${x}/${x}/manifest\\.json$`)),X="content-length;content-type;host;x-goog-if-generation-match",A=m.strictObject({kind:m.literal("gcs-v4-put"),url:m.url(),bucket:m.enum(["enterprise-internal-indiana-test","tinkerland-indiana-prod"]),objectKey:T,byteLength:m.number().int().min(1),expiresAt:m.iso.datetime(),headers:m.strictObject({"Content-Type":m.literal("application/json"),"x-goog-if-generation-match":m.literal("0")})}).superRefine((n,g)=>{let s=new URL(n.url),o=s.searchParams,R=["X-Goog-Algorithm","X-Goog-Credential","X-Goog-Date","X-Goog-Expires","X-Goog-Signature","X-Goog-SignedHeaders"],l=o.get("X-Goog-Date")??"",O=/^\d{8}T\d{6}Z$/.test(l)?Date.parse(`${l.slice(0,4)}-${l.slice(4,6)}-${l.slice(6,8)}T${l.slice(9,11)}:${l.slice(11,13)}:${l.slice(13,15)}Z`):NaN,p=Number(o.get("X-Goog-Expires"));(s.origin!=="https://storage.googleapis.com"||s.username||s.password||s.hash||s.pathname!==`/${n.bucket}/app-manifests/${n.objectKey}`||[...o.keys()].length!==R.length||R.some($=>o.getAll($).length!==1)||o.get("X-Goog-Algorithm")!=="GOOG4-RSA-SHA256"||o.get("X-Goog-Credential")!==`${B[n.bucket]}/${l.slice(0,8)}/auto/storage/goog4_request`||o.get("X-Goog-SignedHeaders")!==X||!/^[a-f0-9]{512,1024}$/.test(o.get("X-Goog-Signature")??"")||!Number.isFinite(O)||!Number.isInteger(p)||p<1||p>900||O+p*1e3!==Date.parse(n.expiresAt))&&g.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var i=e.string().min(1).max(256),c=e.string().regex(/^[a-f0-9]{64}$/),le=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:i,stateKey:i,documentKey:i,documentHash:c,elementKey:i.optional(),nodeId:i.optional(),contentHash:c.optional(),renderKey:i.optional()}),G=e.strictObject({pageKey:i,documentKey:i,expectedDocumentHash:c,renderKey:i.optional(),nodeId:i,elementKey:i,expectedContentHash:c,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),V=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:i,stateKey:i,documentKey:i,documentHash:c,renderKey:i.optional(),patches:e.array(G.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),_=/^[a-z][a-z0-9-]{0,39}$/,K=e.string().regex(_),I=e.enum(["web","ios","android"]),ue=e.discriminatedUnion("action",[e.strictObject({action:e.literal("register"),requestId:e.uuid(),client:K,platform:I,label:e.string().trim().min(1).max(100),sha256:c,bytes:e.number().int().min(1),transferBytes:e.number().int().min(1)}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),variationId:i,changesetId:e.uuid().nullable(),expectedRevision:c.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(G).min(1).max(200)})]),S=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),clientKey:K,platform:I,label:e.string(),sha256:c,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),F=e.strictObject({key:K,platform:I,currentId:e.uuid().nullable()}),ge=e.strictObject({rows:e.array(S).max(100),nextCursor:e.uuid().nullable(),clients:e.array(F).max(20)}),v=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),pe=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:v,runtime:v,previews:v})}),de=e.strictObject({asOf:e.iso.datetime({offset:!0}),reviewOnly:e.literal(!0),complete:e.boolean(),issues:e.strictObject({scanLimit:e.boolean(),invalidReferences:e.number().int().nonnegative(),missingVersions:e.number().int().nonnegative()}),totals:e.strictObject({versions:e.number().int().nonnegative(),protected:e.number().int().nonnegative(),reviewCandidates:e.number().int().nonnegative()}),rows:e.array(e.strictObject({versionId:e.uuid(),kind:e.enum(["source","runtime"]),state:e.enum(["uploading","ready","rejected"]),createdAt:e.iso.datetime({offset:!0}),reviewAfter:e.iso.datetime({offset:!0}),reasons:e.array(e.enum(["current","upload-capability","retention-grace","incomplete-inventory","retained-observation","gb","gb-observation","funnel-draft","funnel-draft-observation","funnel-version","funnel-version-observation"])).max(11)})).max(50),nextCursor:e.uuid().nullable()}),ye=e.strictObject({version:S,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),be=e.strictObject({version:S,upload:A.nullable()}),fe=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:i,path:e.string(),documentKey:i,documentHash:c,initialStateKey:i,initialRenderKey:i})),renders:e.array(w)}).loose().superRefine((n,g)=>{(!n.renders||n.routes.some(s=>!n.renders?.some(o=>o.renderKey===s.initialRenderKey&&o.routeKey===s.routeKey&&o.documentKey===s.documentKey&&o.stateKey===s.initialStateKey&&o.documentHash===s.documentHash&&o.entryMode==="hard")))&&g.addIssue({code:"custom",message:"Incomplete render catalog"})}),he=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:i,key:i,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),xe=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var L=a.strictObject({selector:a.string().min(1).max(2048),action:a.enum(["set","append","remove"]),attribute:a.string().min(1).max(128).refine(n=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(n)||/^(aria|data)-[a-z0-9_-]+$/.test(n)),value:a.string().max(5e4).optional(),parentSelector:a.string().max(2048).optional(),insertBeforeSelector:a.string().max(2048).optional()}),q=a.strictObject({variation:a.string().min(1).max(128),description:a.string().max(2e3).default(""),css:a.string().max(1e5).default(""),js:a.string().max(1e5).default(""),domMutations:a.array(L).max(200).default([]),iam:V.optional(),renderGuard:P.optional()}),j=q.omit({variation:!0,description:!0,iam:!0}),J=y.omit({variations:!0,active:!0}).extend({changeId:a.string().regex(/^[a-f0-9]{64}$/),variations:a.tuple([j,j]).rest(j).refine(n=>n.length<=20)}),Re=a.strictObject({trackExposures:a.boolean(),environmentId:a.uuid(),generation:a.string().regex(/^[a-f0-9]{64}$/),experiments:a.array(J).max(100),savedGroups:h});export{z as a,k as b,y as c,N as d,U as e,D as f,h as g,te as h,le as i,L as j,q as k,j as l,J as m,Re as n};
@@ -0,0 +1 @@
1
+ import{a as T,b as _,e as v}from"./chunk-F767CM3T.js";import{a as e}from"./chunk-6HG7U6AU.js";import{a as C,j as O,m as j,p as D}from"./chunk-3BQFJANQ.js";import{b as E}from"./chunk-AE4CUTUE.js";import{a as k}from"./chunk-EXCPE2XH.js";var P={name:"@tinkerlandai/indiana-sdk",version:"0.8.1",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var L=Symbol("IndianaNoContent");function Q(p,M,U=URL){let d=p.configuration?.scope,b=p.scope??(d&&{projectId:d.projectId,environment:d.environment}),s=b?E.parse(b):void 0;if(s&&d&&(s.projectId!==d.projectId||s.environment!==d.environment))throw new e("SCOPE_MISMATCH","Configuration belongs to another App/environment");let i=new U(p.baseUrl??k);if(i.username||i.password||i.search||i.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let H=p.fetch??globalThis.fetch.bind(globalThis),m=p.timeoutMs??1e4;if(!Number.isFinite(m)||m<1||m>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let f=null,l=0,u=null,h=new Set;function S(){l+=1,f=null,u=null;for(let a of h)a.abort();h.clear()}async function q(a,x={},R="POST",K={}){if(!f)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let y=l,o=new AbortController;h.add(o);let g=()=>y!==l?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),I,V=new Promise((r,n)=>{I=()=>n(g()),o.signal.addEventListener("abort",I,{once:!0})}),F=setTimeout(()=>o.abort(),m),G=async()=>{let r=await H(`${i.href.replace(/\/$/,"")}/api/v1/${a}`,{method:R,headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`,[T]:v.current,[_]:P.version,...s?{"X-Indiana-Project":s.projectId,"X-Indiana-Environment":s.environment}:{}},body:R==="POST"?JSON.stringify(x):void 0,signal:o.signal,credentials:"omit",cache:"no-store",redirect:"error",...K.keepalive?{keepalive:!0}:{}});if(o.signal.aborted)throw g();let n;try{n=r.status===204?L:await r.json()}catch{throw o.signal.aborted?g():new e(r.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",r.status,r.headers.get("X-Request-Id")??void 0)}if(o.signal.aborted)throw g();if(y!==l)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!r.ok){let t=j.safeParse(n),c=t.success&&(!C.safeParse(t.data.error.code).success||O(t.data.error.code,r.status)),A=c?t.data.error.code:"HTTP_ERROR",N=D(A,r.status,{retryAfter:r.headers.get("Retry-After"),recovery:c?t.data.error.recovery:void 0,reason:c?t.data.error.reason:void 0});throw new e(A,c?t.data.error.message:"Indiana request failed",r.status,r.headers.get("X-Request-Id")??(t.success?t.data.requestId:void 0),{...N,...t.success&&t.data.error.retryable===!1?{retryable:!1}:{},...N.retryAfterSeconds===void 0&&t.success&&t.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:t.data.error.retryAfterSeconds}:{}})}if(r.headers.get(T)!==v.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(s&&n!==L){let t=n&&typeof n=="object"&&"scope"in n?n:n&&typeof n=="object"&&"configuration"in n?n.configuration:null;if(!t||typeof t!="object"||!("scope"in t))throw new e("INVALID_RESPONSE","Response is missing its App/environment scope");let c=E.safeParse(t.scope);if(!c.success||c.data.projectId!==s.projectId||c.data.environment!==s.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let w=r.headers.get("X-Indiana-Telemetry-Subject");if(w){if(!/^[a-f0-9]{64}$/.test(w))throw new e("INVALID_RESPONSE","Invalid telemetry identity");u!==w&&(u=w,M?.(u))}return n};try{return await Promise.race([G(),V])}catch(r){throw y!==l?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):r instanceof e?r:new e(o.signal.aborted?"TIMEOUT":"NETWORK_ERROR",o.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(F),o.signal.removeEventListener("abort",I),h.delete(o)}}return{subjectKey:()=>u,identify(a){if(!a.trim()||/\s/.test(a)||a.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");S(),f=a},reset:S,request:q}}export{Q as a};