@tinkerlandai/indiana-sdk 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +9 -4
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +3 -3
  4. package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-BsrSG955.d.ts} +334 -518
  5. package/dist/chunk-3SONNXFG.js +1 -0
  6. package/dist/chunk-467Z5ISI.js +11 -0
  7. package/dist/{chunk-2EJSV6BA.js → chunk-4AWSZWZD.js} +1 -1
  8. package/dist/{chunk-5TEZEOHX.js → chunk-6MO6Y24B.js} +1 -1
  9. package/dist/chunk-HD74AAFS.js +1 -0
  10. package/dist/chunk-J4RHVU3W.js +1 -0
  11. package/dist/chunk-KQCTDXVD.js +17 -0
  12. package/dist/chunk-NOFNOHUI.js +1 -0
  13. package/dist/chunk-QO4YQLZ4.js +1 -0
  14. package/dist/chunk-RRII2DMC.js +1 -0
  15. package/dist/chunk-WCFVNF5D.js +1 -0
  16. package/dist/chunk-YAFMBXIE.js +4 -0
  17. package/dist/{client-OYRHOMUQ.js → client-F6UPJMHR.js} +1 -1
  18. package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-Bvd956GL.d.ts} +333 -25
  19. package/dist/controls-XG46TKUU.js +2 -0
  20. package/dist/funnel-runtime-host-26QI2W3S.js +1 -0
  21. package/dist/{funnel-runtime-start-sZ8ZCNlq.d.ts → funnel-runtime-start-ChVYbLzV.d.ts} +6655 -2785
  22. package/dist/iam.js +1 -1
  23. package/dist/index.d.ts +3634 -1485
  24. package/dist/index.js +1 -1
  25. package/dist/native-shell.js +1 -1
  26. package/dist/openrouter.d.ts +2 -3
  27. package/dist/openrouter.js +1 -1
  28. package/dist/page.d.ts +13 -13
  29. package/dist/page.js +1 -1
  30. package/dist/paywall-WKOHBYW7.js +1 -0
  31. package/dist/popup.d.ts +9 -16
  32. package/dist/popup.js +12 -12
  33. package/dist/react-native.d.ts +14 -14
  34. package/dist/react-native.js +1 -1
  35. package/dist/server.d.ts +4 -4
  36. package/dist/server.js +1 -1
  37. package/dist/src-UHLPVD6E.js +1 -0
  38. package/dist/visual.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-63BWE27V.js +0 -1
  41. package/dist/chunk-CB63JLGT.js +0 -1
  42. package/dist/chunk-D7YHFS6B.js +0 -4
  43. package/dist/chunk-HTRQPMJO.js +0 -11
  44. package/dist/chunk-ISUXYPYL.js +0 -1
  45. package/dist/chunk-QG3WUJG5.js +0 -1
  46. package/dist/chunk-RMJJOSVZ.js +0 -1
  47. package/dist/chunk-S2MSIA57.js +0 -17
  48. package/dist/chunk-VVSQKVE7.js +0 -1
  49. package/dist/funnel-runtime-host-NWS3URFA.js +0 -1
  50. package/dist/paywall-4XZ6NDMY.js +0 -1
  51. package/dist/src-WV6GZYWA.js +0 -1
  52. package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-B4LkIr5q.d.ts} +4 -4
  53. package/dist/{screen-16d-xADb.d.ts → screen-iFngkxaL.d.ts} +185 -185
@@ -1 +1 @@
1
- import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-HTRQPMJO.js";import{a as u}from"./chunk-5TEZEOHX.js";import{h as w}from"./chunk-RMJJOSVZ.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{Qg as E,Rg as M,Sg as j,Tg as O,Ug as T}from"./chunk-467Z5ISI.js";import{a as u}from"./chunk-6MO6Y24B.js";import{h as w}from"./chunk-HD74AAFS.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -1 +1 @@
1
- import{J as o}from"./chunk-RMJJOSVZ.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{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};
@@ -0,0 +1 @@
1
+ import{a as ue}from"./chunk-RRII2DMC.js";import{z as ot}from"zod";var at=["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=ot.enum(at);function pe(e){let t=O.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function Sr(e,t){let r=pe(t),i=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!i?.[1]||(i[2]?.length??0)>r)throw new Error("Amount has invalid currency precision");let a=BigInt(i[1])*BigInt(10**r)+BigInt((i[2]??"").padEnd(r,"0")||"0");if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(a)}function xr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let r=pe(t),i=String(e).padStart(r+1,"0");return r?`${i.slice(0,-r)}.${i.slice(-r)}`:i}function _r(e,t,r="en",i={}){let a=O.parse(t.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as _}from"zod";var te=_.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),st=_.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"),Ie=_.string().min(1).max(64),V=_.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ee=_.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),L=_.record(Ie,_.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,r])=>[t,String(r)]))),Ae=_.record(Ie,_.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[r,i=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");let a=BigInt(r)*BigInt("1000000")+BigInt(i.padEnd(6,"0"));return t?-a:a},Ne=_.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,r)=>{let i=e[r-1]?.upTo;return t.upTo!==null&&(r===0||i!=null&&q(t.upTo)>q(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),ct=_.object({key:Ee,match:Ae,priority:_.number().int().default(0),cost:E.optional(),tiers:Ne.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),lt=_.object({key:Ee,match:Ae,factor:me.optional(),add:st.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"})),ut=_.object({units:me.default("1"),cost:E,tiers:Ne.optional(),dimensions:_.array(ct).max(12).optional(),multipliers:_.array(lt).max(4).optional()}).strict().superRefine((e,t)=>{let r=e.dimensions??[],i=e.multipliers??[];(new Set(r.map(l=>l.key)).size!==r.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 r.entries())for(let g of r.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),...r.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"),y=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=q(R.factor??"1"),p*=BigInt("1000000"),y+=q(R.add??"0"));let h=(s+y*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"})}}),Ar=ut.safeExtend({featureKey:V});import{z as pt}from"zod";var Oe=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,M=pt.string().max(16).regex(Oe,"\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:r,script:i,region:a}=new Intl.Locale(t),c=[r,i,a].filter(Boolean).join("-");return Oe.test(c)?c:null}catch{return null}}var mt=new Set(["TW","HK","MO"]);function Re(e){let[t,r,i]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let a=r?.length===4?r:void 0,c=r?.length===4?i:r;return a?`zh-${a}`:c&&mt.has(c)?"zh-Hant":"zh-Hans"}function ke(e,t,r){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=Re(c),g=i.filter(p=>Re(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return r}var dt=[{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 Or(e){return dt.find(t=>t.code===e)?.label??e}import{z as A}from"zod";var re=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"]),Lr=A.enum([...re.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Tr=A.enum([...re.options,"stale_revision"]),ft=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"]),gt=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"]),Le={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 jr(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 Ce={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 yt(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(Ce,e)){let i=Ce[e];return{retryable:i==="retry_same_request",recovery:i}}let r=re.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Le[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Dr(e,t){let r=re.safeParse(e);if(r.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):Le[r.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 bt(e,t=Date.now()){if(e===null)return;let r=e.trim();if(/^\d+$/.test(r)){let a=Number(r);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(r))return;let i=Date.parse(r);return Number.isFinite(i)?Math.max(0,Math.ceil((i-t)/1e3)):void 0}var Te=A.object({retryable:A.boolean(),recovery:ft,reason:gt.optional(),retryAfterSeconds:A.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),ht=A.object({requestId:A.uuid().optional(),error:A.object({code:A.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:A.string(),...Te.partial().shape})}),zr=A.object({error:ht.shape.error.extend({requestId:A.uuid().optional()})}),Pr=A.object({error:A.string(),code:A.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:A.uuid(),...Te.shape});function wr(e,t,r={}){let i=yt(e,t),a=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??i.recovery,c=i.retryable&&r.retryable!==!1&&a!=="recover_operation",l=c?bt(r.retryAfter??null):void 0;return{...i,retryable:c,recovery:a,...l===void 0?{}:{retryAfterSeconds:l},...r.reason?{reason:r.reason}:{}}}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[r,i=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");return BigInt(r)*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:te,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 r=e.reduce((i,a)=>i+k(a.units,12),0n)-k(t,12);return e.some(i=>i.funding==="balance")?r>=-100n&&r<=100n:r===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:te}),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:te,pricing:u.array(St).min(1).max(12)}).strict().refine(e=>K(()=>e.pricing.reduce((t,r)=>t+k(r.units,6),0n)===k(e.units,6)&&e.pricing.reduce((t,r)=>t+k(r.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 r=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||r(e.remaining)!==r(e.capacity)-r(e.usage)||e.withinLimit!==r(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()}),bn=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(r=>r.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),hn=x.strictObject({paywallId:x.uuid(),requirement:Ve});import{z as U}from"zod";var Be=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),qe=U.strictObject({tiers:U.array(U.strictObject({id:Be,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:Be,period:U.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let r=e.tiers.map(i=>i.id);(new Set(r).size!==r.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=>!r.includes(i.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Me(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}function Fe(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function ae(e){let t={};function r(i){if(Fe(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(r)}return e.pages.forEach(i=>r(i.root)),t}function Ze(e,t,r){let i={};function a(g){if(g.hidden)return;if(g.type==="plan_picker"){let y=r.pickers[g.id];i[g.id]={ids:y?.options??[],defaults:y?.selected?[y.selected]:[],remembered:[]};return}if(g.type!=="stack")return;let s=g.children.filter(y=>!y.hidden),p=g.interaction;if(Fe(g)){let y=i[g.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},h=r.pickers[g.interaction.pickerId]?.options??[];for(let v of s){let R=v.type==="stack"?v.bind?.plan:void 0;R&&h.includes(R)&&!y.ids.includes(R)&&y.ids.push(R),R&&v.id===t[g.id]&&y.remembered.push(R)}let w=g.children[g.interaction.defaultIndex];w?.type==="stack"&&!w.hidden&&w.bind?.plan&&y.defaults.push(w.bind.plan)}if(p?.type==="tabs"){let y=s.find(h=>h.id===t[g.id])??g.children[p.defaultIndex];y&&a(y)}else if(p?.type==="toggle"){let y=typeof t[g.id]=="boolean"?t[g.id]:p.defaultEnabled,h=g.children[y?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],y=s.remembered[0]??(s.ids.includes(r.pickers[g]?.selected??"")?r.pickers[g]?.selected:s.defaults[0]);d[g]=typeof p=="string"?s.ids.includes(p)?p:"":y&&s.ids.includes(y)?y:""}for(let g of Object.keys(ae(e)))d[g]??="";return d}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(),Ge=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(),Rn=f.object({paywall:$e.optional(),nodes:f.record(f.string(),f.object({base:Ge,picker:f.string().optional(),byPlan:f.record(f.string(),Ge).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 se(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function ce(e){let t=se(e).filter(i=>!Ot.includes(i)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(i)),r=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(r.includes("{{")||r.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function On(e,t,r,i=!1){let a=se(e).filter(c=>!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(c)&&t[c]===void 0);return a.length&&!i?{value:r,missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(c,l)=>t[l.trim()]??c),missing:a}}function kn(e,t,r={}){let i=e?.nodes[t];if(!i)return;let a=i.picker?r[i.picker]??e?.pickers[i.picker]?.selected:void 0;return typeof a=="string"?i.byPlan?.[a]??i.base:i.base}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=ce(e).map(r=>`\u672A\u77E5\u53D8\u91CF\uFF1A${r}`);for(let r=0;r<e.length;r++){if(e[r]!=="<"||!/[A-Za-z!/?{]/.test(e[r+1]??""))continue;let i=r;if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4);r=a<0?e.length:a+2}else{let a="";for(r++;r<e.length;r++){let c=e[r];if(a)c===a&&(a="");else if(c==='"'||c==="'")a=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(i,r+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,r,i=!1){let a=ge(e);if(a.length)throw new Error(a[0]);let c=[...new Set(se(e).filter(l=>!l.startsWith("variables.")&&t[l]===void 0))];return c.length&&!i?{value:We(r),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 n}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=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),S=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),jt=n.enum(["none","xs","sm","md","lg","xl"]),Dt=n.enum(["none","sm","md","lg","full"]),ye=n.string().regex(/^#[0-9a-fA-F]{6}$/),Je=n.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"),be=n.union([Je,n.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ye=n.object({primary:ye,background:ye,text:ye,radius:Dt,font:n.enum(["system","serif","rounded","mono"])}).strict(),J=n.union([n.enum(["primary","text","muted","background","surface"]),n.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),b=(e,t)=>n.number().int().min(e).max(t),Xe=n.union([n.enum(["fit","fill"]),b(1,1200)]),zt=n.object({top:b(0,200),right:b(0,200),bottom:b(0,200),left:b(0,200)}).strict(),Pt=n.object({top:b(-100,200),right:b(-100,200),bottom:b(-100,200),left:b(-100,200)}).strict(),et=n.object({x:b(0,100),y:b(0,100)}).strict(),wt=n.discriminatedUnion("type",[n.object({type:n.literal("color"),color:J}).strict(),n.object({type:n.literal("linear"),angle:b(0,360),stops:n.array(n.object({color:J,at:b(0,100)}).strict()).min(2).max(4)}).strict(),n.object({type:n.literal("image"),src:be,fit:n.enum(["cover","contain"]),position:et.optional()}).strict()]),vt=n.discriminatedUnion("type",[n.object({type:n.literal("rect"),radius:n.union([b(0,200),n.object({topLeft:b(0,200),topRight:b(0,200),bottomRight:b(0,200),bottomLeft:b(0,200)}).strict()])}).strict(),n.object({type:n.literal("pill")}).strict()]),Ut=n.object({width:b(0,12),color:J,style:n.enum(["solid","dashed"])}).strict(),Vt=n.object({x:b(-40,40),y:b(-40,40),blur:b(0,80),spread:b(-20,40),color:J}).strict(),$t=n.object({font:n.enum(["system","serif","rounded","mono"]),size:b(8,96),weight:n.number().int().min(100).max(900).multipleOf(100),lineHeight:n.number().min(.8).max(3),letterSpacing:n.number().min(-5).max(20),color:J,align:n.enum(["start","center","end"]),italic:n.boolean(),decoration:n.enum(["none","underline","line-through"]),transform:n.enum(["none","uppercase"])}).strict().partial(),B=n.object({width:Xe,height:Xe,padding:zt,margin:Pt,gap:b(0,120),grow:n.union([n.boolean(),n.number().min(0).max(12)]),background:wt,opacity:n.number().min(0).max(1),clipContent:n.boolean(),shape:vt,border:Ut,shadow:Vt,text:$t}).strict().partial(),C={id:X,name:n.string().trim().min(1).max(60).optional(),hidden:n.boolean().optional(),style:B.optional(),fallback:S.optional()},Bt=n.object({...C,type:n.literal("text"),productField:n.enum(["name","price","trial","period"]).optional(),feature:n.object({id:n.uuid(),field:n.enum(["name","allowance"])}).strict().optional(),text:S,variant:n.enum(["title","heading","body","caption"])}).strict(),qt=n.object({...C,type:n.literal("image"),src:be,localizedSrc:n.record(M,be).optional(),alt:S,aspect:n.enum(["auto","1:1","4:3","16:9","3:1"]),fit:n.enum(["cover","contain"]),position:et.optional()}).strict(),Mt=n.object({...C,type:n.literal("button"),label:S,variant:n.enum(["primary","secondary","link"]),action:S,purpose:n.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Ft=n.object({...C,type:n.literal("divider")}).strict(),Zt=n.object({...C,type:n.literal("customer_data"),title:S,data:Ke}).strict(),Gt=n.object({...C,type:n.literal("spacer"),size:jt}).strict(),Ht=n.object({...C,type:n.literal("custom_html"),html:n.record(M,n.string().max(z.customHtml)),css:n.string().max(z.customCss)}).strict(),Kt=n.object({...C,type:n.literal("price"),fallback:S,parts:n.object({current:B.optional(),original:B.optional(),period:B.optional()}).strict().optional()}).strict(),Qt=n.object({...C,type:n.literal("coupon_code"),label:S,fallback:S}).strict(),Wt=n.object({...C,type:n.literal("countdown"),source:n.enum(["offer.ends_at","offer.expires_at","fixed"]),at:n.iso.datetime().optional(),granularity:n.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=n.object({...C,type:n.literal("plan_picker"),label:S,fallback:S,planIds:n.array(n.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:n.string().min(1).max(200).optional(),grouping:qe.safeExtend({monthLabel:S,yearLabel:S,unavailableLabel:S}).optional(),states:n.object({selected:B.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Me(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Xt=n.discriminatedUnion("type",[n.object({type:n.literal("input"),label:S,keyboard:n.enum(["text","email","tel","url"]),maxLength:b(1,500)}).strict(),n.object({type:n.literal("multiselect"),label:S,min:b(0,50),max:b(1,50)}).strict(),n.object({type:n.literal("select"),label:S,defaultIndex:b(0,49),purpose:n.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:B.optional()}).strict(),n.object({type:n.literal("tabs"),label:S,defaultIndex:b(0,49),purpose:n.literal("tier").optional()}).strict(),n.object({type:n.literal("toggle"),label:S,defaultEnabled:n.boolean()}).strict(),n.object({type:n.literal("carousel"),label:S}).strict()]),D={...C,type:n.literal("stack"),direction:n.enum(["vertical","horizontal","overlay"]),align:n.enum(["start","center","end","stretch"]),justify:n.enum(["start","center","end","between"]),productSlot:n.object({index:b(0,19),period:n.enum(["month","year"]).optional(),requireBinding:n.boolean().optional()}).strict().optional(),interaction:Xt.optional(),states:n.object({selected:B.optional()}).strict().optional(),purpose:n.literal("benefits").optional(),purchaseAction:S.optional(),buttonVariant:n.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},tt=n.lazy(()=>n.object({...C,type:D.type,direction:D.direction,align:D.align,justify:D.justify,children:n.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=n.lazy(()=>n.union([tt,Bt,qt,Mt,Ft,Gt,Ht,Kt,Qt,Wt,Yt,Zt])),er=n.union([n.string().max(500),n.number().finite(),n.boolean(),n.null()]),Y={id:S,event:S,properties:n.record(S,er).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},tr=n.discriminatedUnion("type",[n.object({...Y,type:n.literal("navigate"),close:n.literal(!1),pageId:X}).strict(),n.object({...Y,type:n.literal("event"),close:n.boolean()}).strict(),n.object({...Y,type:n.literal("close"),close:n.literal(!0)}).strict(),n.object({...Y,type:n.literal("open_url"),close:n.boolean(),url:Je}).strict(),n.object({...Y,type:n.literal("claim_offer"),close:n.boolean(),couponId:n.uuid()}).strict()]),rr=n.object({defaultLocale:M,locales:n.record(M,n.record(S,n.string().max(z.stringLength)))}).strict(),nr=n.enum(["popup","paywall","onboarding","page"]),Gn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},ir=n.discriminatedUnion("type",[n.object({type:n.literal("modal"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("sheet"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("fullscreen")}).strict()]),Hn={sm:360,md:420,lg:560},or=n.object({kind:n.literal("screen"),schemaVersion:n.literal(Tt),name:n.string().trim().min(1).max(80),surface:nr,initialPageId:X.optional(),presentation:ir,theme:Ye,pages:n.array(n.object({id:X,name:n.string().trim().min(1).max(60),root:tt,theme:Ye.optional(),editorPosition:n.object({x:n.number().finite().min(-1e5).max(1e5),y:n.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:rr,actions:n.array(tr).max(z.actions)}).strict();function G(e,t){for(let r of e.pages)ee(r.root,t)}function Kn(e,t){return{...e,pages:e.pages.map((r,i)=>i===0?{...r,root:t}:r)}}var ar=or.superRefine((e,t)=>{let r=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(y=>y.id===p.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>r.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${r.pages} \u4E2A`}),e.actions.length>r.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${r.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,y)=>{if(g++,y>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>r.nodes&&i(`\u7EC4\u4EF6\u6700\u591A ${r.nodes} \u4E2A`),s&&i(`\u5C42\u7EA7\u6700\u591A ${z.depth} \u5C42`)});function ee(e,t,r=1,i=null){if(t(e,r,i)!==!1&&e.type==="stack")for(let a of e.children)ee(a,t,r+1,e)}function Se(e){let t=[],r=new Set;return G(e,i=>{let a=(c,l,d)=>{r.has(c)||(r.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,r){if(t.field==="html"){let i;return G(e,a=>{a.id===t.nodeId&&a.type==="custom_html"&&(i=a.html[r])}),i}if(t.field==="src"){let i=he(e,t.nodeId);return i?.type==="image"?i.localizedSrc?.[r]??(r===e.strings.defaultLocale?i.src:void 0):void 0}return e.strings.locales[r]?.[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 r=[],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-")))&&r.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 y=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."))&&!y&&r.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"&&y&&y!==h.couponId&&r.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,y))}e.pages.forEach(s=>a(s.root));let c=[],l=ar.safeParse(e);l.success||r.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 y of ce(p))r.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${y}`);G(e,s=>{if(s.type==="customer_data"&&Object.values(e.strings.locales).some(y=>/\{\{|\}\}/.test(y[s.title]??""))&&r.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(y=>Object.values(e.strings.locales).some(h=>h[y]?.includes("{{")))&&!s.fallback&&r.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(y=>y[s.fallback]?.includes("{{"))&&r.push(`\u7EC4\u4EF6 ${s.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),s.type==="custom_html"){for(let y of Object.values(s.html))r.push(...ge(y).map(h=>`HTML ${s.id}\uFF1A${h}`));Object.values(s.html).some(y=>y.includes("{{"))&&!s.fallback&&r.push(`HTML ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(s.css)&&r.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(ae(e),s.bind.picker)&&r.push(`\u5BB9\u5668 ${s.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let s of Object.keys(ae(e)))he(e,s)||r.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?r.push(`\u9ED8\u8BA4\u8BED\u8A00 ${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):r.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))&&r.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:r,warnings:c}}function cr(e){let t=!1;return ee(e,r=>{if(r.hidden)return!1;r.type==="image"&&(t=!0)}),t}function lr(e,t){let r=!1;return ee(e,i=>{if(i.type==="custom_html")for(let a of Object.values(i.html))a.includes(`data-grow-action="${t}"`)&&(r=!0)}),r}function ur(e){return rt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Yn(e,t){return ke(t,ur(e),e.strings.defaultLocale)}function Xn(e,t){let r=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=r[l.key]?.trim()?r[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 r=null;return ee(e,i=>{if(r)return!1;i.id===t&&(r=i)}),r}function he(e,t){for(let r of e.pages){let i=pr(r.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,r){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]=r?.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),r){let c={...i};for(let[l,d]of Object.entries(a))(typeof d=="string"||typeof d=="boolean")&&(c[l]=d);Object.assign(i,Ze(e,c,r))}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(r=>xe(r,t+1)):Object.entries(e).some(([r,i])=>["__proto__","constructor","prototype"].includes(r)||fr.test(r)||xe(i,t+1)))}var gr=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,yr=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[r,i]of new URL(e).searchParams)I.string().max(500).parse(i),Object.hasOwn(t,r)||(t[r]=i);return yr.parse(t),t}var it=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),br=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:br,answers:dr,values:I.record(I.string(),ue).optional()}).strict();export{at as a,O as b,pe as c,Sr as d,xr as e,_r as f,te as g,E as h,st as i,V as j,L as k,Ne as l,ct as m,lt as n,ut as o,Ar as p,M as q,de as r,ke as s,dt as t,Or as u,re as v,Lr as w,Tr as x,ft as y,gt as z,Le as A,jr as B,Ce as C,yt as D,Dr as E,bt as F,Te as G,ht as H,zr as I,Pr 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,bn as ha,Nt as ia,Rt as ja,$e as ka,hn as la,qe as ma,Me as na,Fe as oa,ae as pa,Ze as qa,Ot as ra,fe as sa,Ge as ta,Rn as ua,se as va,ce as wa,On as xa,kn 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,be 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,yr as Mb,ai as Nb,br as Ob,si as Pb};
@@ -0,0 +1 @@
1
+ import{a as N,b as O,c as U}from"./chunk-4K25DELJ.js";function M(n){let c=n.document??document,r=c.defaultView;if(!r)return{destroy(){},checkpoint(e){},retry(){}};let d="indiana:iam:authoring:v2:"+new URL(n.baseUrl).origin+":"+n.environmentId;function m(e){if(e.length>12e3||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))return!1;try{let t=JSON.parse(r.atob(e.split(".")[0].replaceAll("-","+").replaceAll("_","/")));return N(r.location.origin)&&typeof t=="object"&&t!==null&&"version"in t&&"environmentId"in t&&"origin"in t&&t.version===2&&t.environmentId===n.environmentId&&t.origin===r.location.origin}catch{return!1}}let u=!1,f=!1,i=0,o=!1,s="",b,h,y=0,_=!1,l,I=()=>{try{r.sessionStorage.removeItem(d)}catch{}},E=e=>{if(f!==e){f=e;try{n.onAuthoringChange?.(e)}catch{}}},v=e=>{y=e.snapshots,["authorized","idle","capturing","uploading","waiting"].includes(e.state)&&(_=!0),h?.update({...e,reloadRequired:_});try{n.onStatus?.(e)}catch{}c.dispatchEvent(new r.CustomEvent("indiana:iam:status",{detail:e}))};function g(){u||(i++,b?.abort(),l?.destroy("USER_STOPPED"),l=void 0,o=!1,I(),s="",E(!1),c.removeEventListener("indiana:iam:checkpoint",p),v({state:"stopped",reason:"USER_STOPPED",snapshots:y}))}let p=e=>{let t=e instanceof r.CustomEvent?e.detail:void 0,A=t&&typeof t=="object"&&"label"in t?t.label:void 0;if(typeof A=="string"&&/^[\p{L}\p{N} _.-]{1,64}$/u.test(A))try{l?l.checkpoint(A):s&&!o&&R(s)}catch{}};function L(){let e=new URLSearchParams(r.location.hash.slice(1)),t=e.get("indiana-capture");if(!t)return null;m(t)&&E(!0),e.delete("indiana-capture");let A=new URL(r.location.href);return A.hash=e.toString(),r.history.replaceState(r.history.state,"",A),/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t)&&t.length<=12e3?t:null}function R(e){if(u||!m(e))return;let t=++i;b?.abort(),b=new AbortController;let A=b.signal;l?.destroy("REPLACED"),l=void 0,s=e,o=!0,E(!0),c.addEventListener("indiana:iam:checkpoint",p);try{r.sessionStorage.setItem(d,e)}catch{}(async()=>{if(n.controls!==!1&&!h?.active){let{createCaptureControls:w}=await import("./controls-XG46TKUU.js");if(u||t!==i)return;h?.destroy(),h=w({document:c,nonce:n.nonce,retry(){l?l.retry():s&&!o&&R(s)},stop:g,close(){h?.destroy(),h=void 0}})}if(h?.update({state:"connecting",snapshots:0}),!r.navigator.onLine)throw Object.assign(Error("Capture offline"),{code:"OFFLINE"});if(await n.prepare?.(),u||t!==i)return;let a=await fetch(new URL("/api/app-manifest-captures",n.baseUrl),{method:"POST",credentials:"omit",redirect:"error",cache:"no-store",headers:{Authorization:"Bearer "+e,[O]:U,"Content-Type":"application/json"},body:JSON.stringify({action:"authorize"}),signal:AbortSignal.any([A,AbortSignal.timeout(3e4)])});if(a.status!==204||a.headers.get(O)!==U)throw a.body?.cancel().catch(()=>{}),Object.assign(new Error("Capture authorization refused"),{code:a.ok?a.status===204?"CAPTURE_VERSION_MISMATCH":"SERVICE_RESPONSE_INVALID":"AUTH_OR_SERVICE_"+a.status});if(u||t!==i)return;v({state:"authorized",snapshots:0});let{startCapture:S}=await import("./client-F6UPJMHR.js");if(u||t!==i)return;let C=await S({environmentId:n.environmentId,grant:e,baseUrl:n.baseUrl,document:c,signal:A,onStatus(w){u||t!==i||(w.state==="stopped"&&(I(),s="",E(!1),c.removeEventListener("indiana:iam:checkpoint",p)),v(w))}});if(u||t!==i){C.destroy("REPLACED");return}l=C,c.addEventListener("indiana:iam:checkpoint",p)})().catch(a=>{if(!u&&t===i){let S=a instanceof Error&&["TypeError","TimeoutError"].includes(a.name)||a&&typeof a=="object"&&"code"in a&&/^(?:AUTH_OR_SERVICE_(?:408|429|5\d\d)|SERVICE_RESPONSE_INVALID|OFFLINE)$/.test(String(a.code));S||(I(),s="",E(!1),c.removeEventListener("indiana:iam:checkpoint",p));let C=a&&typeof a=="object"&&"code"in a?String(a.code):"",w={state:S?"paused":"stopped",reason:["CAPTURE_VERSION_MISMATCH","AUTH_OR_SERVICE_426"].includes(C)?"CAPTURE_UPGRADE_REQUIRED":C==="OFFLINE"?"OFFLINE":a&&typeof a=="object"&&"code"in a&&a.code==="AUTHORING_CONTROLS_BLOCKED"?"AUTHORING_CONTROLS_BLOCKED":S?"SERVICE_UNAVAILABLE":"AUTH_OR_SERVICE_UNAVAILABLE",snapshots:0};v(w)}}).finally(()=>{t===i&&(o=!1)})}let k=()=>{let e=L();e&&R(e)};r.addEventListener("hashchange",k);try{let e=L()??r.sessionStorage.getItem(d);e&&R(e)}catch{}return{destroy(){u=!0,i++,b?.abort(),l?.destroy(),h?.destroy(),h=void 0,r.removeEventListener("hashchange",k),c.removeEventListener("indiana:iam:checkpoint",p),I(),s="",E(!1)},checkpoint(e){l?l.checkpoint(e):s&&!o&&R(s)},retry(){l?l.retry():s&&!o&&R(s)}}}async function P(n,c,r){let d=new URL(n,c.baseURI),m=c.defaultView?.location.origin,u=/^\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(d.pathname)?.[1];if(!u||d.origin!==m||d.search||d.hash||d.username||d.password)throw Error("Invalid IAM release URL");let f=AbortSignal.any([r,AbortSignal.timeout(2e3)]),i=await fetch(d,{credentials:"omit",redirect:"error",cache:"force-cache",signal:f}),o=i.headers.get("content-length");if(!i.ok||!/^application\/json(?:;|$)/i.test(i.headers.get("content-type")??"")||o!==null&&(!/^\d+$/.test(o)||Number(o)>512))throw i.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let s=i.body?.getReader();if(!s)throw Error("IAM release is unavailable");let b=[],h=0,y=()=>{},_=new Promise((p,L)=>{y=()=>L(Error("IAM release timeout")),f.addEventListener("abort",y,{once:!0}),f.aborted&&y()}),l=!1;try{for(;;){let p=await Promise.race([s.read(),_]);if(p.done){l=!0;break}if(h+=p.value.length,h>512)throw Error("IAM release budget");b.push(p.value)}}finally{f.removeEventListener("abort",y),l||s.cancel().catch(()=>{}),s.releaseLock()}let I=new Uint8Array(h),E=0;for(let p of b)I.set(p,E),E+=p.length;let v=new TextDecoder("utf-8",{fatal:!0}).decode(I),g=JSON.parse(v);if(v.trim()!==JSON.stringify(g))throw Error("Noncanonical IAM release descriptor");if(!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(g,"format")!=="indiana-app-manifest-release"||Reflect.get(g,"schemaVersion")!==2||Reflect.get(g,"releaseId")!==u||!/^[a-f0-9]{64}$/.test(String(Reflect.get(g,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(g,"manifestDigest")}var T=new WeakMap;function x(n,c=document){if(!/^[a-f0-9]{64}$/.test(n))throw new Error("Invalid IAM manifest digest");let r=T.get(c);r||(r=new Map,T.set(c,r));let d="data-indiana-release",m=c.documentElement,u=()=>new Set((m.getAttribute(d)??"").split(/\s+/).filter(Boolean)),f=r.get(n);if(!f){let o=u();f={count:0,owned:!o.has(n)},r.set(n,f),o.add(n),m.setAttribute(d,[...o].join(" "))}f.count++;let i=!1;return{attributes:{indianaAppManifestRelease:n},destroy(){if(!i&&(i=!0,f.count--,!f.count&&(r.delete(n),f.owned))){let o=u();o.delete(n),o.size?m.setAttribute(d,[...o].join(" ")):m.removeAttribute(d)}}}}async function z(n){return(await import("./client-F6UPJMHR.js")).startCapture(n)}export{M as a,P as b,x as c,z as d};
@@ -0,0 +1,17 @@
1
+ function G(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function C(e,t,n){return n===2?G(G(e+t)+"")%1e4/1e4:null}function ae(e){return e<=0?[]:new Array(e).fill(1/e)}function V(e,t){return e>=t[0]&&e<t[1]}function N(e,t){for(let[n,r]of t.entries())if(V(e,r))return n;return-1}function M(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=ae(e);n=n||r,n.length!==e&&(n=r);let o=n.reduce((a,u)=>u+a,0);(o<.99||o>1.01)&&(n=r);let i=0,s=t;return n.map(a=>{let u=i;return i+=a,[u,u+s*a]})}function I(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let i=r.replace(/#.*/,"").split("&").map(s=>s.split("=",2)).filter(([s])=>s===e).map(([,s])=>s===void 0?NaN:parseInt(s))[0];return i!==void 0&&i>=0&&i<n?i:null}function q(e){try{return e()}catch{return!1}}function B(e){return typeof e=="string"?e:JSON.stringify(e)}function p(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function ue(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function W(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let o of t){let i=De(e,o.type,o.pattern);if(o.include===!1){if(i)return!1}else n=!0,i&&(r=!0)}return r||!n}function Ue(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function _e(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((o,i)=>{r.push([e.searchParams.get(i)||"",o,!1])}),!r.some(o=>!Ue(o[0],o[1],o[2]))}catch{return!1}}function De(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let o=ue(n);return o?o.test(r.href)||o.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return _e(r,n);return!1}catch{return!1}}function J(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function H(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function ce(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);H(e.savedGroups??{})}var je=e=>e/2**32|0,Pe=e=>e>>>0;function fe(e,t,n,r){let o=je(n),i=Pe(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function le(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Q=e=>e?`"${e}" `:"";function Ke(e,t=""){if(typeof e!="number")throw new TypeError(Q(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Q(t)+"expected integer >= 0, got "+e);return e}function L(e,t,n=""){if(le(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Ke(t,"length");let r=le(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Q(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}var Ge=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},de=(e,t)=>{Ge(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function X(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function he(e,t){L(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function z(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function U(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function x(e,t){return e<<32-t|e>>>t}var Ne=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Me=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function be(e){if(L(e),Ne)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Me[e[n]];return t}function Ie(e,t,n="opts"){return de(e,"defaults"),t!==void 0&&de(t,n),Object.assign(Object.create(null),e,t)}function pe(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Ie({},t,"info");let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}var ge=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xe(e,t,n){return e&t^~e&n}function ye(e,t,n){return e&t^e&n^t&n}var _=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=U(this.buffer)}update(t){X(this),L(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let u=Math.min(o-this.pos,i-a);if(u===o){let f=U(t);for(;o<=i-a;a+=o)this.process(f,a);s=!0;continue}r.set(a===0&&u===i?t:t.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===o&&(this.process(n,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){X(this),he(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,n.fill(0,s),this.padOffset>o-s&&(this.process(r,0),n.fill(0)),fe(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();let a=t===n?r:U(t),u=this.outputLen,f=u/4,d=this.get();if(u%4||f>d.length)throw new Error("invalid outputLen");for(let c=0;c<f;c++)a.setUint32(4*c,d[c],i)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=s,s&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=new Uint32Array(64),Y=class extends _{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:u}=this;return[t,n,r,o,i,s,a,u]}set(t,n,r,o,i,s,a,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=u|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let c=0;c<16;c++,n+=4)E[c]=t.getUint32(n,!1);for(let c=16;c<64;c++){let h=E[c-15],g=E[c-2],w=x(h,7)^x(h,18)^h>>>3,S=x(g,17)^x(g,19)^g>>>10;E[c]=S+E[c-7]+w+E[c-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:u,G:f,H:d}=this;for(let c=0;c<64;c++){let h=x(a,6)^x(a,11)^x(a,25),g=d+h+xe(a,u,f)+qe[c]+E[c]|0,S=(x(r,2)^x(r,13)^x(r,22))+ye(r,o,i)|0;d=f,f=u,u=a,a=s+g|0,s=i,i=o,o=r,r=g+S|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,u,f,d)}roundClean(){z(E)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),z(this.buffer)}},Z=class extends Y{constructor(){super(32,ke)}};var me=pe(()=>new Z,ge(1));var we=new Map,ee=32,Se=new WeakMap,Ae=new WeakMap;function We(e){return be(me(new TextEncoder().encode(String(e))))}var j=e=>Array.isArray(e)?e.map(j):typeof e=="string"||typeof e=="number"?We(e):null,D=e=>typeof e=="string"?e.toLowerCase():e;function Fe(e){let t=Se.get(e);return t||(t=new Set(e),Se.set(e,t)),t}function Je(e){let t=Ae.get(e);return t||(t=new Set(e.map(D)),Ae.set(e,t)),t}function Qe(e){H(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ee&&Fe(n)}return e}function k(e,t,n,r){n=n||{},r||H(n),r=r||new Set;for(let[o,i]of Object.entries(t))switch(o){case"$or":if(!Te(e,i,n,r))return!1;break;case"$nor":if(Te(e,i,n,r))return!1;break;case"$and":if(!et(e,i,n,r))return!1;break;case"$not":if(k(e,i,n,r))return!1;break;case"$savedGroup":if(!Xe(e,i,n,r))return!1;break;default:if(!O(i,Re(e,o),n,!1,r))return!1}return!0}function Xe(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:o,attributeKey:i}=t;if(typeof o!="string"||r.has(o)||i!==void 0&&typeof i!="string")return!1;let s=n[o];if(!s||Array.isArray(s)||typeof s!="object")return!1;let a=new Set(r).add(o);if(s.type==="list"||s.type==="hashed"){let u=i??s.attributeKey;if(typeof u!="string"||!Array.isArray(s.values))return!1;let f=Re(e,u);return T(s.type==="hashed"?j(f):f,s.values)}return s.type==="condition"?!s.condition||typeof s.condition!="object"?!1:k(e,s.condition,n,a):!1}function Re(e,t){let n=t.split("."),r=e;for(let o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return null;return r}function Ee(e,t=!1){let n=`${e}${t?"/i":""}`,r=we.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),we.set(n,r)),r}function O(e,t,n,r=!1,o=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!Ce(e))return JSON.stringify(t)===JSON.stringify(e);let i=e;for(let s in i)if(!Ze(s,t,i[s],n,o))return!1;return!0}function Ce(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function ze(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function Ye(e,t,n,r){if(!Array.isArray(e))return!1;let o=Ce(t)?i=>O(t,i,n,!1,r):i=>k(i,t,n,r);for(let i=0;i<e.length;i++)if((e[i]??null)!==null&&o(e[i]))return!0;return!1}function T(e,t,n=!1){if(n){let o;if(t.length>=ee){let i=Je(t);o=s=>{let a=D(s);return!(typeof a=="number"&&Number.isNaN(a))&&i.has(a)}}else o=i=>t.some(s=>D(i)===D(s));return Array.isArray(e)?e.some(i=>o(i)):o(e)}let r=t.length>=ee?(o=>i=>o.has(i))(Fe(t)):o=>t.includes(o);return Array.isArray(e)?e.some(o=>r(o)):r(e)}function ve(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Be(e,t,n,r=!1,o=new Set){if(!Array.isArray(e))return!1;for(let i=0;i<t.length;i++){let s=!1;for(let a=0;a<e.length;a++)if(O(t[i],e[a],n,r,o)){s=!0;break}if(!s)return!1}return!0}function Ze(e,t,n,r,o=new Set){let i=t,s=n;switch(e){case"$veq":return p(t)===p(n);case"$vne":return p(t)!==p(n);case"$vgt":return p(t)>p(n);case"$vgte":return p(t)>=p(n);case"$vlt":return p(t)<p(n);case"$vlte":return p(t)<=p(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return i<s;case"$lte":return i<=s;case"$gt":return i>s;case"$gte":return i>=s;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?T(t,n):!1;case"$ini":return Array.isArray(n)?T(t,n,!0):!1;case"$inGroup":{let a=r[n],u=ve(a);return u===null?!1:T(a?.type==="hashed"?j(t):t,u)}case"$notInGroup":{let a=r[n],u=ve(a);return u===null?!1:!T(a?.type==="hashed"?j(t):t,u)}case"$nin":return Array.isArray(n)?!T(t,n):!1;case"$nini":return Array.isArray(n)?!T(t,n,!0):!1;case"$not":return!O(n,t,r,!1,o);case"$size":return Array.isArray(t)?O(n,t.length,r,!1,o):!1;case"$elemMatch":return Ye(t,n,r,o);case"$all":return Array.isArray(n)?Be(t,n,r,!1,o):!1;case"$alli":return Array.isArray(n)?Be(t,n,r,!0,o):!1;case"$regex":try{return Ee(n).test(t)}catch{return!1}case"$regexi":try{return Ee(n,!0).test(t)}catch{return!1}case"$type":return ze(t)===n;default:return!1}}function Te(e,t,n,r){if(!t.length)return!0;for(let o of t)if(k(e,o,n,r))return!0;return!1}function et(e,t,n,r){for(let o of t)if(!k(e,o,n,r))return!1;return!0}function te(e){return ce(e),{context:e,stack:{evaluatedFeatures:new Set}}}function ne(e){return{...e.attributes,...e.attributeOverrides}}function m(e,t,n){let r=t||"id",o="",i=ne(e);return i[r]&&(o=i[r]),!o&&n&&(i[n]&&(o=i[n]),o&&(r=n)),{hashAttribute:r,hashValue:o}}function l(e,t,n){e.context.log?.(t,n)}function $(e,t){return t=t||0,`${e}__${t}`}function P(e,t){return`${e}||${t}`}function tt(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:o,hashValue:i}=m(e,t),s=P(o,B(i)),{hashAttribute:a,hashValue:u}=m(e,n),f=u?P(a,B(u)):null,d={};return f&&r[f]&&Object.assign(d,r[f].assignments||{}),r[s]&&Object.assign(d,r[s].assignments||{}),d}function re({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:o,expMinBucketVersion:i,expMeta:s}){n=n||0,i=i||0,r=r||"id",s=s||[];let a=$(t,n),u=tt(e,r,o);if(i>0)for(let c=0;c<i;c++){let h=$(t,c);if(u[h]!==void 0)return{variation:-1,versionIsBlocked:!0}}let f=u[a];if(f===void 0)return{variation:-1};let d=s.findIndex(c=>c.key===f);return d<0?{variation:-1}:{variation:d}}function oe(e,t,n,r){let o=P(t,n),i=e.stickyBucketAssignmentDocs,s=i&&i[o]?i[o].assignments||{}:{},a={...s,...r},u=JSON.stringify(s)!==JSON.stringify(a);return{key:o,doc:{attributeName:t,attributeValue:n,assignments:a},changed:u}}function nt(e){let t=new Set;return Object.values(e).forEach(n=>{if(n.rules)for(let r of n.rules)r.variations&&(t.add(r.hashAttribute||"id"),r.fallbackAttribute&&t.add(r.fallbackAttribute))}),Array.from(t)}function rt(e,t=e.features||{}){let n={};return nt(t).forEach(r=>{let{hashValue:o}=m(e,r);n[r]=B(o)}),n}function y(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ot(e){return y({...e,parentConditions:e.parentConditions?.map(t=>y(t)),filters:e.filters?.map(t=>y(t)),meta:e.meta?.map(t=>y(t))})}function Ht(e){return y({...e,parentConditions:e.parentConditions?.map(t=>y(t)),filters:e.filters?.map(t=>y(t)),meta:e.meta?.map(t=>y(t)),tracks:e.tracks?.map(t=>({experiment:ot(t.experiment),result:y(t.result)}))})}function st(e,t){let n=te(t),r=Oe(e,null,n);return t.onExperimentEval?.(e,r),r}function it(e,t){return ie(e,te(t))}function at(e){return e.forcedVariations||{}}function Ve(e,t,n){let{context:r}=e;if(r.trackedExperiments){let o=Le(t,n);if(r.trackedExperiments.has(o))return;r.trackedExperiments.add(o)}se(()=>r.onExperimentViewed?.(t,n))}function ut(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let o=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===o)return;r.trackedFeatureUsage[t]=o}se(()=>r.onFeatureUsage?.(t,n))}function se(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ie(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return l(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),v(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let i of r?.rules??[])J(i);let o=n.forcedFeatureValues;if(o&&o.has(e))return l(t,"Global override",{id:e,value:o.get(e)}),v(t,e,o.get(e),"override");if(!r)return l(t,"Unknown feature",{id:e}),v(t,e,null,"unknownFeature");if(r.rules){let i=new Set(t.stack.evaluatedFeatures);e:for(let s of r.rules){if(s.parentConditions)for(let f of s.parentConditions){t.stack.evaluatedFeatures=new Set(i);let d=ie(f.id,t);if(d.source==="cyclicPrerequisite")return v(t,e,null,"cyclicPrerequisite");let c={value:d.value};if(!k(c,f.condition||{},n.savedGroups||{})){if(f.gate)return l(t,"Feature blocked by prerequisite",{id:e,rule:s}),v(t,e,null,"prerequisite");l(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:s});continue e}}if(s.filters&&He(s.filters,t)){l(t,"Skip rule because of filters",{id:e,rule:s});continue}if("force"in s){if(s.condition&&!$e(s.condition,t)){l(t,"Skip rule because of condition ff",{id:e,rule:s});continue}if(!ct(t,s.seed||e,s.hashAttribute,n.saveStickyBucketAssignmentDoc&&!s.disableStickyBucketing?s.fallbackAttribute:void 0,s.range,s.coverage,s.hashVersion)){l(t,"Skip rule because user not included in rollout",{id:e,rule:s});continue}return l(t,"Force value from rule",{id:e,rule:s}),s.tracks&&s.tracks.forEach(f=>{Ve(t,f.experiment,f.result)}),v(t,e,s.force,"force",s.id)}if(!s.variations){l(t,"Skip invalid rule",{id:e,rule:s});continue}let a={variations:s.variations,key:s.key||e};"coverage"in s&&(a.coverage=s.coverage),s.weights&&(a.weights=s.weights),s.hashAttribute&&(a.hashAttribute=s.hashAttribute),s.fallbackAttribute&&(a.fallbackAttribute=s.fallbackAttribute),s.disableStickyBucketing&&(a.disableStickyBucketing=s.disableStickyBucketing),s.bucketVersion!==void 0&&(a.bucketVersion=s.bucketVersion),s.minBucketVersion!==void 0&&(a.minBucketVersion=s.minBucketVersion),s.meta&&(a.meta=s.meta),s.ranges&&(a.ranges=s.ranges),s.name&&(a.name=s.name),s.phase&&(a.phase=s.phase),s.seed&&(a.seed=s.seed),s.hashVersion&&(a.hashVersion=s.hashVersion),s.filters&&(a.filters=s.filters),s.condition&&(a.condition=s.condition);let u=Oe(a,e,t);if(n.onExperimentEval?.(a,u),u.inExperiment&&!u.passthrough)return v(t,e,u.value,"experiment",s.id,a,u)}}return l(t,"Use default value",{id:e,value:r.defaultValue}),v(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Oe(e,t,n){let{context:r}=n;J(e);let o=e.key,i=e.variations.length;if(i<2)return l(n,"Invalid experiment",{id:o}),b(n,e,-1,!1,t);if(r.enabled===!1)return l(n,"Context disabled",{id:o}),b(n,e,-1,!1,t);if(e.urlPatterns&&!W(r.url||"",e.urlPatterns))return l(n,"Skip because of url targeting",{id:o}),b(n,e,-1,!1,t);let s=I(o,r.url||"",i);if(s!==null)return l(n,"Force via querystring",{id:o,variation:s}),b(n,e,s,!1,t);let u=at(r)[o];if(u!==void 0)return l(n,"Force via dev tools",{id:o,variation:u}),b(n,e,u,!1,t);if(e.active===!1)return l(n,"Skip because inactive",{id:o}),b(n,e,-1,!1,t);let{hashAttribute:f,hashValue:d}=m(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return l(n,"Skip because missing hashAttribute",{id:o}),b(n,e,-1,!1,t);let c=-1,h=!1,g=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:A,versionIsBlocked:F}=re(y({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));h=A>=0,c=A,g=!!F}if(!h){if(e.filters&&He(e.filters,n))return l(n,"Skip because of filters",{id:o}),b(n,e,-1,!1,t);if(e.include&&!q(e.include))return l(n,"Skip because of include function",{id:o}),b(n,e,-1,!1,t);if(e.condition&&!$e(e.condition,n))return l(n,"Skip because of condition exp",{id:o}),b(n,e,-1,!1,t);if(e.parentConditions){let A=new Set(n.stack.evaluatedFeatures);for(let F of e.parentConditions){n.stack.evaluatedFeatures=new Set(A);let R=ie(F.id,n);if(R.source==="cyclicPrerequisite")return b(n,e,-1,!1,t);let K={value:R.value};if(!k(K,F.condition||{},r.savedGroups||{}))return l(n,"Skip because prerequisite evaluation fails",{id:o}),b(n,e,-1,!1,t)}}}let w=C(e.seed||o,d,e.hashVersion??2);if(w===null)return l(n,"Skip because of invalid hash version",{id:o}),b(n,e,-1,!1,t);if(!h){let A=e.ranges||M(i,e.coverage===void 0?1:e.coverage,e.weights);c=N(w,A)}if(g)return l(n,"Skip because sticky bucket version is blocked",{id:o}),b(n,e,-1,!1,t,void 0,!0);if(c<0)return l(n,"Skip because of coverage",{id:o}),b(n,e,-1,!1,t);if("force"in e)return l(n,"Force variation",{id:o,variation:e.force}),b(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return l(n,"Skip because QA mode",{id:o}),b(n,e,-1,!1,t);let S=b(n,e,c,!0,t,w,h);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:A,key:F,doc:R}=oe(r,f,B(d),{[$(e.key,e.bucketVersion)]:S.key});if(A){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[F]=R;let K=r.saveStickyBucketAssignmentDoc;se(()=>K(R))}}return Ve(n,e,S),l(n,"In experiment",{id:o,variation:S.variationId}),S}function v(e,t,n,r,o,i,s){let a={value:n,on:!!n,off:!n,source:r,ruleId:o||""};return i&&(a.experiment=i),s&&(a.experimentResult=s),r!=="override"&&ut(e,t,a),a}function $e(e,t){return k(ne(t.context),e,t.context.savedGroups||{})}function He(e,t){return e.some(n=>{let{hashValue:r}=m(t.context,n.attribute);if(!r)return!0;let o=C(n.seed,r,n.hashVersion||2);return o===null?!0:!n.ranges.some(i=>V(o,i))})}function ct(e,t,n,r,o,i,s){if(!o&&i===void 0)return!0;if(!o&&i===0)return!1;let{hashValue:a}=m(e.context,n,r);if(!a)return!1;let u=C(t,a,s??2);return u===null?!1:o?V(u,o):i!==void 0?u<=i:!0}function b(e,t,n,r,o,i,s){let a=!0;(n<0||n>=t.variations.length)&&(n=0,a=!1);let{hashAttribute:u,hashValue:f}=m(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},c=t.variations[0];for(let[g,w]of t.variations.entries())if(g===n){c=w;break}let h={key:d.key||""+n,featureId:o,inExperiment:a,hashUsed:r,variationId:n,value:c,hashAttribute:u,hashValue:f,stickyBucketUsed:!!s};return d.name&&(h.name=d.name),i!==void 0&&(h.bucket=i),d.passthrough&&(h.passthrough=d.passthrough),h}function Le(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
2
+ Copyright (c) 2025 GrowthBook, Inc.
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
5
+ furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all
8
+ copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16
+ SOFTWARE.
17
+ */export{y as a,Ht as b,I as c,B as d,W as e,be as f,me as g,Qe as h,k as i,rt as j,st as k,it as l,Le as m};
@@ -0,0 +1 @@
1
+ import{a as Ie}from"./chunk-QO4YQLZ4.js";import{Ag as _e,Bg as q,Cg as Ae,Dg as Be,Eg as ze,Ek as Ze,Fg as He,Gd as Ue,Ig as $e,Kg as Ke,Pi as De,Yd as ke,Zd as qe,_i as Pe,ae as Ge,bj as Qe,ig as ie,li as fe,ll as We,mj as Ne,ml as Xe,nj as Ye,nl as en,ol as nn,tg as je,vg as H,wg as Je}from"./chunk-467Z5ISI.js";import{b as xe,h as we}from"./chunk-3SONNXFG.js";import{a as ye}from"./chunk-S5TVMQRC.js";import{a as u}from"./chunk-6MO6Y24B.js";import{b as Te}from"./chunk-RRII2DMC.js";import{h as Ve,l as Me}from"./chunk-KQCTDXVD.js";function En(e){let n=null,i=null,t=0,f=0,v=new Set,o=null,s=null,r=new Set,a=()=>{for(let h of r)try{h()}catch{}},p={attributes:Te.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,F)=>{!v.has(h)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(F))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,F)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(F)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function P(h,F=new Set){return v.has(h)?!o||!o.features[h]||["unknownFeature","cyclicPrerequisite"].includes(o.features[h].source):F.has(h)?!1:(F.add(h),(n?.features[h]?.rules??[]).some(T=>[...T.parentConditions??[],...(T.tracks??[]).flatMap(_=>_.experiment.parentConditions??[])].some(_=>P(_.id,F))))}let S=h=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.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=n.features),v.has(h)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?w():structuredClone(o.features[h]??w()):P(h)?w():structuredClone(Me(h,p))};async function C(){if(!n||!v.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let h=f;if(s?.revision===h)return s.loading;let F=t,T=n,_=[...v],D=(async()=>{let L=Ge.parse(await e.evaluateRemote({attributes:structuredClone(p.attributes),features:_}));if(!(F!==t||h!==f||T!==n)){if(e.assertUsable?.(T.generation),L.generation!==T.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(_.some(G=>!Object.hasOwn(L.features,G))||Object.keys(L.features).some(G=>!v.has(G)))throw new Error("Invalid remote Feature results");o=structuredClone(L),p.features={...T.features,...Object.fromEntries(Object.entries(o.features).map(([G,J])=>[G,{defaultValue:J.value}]))},a()}})();s={revision:h,loading:D};try{await D}finally{s?.loading===D&&(s=null)}}function I(){C().catch(h=>{try{e.onError?.(h)}catch{}})}async function U(){if(i)return i;let h=t,F=(async()=>{let T=await e.load(),_="remoteFeatures"in T?ke.parse(T):null,D=_??we.parse(T);if(D.scope.projectId!==e.scope.projectId||D.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===D.generation){let{evaluatedAt:G,expiresAt:J,...se}=n,{evaluatedAt:W,expiresAt:X,...l}=D;if(q(se)!==q(l))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=D.evaluatedAt,n.expiresAt=D.expiresAt,a(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&I(),structuredClone(n)}let L=new Set(_?.remoteFeatures??[]);if([...L].some(G=>Object.hasOwn(D.features,G)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in D&&!n.analyticsConfig.experimentViewsEnabled&&_?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),n=structuredClone(D),v=L,o=null,s=null,f++,p.features=n.features,p.savedGroups=Ve(n.savedGroups),p.trackedFeatureUsage={},a(),I(),structuredClone(n)})();i=F;try{return await F}finally{i===F&&(i=null)}}return{init:U,refresh:U,refreshRemote:C,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(h){return r.add(h),()=>{r.delete(h)}},setAttributes(h){p.attributes=Te.parse(h),f++,o=null,s=null,p.features=n?.features??{},p.trackedFeatureUsage={},a(),I()},evalFeature:S,isOn(h){return S(h).on},isOff(h){return S(h).off},getFeatureValue(h,F){let T=S(h).value;return structuredClone(T===null?F:T)},reset(){t++,f++,i=null,s=null,n=null,o=null,v.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),a()}}}async function be(e,n){let i=$e.parse(n),{artifact:t,environmentId:f}=i.content,v=new URL(e.baseUrl??ye).origin,o=new URL(t.url,v);if(o.origin!==v||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${f}/artifacts/${t.sha256}`)throw new u("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,r=setTimeout(()=>s.abort(),H.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>t.byteLength)throw new u("INVALID_RESPONSE","Public Paywall is unavailable");let p=a.body?.getReader();if(!p)throw new u("INVALID_RESPONSE","Public Paywall body is missing");let w=[],P=0;try{for(;;){let I=await p.read();if(I.done)break;if(P+=I.value.length,P>t.byteLength)throw new u("INVALID_RESPONSE","Public Paywall exceeds its byte limit");w.push(I.value)}}finally{await p.cancel().catch(()=>{})}let S=new Uint8Array(P),C=0;for(let I of w)S.set(I,C),C+=I.length;if(P!==t.byteLength||Ae(S)!==t.sha256)throw new u("INVALID_RESPONSE","Public Paywall digest or size changed");return Ke(i,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(S)))}finally{clearTimeout(r)}}async function Fe(e,n){let{funnelRuntimeDeliverySchema:i}=await import("./src-UHLPVD6E.js"),t=i.safeParse(n);if(!t.success)throw new u("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new u("SCOPE_MISMATCH","Funnel scope changed");return f}function tn(e){let n,i,t=()=>new u("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),f=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw t();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ye).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(r,a=>a.toString(16).padStart(2,"0")).join("")});f.catch(()=>{});async function v(s){try{let r=await f;return await i.request(r,{mode:"exclusive"},()=>s(r))}catch(r){throw r instanceof u?r:t()}}function o(s){let r=n.getItem(s);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let a=JSON.parse(r);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw t();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>v(o),write:(s,r)=>v(a=>{if(o(a).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw t();return n.setItem(a,JSON.stringify({revision:s+1,entry:r})),s+1})}}function Tn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function he(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((f,v)=>he(f,n[v]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),t=Object.entries(n);return i.length===t.length&&i.every(([f,v])=>Object.hasOwn(n,f)&&he(v,Reflect.get(n,f)))}var me=(e,n)=>new u(e,n);function xn(e){return We(e,me)}function pn(e,n,i){return en(e,n,i,me)}async function rn(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new u("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new u("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:f,remoteFeatures:v,...o}=t.growth,s=Ne({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:we.parse(o)});if(e.scope.environmentId!==i.environmentId)throw new u("SCOPE_MISMATCH","Evaluation environment changed");let r=pn(s,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:t.manifest.generation,result:r}}async function on(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new u("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new u("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new u("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:f,remoteFeatures:v,...o}=t.growth,s=Ne({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:we.parse(o)}),r=gn(s,t.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...r,generation:t.manifest.generation,policyRevision:i.policyRevision}}function gn(e,n,i){return nn(e,n,i,me)}import{z as K}from"zod";var an=ie.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new u("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),sn=K.strictObject({schemaVersion:K.literal(1),scope:xe,runId:K.uuid(),funnelId:K.uuid(),versionId:K.uuid(),command:an.optional(),closeCommand:an.refine(e=>e.operation==="close").optional(),purchase:K.strictObject({receiptId:K.uuid(),operationId:K.uuid(),generation:K.number().int().nonnegative()}).optional(),closed:K.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),B=()=>new u("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Oe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function un(e){let n=0,i=null,t=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),f=Promise.resolve();async function v(){let r=await e.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new u("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:sn.parse(r.entry)}}function o(r){let a=f.then(r);return f=a.catch(()=>{}),a}async function s(r){for(let a=0;a<4;a++){let p=await v();if(p.entry&&i!==null&&t(p.entry)!==i)throw B();let w=r(p.entry,p.revision);if(Oe(p.entry,w)){n=p.revision;return}let P=await e.write(p.revision,w);if(P!==null){if(!Number.isSafeInteger(P)||P<=p.revision)throw B();n=P;return}}throw B()}return{bind(r){let a=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(i!==null&&i!==a)throw B();i=a},async load(){let r=await v();return n=r.revision,i=r.entry?t(r.entry):null,r.entry},retain(r){let a=sn.parse(r),p=a.command;return!p||i!==null&&t(a)!==i?Promise.reject(B()):(i??=t(a),o(()=>s((w,P)=>{if(w&&!Oe(t(w),t(a)))throw B();if(!w){if(P!==n&&p.operation!=="close")throw B();return a}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&&!Oe(w.closeCommand,p))throw B();return{...w,closeCommand:p,closed:!0}}if(!Oe(w.command,p))throw B();return w})))},observePurchase(r,a,p){return o(()=>s((w,P)=>{if(!w&&P!==n||w&&t(w)!==t({...r,schemaVersion:1}))throw B();if(w?.purchase&&w.purchase.generation>a.generation)return w;if(w?.purchase&&w.purchase.generation===a.generation&&w.purchase.operationId!==a.operationId)throw B();return p?!w?.purchase||w.purchase.operationId!==a.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...r,...w,purchase:a}}))},settle(r){return o(()=>s(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===r?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===r?{...a,closeCommand:void 0}:a:null))}}}function pe(e){let{customerToken:n,...i}=e;return i}var wn=e=>!(e instanceof u)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function ln(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new u("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new u("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=Ie({...e,...e.serverKey?{fetch:(l,c)=>{let O=new Headers(c?.headers),V=typeof c?.body=="string"?JSON.parse(c.body):null;return V!==null&&typeof V=="object"&&"customerToken"in V&&typeof V.customerToken=="string"&&V.customerToken.length>0||O.set(Qe,e.serverKey),(e.fetch??globalThis.fetch)(l,{...c,headers:O})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,t=null,f=0,v=0,o=null,s=null,r=!1,a=null,p=!1,w=null,P=new Set,S=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?tn(e):void 0),C=S&&un(S),I,U=null,h=!1,F=C?C.load().then(l=>{if(h)throw new u("IDENTITY_CHANGED","Controller was reset during command restoration");if(U=l,!l)return;if(e.scope&&(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment))throw new u("SCOPE_MISMATCH","Pending command belongs to another scope");if(I=l.purchase,r=l.closed===!0,!l.command)return;let c=ie.parse(l.command);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new u("COMMAND_STORAGE_INVALID","Stored mutation required");o=c,l.closeCommand&&(s=l.closeCommand,r=!0),c.operation==="close"&&(r=!0),p=!0}):Promise.resolve();F.catch(()=>{});async function T(l,c,O){let V=f,z=()=>{if(V!==f||h)throw new u("IDENTITY_CHANGED","Run identity changed during the request")};C&&await F,z();let A=t,m=Pe.parse(await Fe(e,await n.request("funnels",ie.parse(l))));if(l.operation==="review"&&!m.review)throw new u("INVALID_RESPONSE","Historical projection is missing");if(z(),m.runToken&&m.runToken!==e.runToken)throw new u("INVALID_RESPONSE","Run credential changed");let ee=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(ee&&m.settlement?.requestId!==ee)throw new u("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(U&&(m.run.id!==U.runId||m.run.source.id!==U.funnelId||m.run.source.versionId!==U.versionId))throw new u("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(t&&(m.run.id!==t.id||m.run.source.type!==t.source.type||m.run.source.id!==t.source.id||m.run.source.versionId!==t.source.versionId||m.run.locale!==t.locale||!he(m.run.parameters,t.parameters)))throw new u("INVALID_RESPONSE","Run version changed");if(e.funnelId&&m.run.source.id!==e.funnelId)throw new u("INVALID_RESPONSE","Run belongs to another Funnel");C?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId}),S&&!e.scope&&(e.scope=m.scope);let $=m.run.paywall,Q=$??m.purchase,ue=Q?.operation,ne=m.settlement&&(!$||$.purchaseRequestId===m.settlement.requestId)&&(!I||I.operationId===m.settlement.operationId)?m.settlement:void 0,te=ue?.operationId??Q?.quote?.operationId??ne?.operationId,ve=Q?.receiptId??ne?.receiptId,Re=$?.selectionGeneration??I?.generation??0;if(C&&te&&ve&&l.operation!=="review"&&(!t||m.run.revision>=t.revision)&&(O===void 0||O>=v)&&(!I||Re>=I.generation)){let le={receiptId:ve,operationId:te,generation:Re},Ee=ue?.status==="complete"||Q?.canReselect===!0;await C.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},le,Ee),z(),Ee?I?.operationId===le.operationId&&(I=void 0):I=le}if(!m.run.stopped&&["running","waiting"].includes(m.run.status)&&l.operation==="get"&&l.settlementRequestId)return m;let re=c?.(m),ge=typeof re=="boolean"?re:re?await re:!1;if(z(),["running","waiting"].includes(m.run.status)||(r=!0),l.operation==="review"&&t&&t!==A&&m.run.revision<=t.revision||t&&m.run.revision===t.revision&&O!==void 0&&O<v||(l.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&t&&m.run.nodeId===t.nodeId&&m.run.visit===t.visit&&m.run.revision===t.revision&&(m.run.screen=t.screen,(t.paywall?.quote?.operationId===m.review?.activeOperationId||!t.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=t.paywall)),t?.paywall&&m.run.paywall&&t.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))return m;if(!t||m.run.revision>=t.revision)t=m.run;else if(!ge)return m;if(t)for(let le of P)try{le(structuredClone(t))}catch{}return m}async function _(l=o){if(C&&await F,!l)throw new u("INVALID_REQUEST","No command is pending");let c=l,O=f;if(C){if(!t||!e.scope)throw new u("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await C.retain({schemaVersion:1,scope:e.scope,runId:t.id,funnelId:t.source.id,versionId:t.source.versionId,command:pe(c)})}if(O!==f||o!==c&&s!==c)throw new u("IDENTITY_CHANGED","Run changed before command dispatch");let V={...c,...i?{customerToken:i}:{}},z=p;p=!0;try{return await T(V,A=>{if(!A.settlement)throw new u("INVALID_RESPONSE","Exact command settlement is missing");if(A.settlement.requestId!==c.requestId)throw new u("INVALID_RESPONSE","Command settlement identity changed");if(O===f&&(o===c||s===c)&&A.run.pendingRequest?.requestId!==c.requestId&&A.settlement.state==="settled"&&(!r||c.operation==="close"||A.settlement?.state==="settled"&&!["running","waiting"].includes(A.run.status))){let m=()=>O!==f||o!==c&&s!==c?!1:(o===c&&(o=null),s===c&&(s=null),p=o!==null,U=null,!0);return C?C.settle(c.requestId).then(m):m()}return!1})}catch(A){throw O===f&&o===c&&!z&&!wn(A)&&(C&&await C.settle(c.requestId),O===f&&o===c&&(o=null,p=!1,U=null)),A}}function D(l){let c=ie.parse(l);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new u("INVALID_REQUEST","Mutation required");if(t?.recoveryRestricted&&c.operation!=="close"&&c.operation!=="resume"&&o?.requestId!==c.requestId)throw new u("PRECONDITION_FAILED","Original Run requires restricted recovery");if(r&&c.operation!=="close"){if(o?.requestId===c.requestId)return X.settle(c.requestId);throw new u("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(c.operation==="close"&&o?.operation!=="close"){if(r=!0,s&&JSON.stringify(pe(s))!==JSON.stringify(pe(c)))throw new u("COMMAND_PENDING","Retry the original Close");if(s??=c,a)return a;let V=_(s);return a=V,V.then(()=>{a===V&&(a=null)},()=>{a===V&&(a=null)}),V}if(o){if(JSON.stringify(pe(o))!==JSON.stringify(pe(c)))throw new u("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else o=c,p=!1;let O=_();return w=O,O.then(()=>{w===O&&(w=null)},()=>{w===O&&(w=null)}),O}let L=null,G=new WeakMap;function J(l){let c=G.get(l);if(c)return c;let O=W(l);return G.set(l,O),O}let se=!1;async function W(l){let c=await l;if(c.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(c.run.instruction?.type??""))return c;if(L)return L;se=!0;let O=f,V=(async()=>{for(let z=0;z<32&&["evaluate","evaluate_segment"].includes(c.run.instruction?.type??"");z++){if(o||r)return c;let A=c.run,m=c.run.instruction;if(m?.type==="evaluate_segment"){let $=await on(e.configuration,A);if(O!==f)throw new u("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o||r)return c;if(t&&(t.revision!==A.revision||t.visit!==A.visit||t.nodeId!==A.nodeId))return T({operation:"get",...i?{customerToken:i}:{}});c=await D({operation:"commit_segment",requestId:De(A.id,A.visit,`segment:${A.revision}`),nodeId:A.nodeId,visit:A.visit,revision:A.revision,...$});continue}if(m?.type!=="evaluate")return c;let ee=await rn(e.configuration,A);if(O!==f)throw new u("IDENTITY_CHANGED","Run identity changed during evaluation");if(o||r)return c;if(t&&(t.revision!==A.revision||t.visit!==A.visit||t.nodeId!==A.nodeId))return T({operation:"get",...i?{customerToken:i}:{}});c=await D({operation:"evaluate",requestId:De(A.id,A.visit,"evaluation"),nodeId:A.nodeId,visit:A.visit,revision:A.revision,receiptId:m.receiptId,policyRevision:m.policyRevision,...ee})}return c})();L=V;try{return await V}finally{L===V&&(L=null)}}let X={get configuration(){return se?e.configuration:void 0},get configurationReady(){return!0},get view(){return t?structuredClone(t):null},get pendingCommand(){let l=s??o;return l?structuredClone(pe(l)):null},get pendingCommands(){return[o,s].filter(l=>l!==null).map(l=>structuredClone(pe(l)))},get pendingPurchase(){return I?structuredClone(I):null},async settle(l){let c=await T({operation:"get",settlementRequestId:l,...i?{customerToken:i}:{}});if(c.settlement?.requestId!==l)throw new u("INVALID_RESPONSE","Exact command settlement is missing");return c.settlement.state==="settled"&&(C&&await C.settle(l),o?.requestId===l&&(o=null,p=!1),s?.requestId===l&&(s=null)),c},get webViewUrl(){return"bundled"},resolvePaywall(l){return be(e,l)},review(l){return T({operation:"review",...l?{receiptId:l}:{},...i?{customerToken:i}:{}},void 0,++v)},async get(l,c){C&&await F,c??=I&&{receiptId:I.receiptId,operationId:I.operationId};let O=++v;return J(T({operation:"get",...l?{data:l}:{},...c?{purchase:c}:{},...i?{customerToken:i}:{}},void 0,O))},resume(l=t?.pendingRequest?.requestId){return l?r?X.settle(l):o?.requestId===l?J(D(o)):J(D({operation:"resume",requestId:l})):Promise.reject(new u("INVALID_REQUEST","No interrupted command is available"))},submit(l){return J(D(l))},retry(){return a||(s?_(s):r&&o?X.settle(o.requestId):w?J(w):o?J(D(o)):Promise.reject(new u("INVALID_REQUEST","No command is pending")))},identify(l){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(l))throw new u("INVALID_TOKEN","Customer credential required");f++,i=l,n.identify(e.runToken)},subscribe(l){return P.add(l),()=>P.delete(l)},reset(){h=!0,f++,i=void 0,t=null,o=null,s=null,a=null,p=!1,w=null,n.reset(),P.clear()}};return X}async function ut(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new u("INVALID_TOKEN","A verified Customer credential is required");let i=Ie(e);i.identify(n.customerToken);let t=fe.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),f=null,v=!1,o=null,s=null,r=null,a=null;async function p(){if(v)throw new u("IDENTITY_CHANGED","Paywall is closed");let S=fe.resolvePaywall,C=S.response.parse(await i.request(S.path,S.request.parse({...t,selector:f?{type:"version",versionId:f.id}:t.selector}))),I={paywall:await be(e,C.paywall)};if(v)throw new u("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?I.paywall.id!==n.paywallVersionId:I.paywall.paywallId!==n.paywallId)throw new u("INVALID_RESPONSE","The requested Paywall changed");if(f&&(I.paywall.id!==f.id||I.paywall.paywallId!==f.paywallId||I.paywall.offering.id!==f.offering.id||I.paywall.content?.artifact.sha256!==f.content?.artifact.sha256))throw new u("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return f=I.paywall,structuredClone(f)}async function w(S){if(!o)throw new u("INVALID_REQUEST","A quoted purchase is required");let C=S==="read"?fe.readSubscriptionOperation:fe.attach,I=C.response.parse(await i.request(C.path,C.request.parse({operationId:o.operationId,...S==="read"?{}:{intent:S}})));if(I.operation.operationId!==o.operationId||I.operation.currency!==t.commerce.currency)throw new u("INVALID_RESPONSE","The purchase operation changed");return s?.status==="complete"&&I.operation.status!=="complete"||s&&s.status!=="pending"&&I.operation.status==="pending"||(s=I.operation),structuredClone(s)}let P={get view(){return f?structuredClone(f):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:p,async preview(S){if(!f)throw new u("INVALID_REQUEST","Load the Paywall first");let C=f.document.buttons[S.actionId];if(C?.type!=="checkout")throw new u("INVALID_REQUEST","Choose an authored purchase action");let I=Ue(C.product,S.selection,f.capabilities);if(!I)throw new u("PRODUCT_UNAVAILABLE","Choose an available Product");let U=fe.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:S.requestId,plans:[{productVersionId:I}],provider:t.commerce.provider,currency:t.commerce.currency,...S.offerId?{offerId:S.offerId}:{},...S.nativeOffer?{nativeOffer:S.nativeOffer}:{}}),h=JSON.stringify(U);if(r&&r!==h&&(!s||s.status==="pending"))throw new u("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(r===h){if(a)return a;if(o)return structuredClone(o)}r=h;let F=(async()=>{let T=fe.previewAttach,_=T.response.parse(await i.request(T.path,U));if(_.quote.currency!==t.commerce.currency||_.quote.provider!==t.commerce.provider||_.quote.lines.length!==1||_.quote.lines[0].productVersionId!==I)throw new u("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return o=_.quote,s=null,structuredClone(o)})();a=F;try{return await F}finally{a===F&&(a=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){v=!0,i.reset(),f=null,o=null,s=null,r=null}};return await p(),P}import{z as vn}from"zod";import{z as Ce}from"zod";var yn=Ce.record(Ce.string().regex(/^[a-f0-9]{64}$/),Ce.strictObject({at:Ce.number(),text:Ce.string()})),cn=2*1048576,In=100;function hn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dn(e,n){let i=n===void 0?hn():n,t=Promise.resolve();async function f(o){if(!i)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>i.getItem(o)),new Promise(r=>{s=setTimeout(()=>r(null),In)})])}catch{return null}finally{clearTimeout(s)}}async function v(){try{let o=await f(`${e}:artifacts`);if(o&&o.length<=cn)return yn.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return f(e)},writeManifest(o){Promise.resolve().then(()=>i?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await v())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=H.retentionMs?s.text:void 0},writeArtifact(o,s){i&&(t=t.catch(()=>{}).then(async()=>{let r=await v(),a=Date.now();r[o]={at:a,text:s};let p={},w=2,P=0;for(let[S,C]of Object.entries(r).sort(([,I],[,U])=>U.at-I.at)){if(C.at>a||a-C.at>H.retentionMs)continue;let I=new TextEncoder().encode(JSON.stringify({[S]:C})).byteLength;w+I>cn||P>=128||(p[S]=C,w+=I,P++)}await i.setItem(`${e}:artifacts`,JSON.stringify(p))}).catch(()=>{}))}}}var E=(e,n)=>new u(e,n),ae=()=>performance.now(),fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function It(e){let n=Je.parse(e.scope),i=new URL(e.origin??ye);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([i.origin,...(e.assetOrigins??[]).map(g=>{let d=new URL(g);if(d.protocol!=="https:"||d.username||d.password||d.search||d.hash||d.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return d.origin})]),f=e.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${n.environmentId}`,o=`indiana:configuration:1:${i.origin}:${q(n)}`,s=dn(o,e.storage),r,a=0,p=0,w=!1,P=!1,S=0,C=0,I,U,h,F,T=0,_=new Set,D=new Set,L=new Map,G=new Map,J=0,se=!1;function W(){for(let g of _)try{g()}catch{}}function X(g){try{e.onError?.(g)}catch{}}let l=()=>!P&&!w&&!!r&&ae()<a&&Date.now()<p;function c(){if(!l())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function O(g,d){let R=new TextEncoder().encode(d).byteLength;if(!L.has(g)){for(;L.size&&(L.size>=128||J+R>H.maxCacheBytes);){let y=L.entries().next().value;J-=new TextEncoder().encode(y[1]).byteLength,L.delete(y[0])}L.set(g,d),J+=R}}async function V(g,d,R){if(Number(g.headers.get("content-length"))>d)throw E("INVALID_RESPONSE","Configuration exceeds its byte limit");let y=g.body?.getReader();if(!y)throw E("INVALID_RESPONSE","Configuration body is missing");let N=[],x=0;try{for(;;){R.throwIfAborted();let M=await y.read();if(M.done)break;if(x+=M.value.length,x>d)throw E("INVALID_RESPONSE","Configuration exceeds its byte limit");N.push(M.value)}}finally{await y.cancel().catch(()=>{})}R.throwIfAborted();let b=new Uint8Array(x),k=0;for(let M of N)b.set(M,k),k+=M.length;return new TextDecoder("utf-8",{fatal:!0}).decode(b)}function z(g){let d=new URL(g,i);if(!t.has(d.origin)||d.username||d.password||d.hash||d.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return d.href}async function A(g,d,R=!1){let y=await f(z(g),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:d,headers:{}});if(y.status===429){let N=y.headers.get("retry-after")??"";T=/^\d+$/.test(N)?Number(N)*1e3:Math.max(0,Date.parse(N)-Date.now())||15e3}if(!y.ok&&y.status!==304)throw E(`CONFIGURATION_HTTP_${y.status}`,"Configuration synchronization failed");return y}function m(g,d,R){let y=Date.parse(g.headers.get("x-indiana-config-validated-at")??""),N=Date.parse(g.headers.get("x-indiana-config-valid-until")??""),x=Date.parse(g.headers.get("date")??""),b=g.headers.get("age"),k=b!==null&&/^\d+(\.\d+)?$/.test(b)?Number(b)*1e3:NaN;if(![y,N,x,k].every(Number.isFinite)||N<=y||N-y>H.maxControlAgeMs||y>x+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let j=Math.min(N-y,R.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(k,x-y,0)-(ae()-d);if(j<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return ae()+j}function ee(){if(clearTimeout(h),clearTimeout(F),P||!_.size)return;l()&&(F=setTimeout(()=>{l()?ee():W()},Math.max(1,a-ae())),fn(F));let g=C?Math.min(15e3,1e3*2**Math.min(C-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);h=setTimeout(()=>{$().catch(X)},Math.max(T,g*(.8+Math.random()*.2))),fn(h)}async function $(){if(P)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(I)return I;let g=S,d=new AbortController;U=d;let R=(async()=>{if(!se){se=!0;try{let Se=await s.readManifest();if(Se&&!r){let Z=_e.parse(JSON.parse(Se));q(Z.scope)===q(n)&&(r=Z)}}catch{}}d.signal.throwIfAborted();let b=r,k=ae(),M=await A(v,d.signal);M.status===304&&(!b||!M.headers.has("x-indiana-config-validated-at")||!M.headers.has("x-indiana-config-valid-until")||!M.headers.has("age"))&&(M=await A(v,d.signal));let j=M.status===304?b:_e.parse(JSON.parse(await V(M,H.maxManifestBytes,d.signal))),{generation:Y,...oe}=j,ce=M.headers.get("etag");if(q(j.scope)!==q(n)||Be(oe)!==Y||ce!==`"${Y}"`&&ce!==`W/"${Y}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(b&&(j.revision<b.revision||j.revision===b.revision&&j.generation!==b.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Se,Z]of Object.entries(b?.funnels??{})){let de=j.funnels[Se];if(de&&(de.controlRevision<Z.controlRevision||de.evaluationRevision<Z.evaluationRevision||de.controlRevision===Z.controlRevision&&de.state!==Z.state||de.evaluationRevision===Z.evaluationRevision&&de.evaluationMode!==Z.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let Le=m(M,k,j.policy);if(d.signal.throwIfAborted(),g!==S)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return r=j,a=Le,p=Date.now()+Math.max(0,Le-ae()),w=!1,C=0,T=0,s.writeManifest(q(j)),W(),structuredClone(j)})(),y=setTimeout(()=>d.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),N=new Promise((b,k)=>d.signal.addEventListener("abort",()=>k(d.signal.reason),{once:!0})),x=Promise.race([R,N]).catch(b=>{throw C++,(b instanceof vn.ZodError||b instanceof SyntaxError||b instanceof u&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(b.code))&&(a=0,w=!0,W()),b}).finally(()=>{clearTimeout(y),I===x&&(I=void 0),ee()});return I=x,x}async function Q(g){let d=g.sha256,R=Y=>new TextEncoder().encode(Y).byteLength===g.byteLength&&Ae(Y)===d;z(g.url);let y=L.get(d);if(y&&R(y))return L.delete(d),L.set(d,y),y;if(G.has(d))return G.get(d);let N=new AbortController;D.add(N);let x=S,b=(async()=>{try{let ce=await s.readArtifact(d);if(ce&&R(ce))return O(d,ce),ce}catch{}N.signal.throwIfAborted();let Y=await A(g.url,N.signal,!0),oe=await V(Y,g.byteLength,N.signal);if(!R(oe))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(P||x!==S)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return O(d,oe),s.writeArtifact(d,oe),oe})(),k=setTimeout(()=>N.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),M=new Promise((Y,oe)=>N.signal.addEventListener("abort",()=>oe(N.signal.reason),{once:!0})),j=Promise.race([b,M]).finally(()=>{clearTimeout(k),D.delete(N),G.delete(d)});return G.set(d,j),j}async function ue(){return l()||await $(),c(),r}async function ne(g){let d,R=new Promise((y,N)=>{d=setTimeout(()=>N(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([g(),R])}finally{clearTimeout(d)}}function te(g,d){if(c(),r?.generation!==g.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(d&&r.funnels[d]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function ve(g){let d=g.gb.features;if(!d)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=g.artifacts[d];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let y=qe.parse(JSON.parse(await Q(R)));if(q(y.scope)!==q({projectId:n.projectId,environment:n.environment})||y.generation!==R.generation||y.remoteFeatures.some(N=>Object.hasOwn(y.features,N)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return te(g),{...y,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-ae())).toISOString()}}async function Re(g,d){let R=await ue();te(R,g);let y=R.funnels[g];if(y.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let N=d??y.currentVersionId,x=y.versions[N];if(!x)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[x.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[b,k]=await Promise.all([Q(R.artifacts[x.artifact]).then(M=>He(JSON.parse(M))),y.evaluationMode==="local"?ve(R):void 0]);if(k&&q(ze(b,k))!==q(x.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return te(R,g),{document:b,growth:k,versionId:N,control:structuredClone(y),manifest:structuredClone(R)}}function re(){w=!0,W(),$().catch(X)}let ge=()=>{(typeof document>"u"||document.visibilityState==="visible")&&re()};function le(g){if(P)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return _.add(g),_.size===1&&(typeof window<"u"&&(window.addEventListener("online",re),window.addEventListener("focus",ge),document.addEventListener("visibilitychange",ge)),ee()),()=>{_.delete(g),_.size||(clearTimeout(h),clearTimeout(F),Ee())}}function Ee(){typeof window<"u"&&(window.removeEventListener("online",re),window.removeEventListener("focus",ge),document.removeEventListener("visibilitychange",ge))}return{scope:Object.freeze({...n}),refresh:$,subscribe:le,assertFresh:c,assertFeatures(g){c();let d=r.gb.features;if(!d)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(g!==void 0&&r.artifacts[d].generation!==g)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return l()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return l()?Math.max(0,a-ae()):0},async features(){return ne(async()=>ve(await ue()))},pageExperiments:()=>ne(async()=>{let g=await ue(),d=g.gb.pageExperiments;if(!d)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=g.artifacts[d];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let y=Ze.parse(JSON.parse(await Q(R)));if(y.environmentId!==n.environmentId||y.generation!==R.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return te(g),y}),funnel:(g,d)=>ne(()=>Re(g,d)),paywall:(g,d)=>ne(async()=>{let R=await ue(),y=R.paywalls?.[g];if(!y||!d&&y.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let N=d??y.currentVersionId,x=y.versions[N],b=x&&R.artifacts[x.artifact];if(!b||b.kind!=="paywall"||b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let k=je.parse(JSON.parse(await Q(b)));return te(R),{document:k,versionId:N,version:x.version,control:structuredClone(y),manifest:structuredClone(R)}}),async localFunnel(g,d){let R=await ne(()=>Re(g,d));if(!R.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:y,remoteFeatures:N,...x}=R.growth;return Ye({scope:{projectId:n.projectId,environment:n.environment},funnelId:g,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:x})},assertFunnel(g,d,R){c();let y=r.funnels[g];if(!y||y.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(y.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Indiana");if(d!==void 0&&y.controlRevision!==d)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!y.versions[R])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!P){P=!0,S++,a=0,U?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(h),clearTimeout(F),Ee(),W(),_.clear();for(let g of D)g.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));L.clear(),J=0}}}}function Et(e,n,i){return Xe(e,n,i,me)}function mn(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new u("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new u("INVALID_TOKEN","A customer credential or server API key is required");let i=Ie({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(t){let f=ie.safeParse({...t,operation:"start"});if(!f.success||f.data.operation!=="start"||(n?f.data.customer!==void 0:f.data.customer===void 0))throw new u("INVALID_REQUEST","Invalid current Funnel start");let v=f.data,o=Pe.safeParse(await Fe(e,await i.request("funnels",v)));if(!o.success||!o.data.runToken)throw new u("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==v.funnelId||s.run.locale!==(v.locale??"en")||!he(s.run.parameters,v.parameters??{})||(v.customer?!s.customerId||v.customer.type==="id"&&s.customerId!==v.customer.value:s.customerId!==void 0))throw new u("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function Dt(e){e={...e};let n=e.configuration;if(!n)throw new u("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&q(i)!==q(e.scope))throw new u("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new u("EVALUATION_MODE","This Funnel uses Remote evaluation");let f=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(f?!e.customerId:e.customerId!==void 0)throw new u("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mn({...e,scope:i,apiKey:e.credential}),o=s=>{let r=ln({...e,scope:i,runToken:s,...f?{serverKey:e.credential}:{}});return f||r.identify(e.credential),r};return{async start(s){let r=await v.start({...s,funnelId:e.funnelId,...f?{customer:{type:"id",value:e.customerId}}:{}}),a=o(r.runToken),p=await a.get();return{...r,...p,controller:a}},async restore(s){let r=o(s),a=await r.get();if(a.run.source.id!==e.funnelId)throw r.reset(),new u("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:s,controller:r}}}}export{En as a,Tn as b,he as c,Fe as d,xn as e,pn as f,gn as g,tn as h,ln as i,ut as j,It as k,Et as l,mn as m,Dt as n};
@@ -0,0 +1 @@
1
+ import{kb as T,lb as C,ob as E}from"./chunk-467Z5ISI.js";import{b as I}from"./chunk-3SONNXFG.js";import{a as k}from"./chunk-S5TVMQRC.js";import{a as t}from"./chunk-6MO6Y24B.js";import{E as N,H as D,K as O,v as A}from"./chunk-HD74AAFS.js";var _={name:"@tinkerlandai/indiana-sdk",version:"0.7.0",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"},"./iam":{types:"./dist/iam.d.ts",import:"./dist/iam.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/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.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@rrweb/types":"2.1.7","@types/css-tree":"^3.2.0",ai:"7.0.136","rrweb-snapshot":"2.1.7",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 F=Symbol("IndianaNoContent");function J(d,j,P=URL){let a=d.scope?I.parse(d.scope):void 0,o=new P(d.baseUrl??k);if(o.username||o.password||o.search||o.hash)throw new t("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new t("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let L=d.fetch??globalThis.fetch.bind(globalThis),p=d.timeoutMs??1e4;if(!Number.isFinite(p)||p<=0||p>12e4)throw new t("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,c=0,l=null,m=new Set;function b(){c+=1,u=null,l=null;for(let i of m)i.abort();m.clear()}async function M(i,U={},v="POST",H={}){if(!u)throw new t("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let g=c,n=new AbortController;m.add(n);let f=()=>g!==c?new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new t("TIMEOUT","Indiana request timed out"),y,q=new Promise((r,s)=>{y=()=>s(f()),n.signal.addEventListener("abort",y,{once:!0})}),K=setTimeout(()=>n.abort(),p),x=async()=>{let r=await L(`${o.href.replace(/\/$/,"")}/api/v1/${i}`,{method:v,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`,[T]:E.current,[C]:_.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(U):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw f();let s;try{s=r.status===204?F:await r.json()}catch{throw n.signal.aborted?f():new t(r.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",r.status,r.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw f();if(g!==c)throw new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!r.ok){let e=D.safeParse(s),w=e.success&&(!A.safeParse(e.data.error.code).success||N(e.data.error.code,r.status)),S=w?e.data.error.code:"HTTP_ERROR",R=O(S,r.status,{retryAfter:r.headers.get("Retry-After"),recovery:w?e.data.error.recovery:void 0,reason:w?e.data.error.reason:void 0});throw new t(S,w?e.data.error.message:"Indiana request failed",r.status,r.headers.get("X-Request-Id")??(e.success?e.data.requestId:void 0),{...R,...e.success&&e.data.error.retryable===!1?{retryable:!1}:{},...R.retryAfterSeconds===void 0&&e.success&&e.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:e.data.error.retryAfterSeconds}:{}})}if(r.headers.get(T)!==E.current)throw new t("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&s&&typeof s=="object"&&"scope"in s){let e=I.safeParse(s.scope);if(!e.success||e.data.projectId!==a.projectId||e.data.environment!==a.environment)throw new t("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let h=r.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new t("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,j?.(l))}return s};try{return await Promise.race([x(),q])}catch(r){throw g!==c?new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):r instanceof t?r:new t(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(K),n.signal.removeEventListener("abort",y),m.delete(n)}}return{subjectKey:()=>l,identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new t("INVALID_TOKEN","A nonempty server-issued token is required");b(),u=i},reset:b,request:M}}export{J as a};
@@ -0,0 +1 @@
1
+ import{a as m,b as j}from"./chunk-KQCTDXVD.js";import{z as e}from"zod";var f=e.json().superRefine((t,a)=>{let r=0;function i(o,s){if(++r>1e4||s>20){a.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof o=="string"&&(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o))&&a.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(o))o.forEach(n=>i(n,s+1));else if(o&&typeof o=="object")for(let[n,c]of Object.entries(o))(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n)||["__proto__","prototype","constructor"].includes(n))&&a.addIssue({code:"custom",message:"Reserved JSON property"}),i(c,s+1)}i(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&a.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),$=e.record(e.string().min(1).max(128),f).superRefine((t,a)=>{(!f.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(r=>Object.hasOwn(t,r)))&&a.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),D=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),h=$.superRefine((t,a)=>{function r(i){if(Array.isArray(i))i.forEach(r);else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i)){if(o==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(s).success&&a.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!o.startsWith("$")&&o.split(".").some(n=>["__proto__","prototype","constructor"].includes(n))&&a.addIssue({code:"custom",message:"Reserved attribute path"}),o.startsWith("$")&&!D.has(o)&&a.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${o}`}),["$regex","$regexi"].includes(o)&&typeof s=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(s)||[...s.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(n=>Number(n[1])>255||Number(n[2]||0)>255)||o==="$regexi"&&/[^\x00-\x7f]/.test(s.replace(/\\u([0-9a-f]{4})/gi,(n,c)=>String.fromCharCode(Number.parseInt(c,16)))))&&a.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(s)}catch{a.addIssue({code:"custom",message:"Invalid regular expression"})}}r(s)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&a.addIssue({code:"custom",message:"Obsolete condition protocol"}),r(t)}),V=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:h}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function C(t){let a=new Set;function r(i){if(Array.isArray(i))i.forEach(r);else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))o==="$savedGroup"&&s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.id=="string"?a.add(s.id):["$inGroup","$notInGroup"].includes(o)&&typeof s=="string"?a.add(s):["$eq","$ne","$in","$nin","$ini","$nini"].includes(o)||r(s)}return r(t),[...a]}var G=e.record(e.uuid(),V).superRefine((t,a)=>{let r=new Set,i=new Set;function o(s){if(r.has(s)){a.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(i.has(s))return;let n=t[s];if(!n){a.addIssue({code:"custom",message:"Missing saved group dependency"});return}r.add(s),n.type==="condition"&&C(n.condition).forEach(o),r.delete(s),i.add(s)}Object.keys(t).forEach(o)}),k=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,a])=>t<=a),A=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(k).min(1).max(100)}),R=e.strictObject({id:e.string().min(1).max(128),condition:h,gate:e.boolean().optional()}),w={id:e.string().max(128).optional(),condition:h.optional(),parentConditions:e.array(R).max(50).optional(),filters:e.array(A).max(20).optional()},B=e.union([e.strictObject({...w}),e.strictObject({...w,force:f,coverage:e.number().min(0).max(1).optional(),range:k.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...w,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),f),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),_=e.strictObject({defaultValue:f,rules:e.array(B).max(100)}),X=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),_).superRefine((t,a)=>{Object.keys(t).length>100&&a.addIssue({code:"custom",message:"Too many Features"});let r=new Set,i=new Set;function o(s){if(r.has(s)){a.addIssue({code:"custom",message:`Cyclic Feature dependency: ${s}`});return}if(i.has(s))return;let n=t[s];if(!n){a.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${s}`});return}r.add(s);for(let c of n.rules)for(let d of c.parentConditions??[])o(d.id);r.delete(s),i.add(s)}Object.keys(t).forEach(o)}),z=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((a,r)=>a+r,0)-1)<=.01),condition:h,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(k).min(1)}).nullable(),seed:e.string().min(1).max(128)}),J=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(z).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,a)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((r,i)=>{if(i===0)return!1;let o=t.phases[i-1];return!o?.dateEnded||Date.parse(r.dateStarted)<Date.parse(o.dateStarted)||Date.parse(o.dateEnded)>Date.parse(r.dateStarted)})||new Set(t.variations.map(r=>r.key)).size!==t.variations.length||new Set(t.variations.map(r=>r.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(r=>r.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(r=>r.dateEnded&&Date.parse(r.dateStarted)>=Date.parse(r.dateEnded)||r.namespace?.ranges.some(([i,o],s,n)=>i>=o||n.some(([c,d],g)=>g!==s&&i<d&&c<o)))||t.phases.some(r=>r.variationWeights.length!==t.variations.length))&&a.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function Y(t,a,r=Date.now()){return Object.fromEntries(Object.entries(t).map(([i,o])=>[i,{defaultValue:o.defaultValue,rules:o.rules.flatMap(s=>{if(!("experimentId"in s))return[j({...s,hashVersion:2})];let n=a[s.experimentId];if(!n)throw new Error(`Missing experiment: ${s.experimentId}`);let c=n.phases.at(-1);if(!c)throw new Error("Experiment requires an active phase");let d=n.statusSchedule?.startAt?Date.parse(n.statusSchedule.startAt):null,g=E(n),F=n.status!=="stopped"&&(n.status==="running"||d!==null&&r>=d)&&(d===null||r>=d)&&(g===null||r<g),{type:M,experimentId:U,values:b,meta:y,...x}=s,p=m({...x,parentConditions:x.parentConditions?.map(u=>m(u)),filters:x.filters?.map(u=>m(u))});if(n.variations.some(u=>!Object.hasOwn(b,u.key))||Object.keys(b).length!==n.variations.length||Object.keys(y??{}).some(u=>!n.variations.some(l=>l.key===u)))throw new Error("Every variation needs a Feature value");let O=u=>{let l=b[u];if(l===void 0)throw new Error("Every variation needs a Feature value");return l},S={$and:[c.condition,...p.condition?[p.condition]:[],...c.savedGroups.map(u=>{let l=u.ids.map(I=>({$savedGroup:{id:I}}));return u.match==="all"?{$and:l}:u.match==="none"?{$nor:l}:{$or:l}})]},v=n.variations.find(u=>u.id===n.releasedVariationId);return v&&!n.excludeFromPayload?y?.[v.key]?.passthrough?[{...p,condition:S}]:[{...p,condition:S,force:O(v.key)}]:[{...p,condition:S,key:n.key,variations:n.variations.map(u=>O(u.key)),meta:n.variations.map(u=>({key:u.key,name:u.name,...m(y?.[u.key]??{})})),weights:c.variationWeights,coverage:F?c.coverage:0,seed:c.seed,hashVersion:2,hashAttribute:n.hashAttribute,...n.fallbackAttribute===null?{}:{fallbackAttribute:n.fallbackAttribute},disableStickyBucketing:!F||n.disableStickyBucketing,bucketVersion:n.bucketVersion,minBucketVersion:n.minBucketVersion,filters:[...p.filters??[],...(n.filters??[]).map(u=>m(u))]}]})}]))}function E(t){if(t.statusSchedule?.stopAt)return Date.parse(t.statusSchedule.stopAt);let a=t.statusSchedule?.stopAfter;if(!a||t.status==="draft"&&!t.statusSchedule?.startAt)return null;let r=t.statusSchedule?.startAt??t.phases.at(-1)?.dateStarted;if(!r)throw new Error("Experiment requires an active phase");return Date.parse(r)+a.value*(a.unit==="days"?864e5:36e5)}function ee(t,a=Date.now()){let r=Object.values(t).filter(i=>i.status!=="stopped"&&!(i.releasedVariationId&&!i.excludeFromPayload)).flatMap(i=>[i.statusSchedule?.startAt?Date.parse(i.statusSchedule.startAt):null,E(i)]).filter(i=>i!==null&&i>a);return r.length?new Date(Math.min(...r)).toISOString():null}var N=J.safeExtend({filters:e.array(A).optional()}),q=e.strictObject({experiments:e.record(e.uuid(),N),savedGroups:G}),P=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),te=e.strictObject({snapshot:q,attributes:$,results:$,stickyBucketAssignmentDocs:e.record(e.string(),P)}),re=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{f as a,$ as b,h as c,V as d,C as e,G as f,B as g,_ as h,X as i,z as j,J as k,Y as l,E as m,ee as n,N as o,q as p,P as q,te as r,re as s};
@@ -0,0 +1 @@
1
+ async function g(e,l,o,h={}){let a=h.message??"Invalid SDK JSON response",c=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||c!==null&&(!/^\d+$/.test(c)||Number(c)>l)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(a);let s=e.body.getReader(),u=[],i=0,b=!1,r=()=>{},f=new Promise((d,n)=>{r=()=>n(Error(a)),o.addEventListener("abort",r,{once:!0}),o.aborted&&r()});try{for(;;){let t=await Promise.race([s.read(),f]);if(t.done){b=!0;break}if(i+=t.value.byteLength,i>l)throw Error(a);u.push(t.value)}let d=new Uint8Array(i),n=0;for(let t of u)d.set(t,n),n+=t.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d))}finally{o.removeEventListener("abort",r),b||s.cancel().catch(()=>{}),s.releaseLock()}}export{g as a};
@@ -0,0 +1,4 @@
1
+ import{a as U}from"./chunk-S5TVMQRC.js";import{e as T,h as I,k as A}from"./chunk-KQCTDXVD.js";function L(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let r of document.cookie.split(";"))if(r.trim().startsWith(`${e}=`))try{t=decodeURIComponent(r.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function C(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function _(e=U){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var y=new Set,E;function $(e){if(y.add(e),!E){let t=history.pushState,r=history.replaceState,n=()=>{for(let c of y)c()},a=function(...c){t.apply(this,c),n()},d=function(...c){r.apply(this,c),n()};history.pushState=a,history.replaceState=d,addEventListener("popstate",n),addEventListener("hashchange",n),E=()=>{history.pushState===a&&(history.pushState=t),history.replaceState===d&&(history.replaceState=r),removeEventListener("popstate",n),removeEventListener("hashchange",n)}}return()=>{y.delete(e),y.size||(E?.(),E=void 0)}}var G=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function Y(e,t){let r=e,n=a=>Number.isInteger(a)&&a>=0;return!!r&&typeof r=="object"&&n(r.inserted)&&n(r.duplicates)&&n(r.skipped)&&Array.isArray(r.rejected)&&r.inserted+r.duplicates+r.skipped+r.rejected.length===t}function D(e){let t=[],r,n=(s,o)=>e.log?.(`${e.label} ${s}`,o);function a(s){r===void 0&&t.length&&(r=setTimeout(()=>{c()},s))}async function d(s){let o;try{o=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:s}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(g){return n("not sent",{error:g}),!1}if(o.status===408||o.status===429||o.status>=500)return n("not sent",{status:o.status}),!1;if(!o.ok)return n("rejected",{status:o.status,events:s.length}),!0;let l;try{l=await o.json()}catch{l=void 0}return Y(l,s.length)?(l.rejected.length&&n("rejected",{rejected:l.rejected}),!0):(n("not acknowledged",{status:o.status}),!1)}function c(){clearTimeout(r),r=void 0;let s=[];for(;t.length&&s.length<20&&(!s.length||G([...s,t[0]].map(o=>o.event))<=65536);)s.push(t.shift());return s.length?d(s.map(o=>o.event)).then(o=>{if(o)return a(1e3);let l=s.filter(g=>++g.attempts<5);l.length<s.length&&n("dropped after retries",{events:s.length-l.length}),t.unshift(...l),a(5e3)}):Promise.resolve()}return{push(s){t.push({event:s,attempts:0}),t.length>=20?c():a(1e3)},flush:c}}/*!
2
+ Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
+ plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
+ */function J(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return t}return r.searchParams.forEach((a,d)=>{n.searchParams.has(d)||n.searchParams.set(d,a)}),n.toString()}function Q(e,t){let r=navigator.userAgent,n=new URLSearchParams(t.search),a={};for(let d of["source","medium","campaign","term","content"]){let c=n.get(`utm_${d}`);c!==null&&(a[`utm${d[0].toUpperCase()}${d.slice(1)}`]=c)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(r)?"edge":/Chrome/.test(r)?"chrome":/Firefox/.test(r)?"firefox":/Safari/.test(r)?"safari":"unknown",deviceType:/Mobi/.test(r)?"mobile":"desktop",...a}}function z(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(a=>Object.hasOwn(n,a))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(a=>!!a&&typeof a.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ee(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=_(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=`${t}/api/v1/page-experiments/${e.environmentId}`,a=L(e.deviceIdCookie??"indiana_did"),d=C(),c=null,s={...e.attributes??{}},o="",l=!1,g=new Map,P=D({endpoint:`${n}/events`,fetch:r,log:e.log,label:"Exposure"}),x=P.flush,f={trackedExperiments:new Set,log:e.log,onExperimentViewed:(i,u)=>{e.trackExposures===!1||c?.trackExposures===!1||P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...d?{sessionId:d}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:u.key})}},j=()=>{f.url=location.href,f.attributes={...Q(a,location),...s}};function O(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let u=new URL(location.href);return i.variations.some(p=>{if(!p.urlRedirect)return!1;let v=new URL(p.urlRedirect);return v.protocol!==u.protocol||v.host!==u.host})}catch{return!0}}function N(i,u){let p=e.configuration?.snapshot?.generation;o=i;let v=e.navigate??(m=>location.replace(m)),M=e.navigateDelay??(e.navigate?0:100),V=e.maxNavigateDelay??1e3;Promise.all([Promise.race([u,new Promise(m=>setTimeout(m,V))]),new Promise(m=>setTimeout(m,M))]).then(()=>{!l&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===p)&&v(i)})}function h(){if(!(!c||l||e.configuration&&!e.configuration.fresh)){j();for(let i of c.experiments){if(O(i)){e.log?.("Auto experiment blocked",{id:i.key});continue}let u;try{u=A(i,f)}catch(p){e.log?.("Skipping page experiment",{id:i.key,error:String(p)});continue}if(g.set(i.key,u),!!u.inExperiment){if(u.value.urlRedirect){let p=i.persistQueryString?J(location.href,u.value.urlRedirect):u.value.urlRedirect;T(p,i.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):p!==o&&N(p,x())}break}}}}let b="",H=()=>{location.href!==b&&(b=location.href,o="",h())},R,S;function B(){R??=$(H),addEventListener("pagehide",k)}let k=()=>{x()};async function w(){let i=e.configuration?null:await r(n,{cache:"no-cache",credentials:"omit"});if(i&&!i.ok)throw new Error(`Page experiments unavailable (${i.status})`);let u=z(e.configuration?await e.configuration.pageExperiments():await i.json());if(u.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");c?.trackExposures===!1&&u.trackExposures&&f.trackedExperiments?.clear(),c=u,f.savedGroups=I(u.savedGroups)}return{async start(){await w(),S??=e.configuration?.subscribe(()=>{!l&&e.configuration?.fresh&&w().then(h).catch(i=>e.log?.("Page configuration unavailable",{error:String(i)}))}),B(),b=location.href,h()},async refresh(){await w(),o="",h()},setAttributes(i){s={...i},h()},getResults(){return new Map(g)},get generation(){return c?.generation??null},destroy(){l=!0,S?.(),R?.(),removeEventListener("pagehide",k),x()}}}export{L as a,C as b,_ as c,$ as d,J as e,Q as f,z as g,ee as h};