@tinkerlandai/indiana-sdk 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -1
- package/README.md +178 -9
- package/README.zh-CN.md +94 -6
- package/THIRD_PARTY_NOTICES.md +0 -1
- package/dist/ai-usage-B4W5m4Ie.d.ts +11102 -0
- package/dist/chunk-4JBIKJMU.js +4 -0
- package/dist/chunk-5TEZEOHX.js +1 -0
- package/dist/chunk-5WY3AXSS.js +1 -0
- package/dist/chunk-HU2HIDVT.js +11 -0
- package/dist/chunk-OHDY27EI.js +1 -0
- package/dist/chunk-OK2Q6IJD.js +1 -0
- package/dist/chunk-PCVQHHEE.js +1 -0
- package/dist/chunk-RMJJOSVZ.js +1 -0
- package/dist/chunk-S2MSIA57.js +17 -0
- package/dist/chunk-S5TVMQRC.js +1 -0
- package/dist/configuration-sync-Bnu8s4pc.d.ts +1314 -0
- package/dist/{customer-page-aZb5Twue.d.ts → customer-page-B4FGCVpt.d.ts} +3 -0
- package/dist/funnel-runtime-host-L3WILUHK.js +1 -0
- package/dist/funnel-runtime-start-Zbd5ro5r.d.ts +30920 -0
- package/dist/{growth-rules-D64pEvg9.d.ts → growth-rules-B4YYy64R.d.ts} +8 -1
- package/dist/index.d.ts +15481 -5669
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +18 -20
- package/dist/page.js +1 -1
- package/dist/paywall-TCE5DE5T.js +1 -0
- package/dist/popup.d.ts +259 -3
- package/dist/popup.js +6 -6
- package/dist/{screen-Keau_Qa2.d.ts → screen-16d-xADb.d.ts} +354 -463
- package/dist/server.d.ts +6 -4
- package/dist/server.js +1 -1
- package/dist/src-VGIVVM27.js +1 -0
- package/dist/visual-editor-agent-WW65CMKW.js +1 -0
- package/dist/visual.d.ts +4 -2
- package/dist/visual.js +1 -1
- package/package.json +3 -2
- package/dist/ai-usage-D9xVKhvu.d.ts +0 -9953
- package/dist/chunk-2UFPTDCV.js +0 -4
- package/dist/chunk-LFNFVYC2.js +0 -1
- package/dist/chunk-PVJKOUNE.js +0 -11
- package/dist/chunk-TZ6REIUE.js +0 -17
- package/dist/chunk-VTSEZ4GI.js +0 -1
- package/dist/funnel-runtime-host-4PQY2MFC.js +0 -1
- package/dist/funnel-runtime-start-B93fV5gJ.d.ts +0 -9165
- package/dist/paywall-M5CIDUIT.js +0 -1
- package/dist/src-XEDJAKEB.js +0 -1
- package/dist/visual-editor-agent-PYMKMPY3.js +0 -1
- /package/dist/{chunk-ZT523F45.js → chunk-BIFEEVQO.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as n,n as i}from"./chunk-S2MSIA57.js";import{z as o}from"zod";var g=o.enum(["sandbox","live"]),p=o.object({projectId:o.string().min(1),environment:g}).strict();import{z as t}from"zod";var s=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([a,u])=>a<=u),x=t.strictObject({attribute:t.string().optional(),seed:t.string(),hashVersion:t.literal(2),ranges:t.array(s).max(100)}),b=t.strictObject({id:t.string().min(1).max(255),condition:i,gate:t.boolean().optional()}),d=t.strictObject({key:t.string().optional(),name:t.string().optional(),passthrough:t.boolean().optional()}),c={condition:i.optional(),parentConditions:t.array(b).max(100).optional(),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),hashAttribute:t.string().optional(),fallbackAttribute:t.string().optional(),hashVersion:t.literal(2).optional(),disableStickyBucketing:t.boolean().optional(),bucketVersion:t.number().int().nonnegative().optional(),minBucketVersion:t.number().int().nonnegative().optional(),filters:t.array(x).max(100).optional(),ranges:t.array(s).max(20).optional(),meta:t.array(d).max(20).optional(),seed:t.string().optional(),name:t.string().optional(),phase:t.string().optional()},r=t.strictObject({...c,key:t.string().min(1).max(255),variations:t.tuple([n,n]).rest(n).refine(a=>a.length<=20),urlPatterns:t.array(t.strictObject({include:t.boolean(),type:t.enum(["regex","simple"]),pattern:t.string()})).max(100).optional(),force:t.number().int().nonnegative().optional(),active:t.boolean().optional(),persistQueryString:t.boolean().optional()}),h=t.strictObject({value:n,variationId:t.number().int(),key:t.string(),name:t.string().optional(),bucket:t.number().optional(),passthrough:t.boolean().optional(),inExperiment:t.boolean(),hashUsed:t.boolean().optional(),hashAttribute:t.string(),hashValue:t.string(),featureId:t.string().nullable(),stickyBucketUsed:t.boolean().optional()}),f=t.strictObject({...c,id:t.string().max(255).optional(),force:n.optional(),variations:t.array(n).min(2).max(20).optional(),key:t.string().optional(),range:s.optional(),tracks:t.array(t.strictObject({experiment:r,result:h})).max(100).optional()}),y=t.strictObject({defaultValue:n.optional(),rules:t.array(f).max(500).optional()}),l=t.record(t.string(),t.union([t.strictObject({type:t.literal("hashed"),attributeKey:t.string(),values:t.array(t.string().regex(/^[a-f0-9]{64}$/))}),t.strictObject({type:t.literal("list"),attributeKey:t.string(),values:t.array(t.union([t.string(),t.number()]))}),t.strictObject({type:t.literal("condition"),condition:i})])),R=t.strictObject({scope:p,generation:t.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}).nullable(),features:t.record(t.string(),y),savedGroups:l,experiments:t.record(t.uuid(),r)});import{z as e}from"zod";var v=e.strictObject({selector:e.string().min(1).max(2048),action:e.enum(["set","append","remove"]),attribute:e.string().min(1).max(128).refine(a=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(a)||/^(aria|data)-[a-z0-9_-]+$/.test(a)),value:e.string().max(5e4).optional(),parentSelector:e.string().max(2048).optional(),insertBeforeSelector:e.string().max(2048).optional()}),S=e.strictObject({variation:e.string().min(1).max(128),description:e.string().max(2e3).default(""),css:e.string().max(1e5).default(""),js:e.string().max(1e5).default(""),domMutations:e.array(v).max(200).default([])}),m=S.omit({variation:!0,description:!0}),j=r.omit({variations:!0,active:!0}).extend({changeId:e.string().regex(/^[a-f0-9]{64}$/),variations:e.tuple([m,m]).rest(m).refine(a=>a.length<=20)}),_=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:e.string().regex(/^[a-f0-9]{64}$/),experiments:e.array(j).max(100),savedGroups:l}),C="__indiana_visual_editor",M=e.object({selector:e.string().max(2048),tag:e.string().max(64),text:e.string().max(1e3),href:e.string().max(2048),src:e.string().max(2048),matches:e.number().int().nonnegative()});export{g as a,p as b,r as c,h as d,f as e,y as f,l as g,R as h,v as i,S as j,m as k,j as l,_ as m,C as n,M as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e}from"./chunk-5TEZEOHX.js";import{a as j}from"./chunk-S5TVMQRC.js";import{kb as T,lb as P,ob as S}from"./chunk-HU2HIDVT.js";import{D as _,G as C,J as k,v as O}from"./chunk-RMJJOSVZ.js";import{b as E}from"./chunk-OHDY27EI.js";var L={name:"@tinkerlandai/indiana-sdk",version:"0.6.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:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/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","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var X=Symbol("IndianaNoContent");function Q(a,V){let v=a.webView??"hosted";if(!["hosted","embedded"].includes(v))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=a.scope?E.parse(a.scope):void 0,s=new URL(a.baseUrl??j);if(s.username||s.password||s.search||s.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let U=a.fetch??globalThis.fetch.bind(globalThis),u=a.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,g,c=0,l=null,f=new Set;function R(){c+=1,p=null,l=null;for(let i of f)i.abort();f.clear()}async function M(i,H={},N="POST",q={}){if(!p)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let I=c,n=new AbortController;f.add(n);let m=()=>I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),y,K=new Promise((t,o)=>{y=()=>o(m()),n.signal.addEventListener("abort",y,{once:!0})}),x=setTimeout(()=>n.abort(),u),F=async()=>{let t=await U(`${s.href.replace(/\/$/,"")}/api/v1/${i}`,{method:N,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:S.current,[P]:L.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:N==="POST"?JSON.stringify(H):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...q.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw m();let o;try{o=t.status===204?X:await t.json()}catch{throw n.signal.aborted?m():new e(t.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",t.status,t.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw m();if(I!==c)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!t.ok){let r=C.safeParse(o),w=r.success&&(!O.safeParse(r.data.error.code).success||_(r.data.error.code,t.status)),A=w?r.data.error.code:"HTTP_ERROR",D=k(A,t.status,{retryAfter:t.headers.get("Retry-After"),recovery:w?r.data.error.recovery:void 0,reason:w?r.data.error.reason:void 0});throw new e(A,w?r.data.error.message:"Indiana request failed",t.status,t.headers.get("X-Request-Id")??(r.success?r.data.requestId:void 0),{...D,...r.success&&r.data.error.retryable===!1?{retryable:!1}:{},...D.retryAfterSeconds===void 0&&r.success&&r.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:r.data.error.retryAfterSeconds}:{}})}if(t.headers.get(T)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&o&&typeof o=="object"&&"scope"in o){let r=E.safeParse(o.scope);if(!r.success||r.data.projectId!==d.projectId||r.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let b=t.headers.get("X-Indiana-Web-View");if(b){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(b))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");g=b}let h=t.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new e("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,V?.(l))}return o};try{return await Promise.race([F(),K])}catch(t){throw I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):t instanceof e?t:new e(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(x),n.signal.removeEventListener("abort",y),f.delete(n)}}return{subjectKey:()=>l,webViewUrl(){if(v!=="embedded"){if(!g)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(g,s).href}},identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");R(),p=i},reset:R,request:M}}export{Q as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as u}from"./chunk-5TEZEOHX.js";import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-HU2HIDVT.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as ue}from"./chunk-S2MSIA57.js";import{z as ct}from"zod";var lt=["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"],k=ct.enum(lt);function pe(e){let t=k.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function Nr(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 Rr(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 kr(e,t,r="en",i={}){let a=k.parse(t.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as I}from"zod";var te=I.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),A=I.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),ut=I.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=A.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ee=I.string().min(1).max(64),V=I.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ne=I.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),z=I.record(Ee,I.union([I.string().max(120),I.number().finite(),I.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)]))),Re=I.record(Ee,I.union([I.string().max(120),I.number().finite(),I.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Z=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},ke=I.array(I.object({upTo:me.nullable(),cost:A}).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&&Z(t.upTo)>Z(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),pt=I.object({key:Ne,match:Re,priority:I.number().int().default(0),cost:A.optional(),tiers:ke.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),mt=I.object({key:Ne,match:Re,factor:me.optional(),add:ut.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"})),dt=I.object({units:me.default("1"),cost:A,tiers:ke.optional(),dimensions:I.array(pt).max(12).optional(),multipliers:I.array(mt).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=Z(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(Ae=>Object.keys(v.match).some(le=>Ae.match[le]!==void 0&&Ae.match[le]!==v.match[le]))))continue;let s=Z(l),p=BigInt("1"),y=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=Z(R.factor??"1"),p*=BigInt("1000000"),y+=Z(R.add??"0"));let h=(s+y*p)*BigInt("1000000"),P=p*c;(h<BigInt("0")||h%P!==BigInt("0")||h/P>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"})}}),zr=dt.safeExtend({featureKey:V});import{z as ft}from"zod";var je=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,U=ft.string().max(16).regex(je,"\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 je.test(c)?c:null}catch{return null}}var gt=new Set(["TW","HK","MO"]);function Oe(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&>.has(c)?"zh-Hant":"zh-Hans"}function ze(e,t,r){let i=t.map(a=>({code:U.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=Oe(c),g=i.filter(p=>Oe(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return r}var yt=[{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 Tr(e){return yt.find(t=>t.code===e)?.label??e}import{z as E}from"zod";var re=E.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"]),Pr=E.enum([...re.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),vr=E.enum([...re.options,"stale_revision"]),bt=E.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"]),ht=E.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Ce={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function $r(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}function xt(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(["TIMEOUT","NETWORK_ERROR","HTTP_ERROR","INVALID_RESPONSE","INVALID_SERVER_RESPONSE"].includes(e))return{retryable:!1,recovery:"recover_operation"};if(e==="NOT_IDENTIFIED"||e==="INVALID_TOKEN")return{retryable:!1,recovery:"authenticate"};if(["INVALID_URL","INVALID_TIMEOUT","SERVER_ONLY","AMBIGUOUS_AUTHENTICATION"].includes(e))return{retryable:!1,recovery:"fix_request"};if(e==="PROTOCOL_MISMATCH")return{retryable:!1,recovery:"upgrade_sdk"};if(e==="IDENTITY_CHANGED")return{retryable:!1,recovery:"reload_state"};if(e==="CAPABILITY_UNAVAILABLE")return{retryable:!1,recovery:"check_availability"};let r=re.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Ce[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Ur(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):Ce[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 St(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 Le=E.object({retryable:E.boolean(),recovery:bt,reason:ht.optional(),retryAfterSeconds:E.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),It=E.object({requestId:E.uuid().optional(),error:E.object({code:E.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:E.string(),...Le.partial().shape})}),Vr=E.object({error:It.shape.error.extend({requestId:E.uuid().optional()})}),Br=E.object({error:E.string(),code:E.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:E.uuid(),...Le.shape});function qr(e,t,r={}){let i=xt(e,t),a=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??i.recovery,c=i.retryable&&r.retryable!==!1&&a!=="recover_operation",l=c?St(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 B=A.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),K=u.string().min(1).max(120),ne=u.enum(["cap","overflow"]),O=(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"))},G=e=>{try{return e()}catch{return!1}},Hr=u.discriminatedUnion("operation",[u.object({operation:u.literal("quote"),overageBehavior:ne.optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:B,properties:z}).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:A,properties:z,idempotencyKey:K}).strict(),u.object({operation:u.literal("reserve"),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:B,properties:z,idempotencyKey:K,expiresInSeconds:u.number().int().min(1).max(86400)}).strict(),u.object({operation:u.literal("confirm"),operationId:u.uuid(),quantity:B,properties:z.optional(),idempotencyKey:K}).strict(),u.object({operation:u.literal("refund"),operationId:u.uuid(),quantity:B,idempotencyKey:K}).strict(),u.object({operation:u.literal("release"),operationId:u.uuid(),idempotencyKey:K}).strict()]),_t=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:A,units:B,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 Te(e,t){let r=e.reduce((i,a)=>i+O(a.units,12),0n)-O(t,12);return e.some(i=>i.funding==="balance")?r>=-100n&&r<=100n:r===0n}var we=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:B,amount:te,pricing:u.array(_t).min(1).max(12)}).strict().refine(e=>G(()=>e.pricing.reduce((t,r)=>t+O(r.units,6),0n)===O(e.units,6)&&e.pricing.reduce((t,r)=>t+O(r.amount,12),0n)===O(e.amount,12)&&e.pricing.every(t=>O(t.unitCost,6)*O(t.units,6)===O(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),u.object({funding:u.literal("postpaid"),invoiceLineId:u.uuid().nullable(),units:B,authorizationId:u.uuid()}).strict()]),ie=u.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Kr=u.object({allowed:u.boolean(),internal_feature_id:u.uuid(),quantity:A,requestedQuantity:A.optional(),overageBehavior:ne.optional(),reason:ie.nullable(),allocations:u.array(we).max(500)}).strict().refine(e=>G(()=>e.allowed?e.reason===null&&Te(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>G(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&O(e.requestedQuantity,6)>=O(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Gr=u.object({id:u.uuid(),internal_feature_id:u.uuid(),kind:u.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:u.uuid().nullable(),quantity:A,requestedQuantity:A.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(we).max(500)}).strict().refine(e=>G(()=>e.accepted?e.reason===null&&Te(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>G(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&O(e.requestedQuantity,6)>=O(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 C}from"zod";var At=C.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Et=C.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),De=C.strictObject({internal_feature_id:C.uuid(),entityId:C.uuid().nullable()}),Xr=De.extend({quantity:A,expectedRevision:C.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:C.string().min(1).max(120),properties:z.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Pe=De.extend({operationId:C.uuid().nullable(),usage:A,capacity:At.nullable(),remaining:Et.nullable(),withinLimit:C.boolean(),revision:C.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:C.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 D=o.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),L=o.iso.datetime({offset:!0}),Nt=o.enum(["access","metered","credit"]),W={internal_feature_id:o.uuid(),key:V,name:o.string().min(1).max(120),kind:Nt},an=o.object({customerId:o.uuid(),snapshotAt:L,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:L,benefitsAppliedAt:L.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:L,endsAt:L.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:D,held:D,debt:D,nextExpiresAt:L.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(),ve=o.enum(["source","usage","transaction","invoice","debt","settlement"]),oe=o.object({at:L,id:o.uuid(),type:ve}).strict(),sn=o.object({type:ve.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"),M={id:o.uuid(),occurredAt:L},Rt=o.discriminatedUnion("type",[o.strictObject({...M,type:o.literal("invoice"),status:o.string().min(1).max(80),paid:D,refunded:D,currency:k,externalId:o.string().nullable()}),o.object({...M,...W,type:o.literal("source"),reason:o.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:D,unlimited:o.boolean(),status:o.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:L,expiresAt:L.nullable(),orderId:o.uuid().nullable(),parentSourceId:o.uuid().nullable()}).strict(),o.object({...M,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:A,accepted:o.boolean(),reason:o.enum([...ie.options,"expired"]).nullable(),properties:z,reservationStatus:o.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:L.nullable(),charges:o.array(o.discriminatedUnion("funding",[o.strictObject({funding:o.literal("balance"),sourceId:o.uuid(),rolloverId:o.uuid().nullable(),units:Q,amount:D}),o.strictObject({funding:o.literal("unbilled"),units:Q}),o.object({...W,funding:o.literal("prepaid"),amount:D}).strict(),o.object({funding:o.literal("postpaid"),invoiceId:o.uuid(),invoiceLineId:o.uuid(),authorizationId:o.uuid(),units:A,currency:k}).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({...M,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:k.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({...M,...W,type:o.literal("debt"),sourceId:o.uuid(),transactionId:o.uuid(),amount:D}).strict(),o.object({...M,...W,type:o.literal("settlement"),sourceId:o.uuid(),debtId:o.uuid(),kind:o.enum(["payment","usage_refund","payment_return"]),amount:D}).strict()]),cn=o.object({customerId:o.uuid(),rows:o.array(Rt).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 F}from"zod";var $e=F.enum(["stripe","apple","google"]),pn=F.enum(["membership","credit_pack","lifetime"]),mn=F.enum(["active","grace","suspended","inactive","revoked"]),dn=F.strictObject({currency:F.string().regex(/^[A-Z]{3}$/),micros:F.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as kt}from"zod";var Ue=kt.object({provider:$e,currency:k}).strict();import{z as S}from"zod";var Ve=S.strictObject({internal_feature_id:S.uuid(),quantity:A.refine(e=>/[1-9]/.test(e)),properties:z,entityId:S.uuid().optional()}),An=S.strictObject({requirement:Ve,commerce:Ue.optional(),paywallId:S.uuid().optional()}),Ot=S.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),jt=S.strictObject({productId:S.string().min(1),productVersionId:S.string().min(1),name:S.string().min(1).max(120),action:S.enum(["purchase","upgrade","addon","topup"]),membershipId:S.string().min(1).nullable(),currency:k,amountMinor:S.string().regex(/^(0|[1-9]\d{0,8})$/),interval:S.enum(["free","week","month","year","one_time"]),intervalCount:S.number().int().min(1).max(156)}),Be=S.strictObject({internal_feature_id:S.string().min(1),name:S.string().min(1).max(120),kind:S.enum(["access","metered","credit"]),quantity:A,allowed:S.boolean(),reason:Ot.nullable(),preview:S.strictObject({scenario:S.enum(["feature_flag","usage_limit"]),candidates:S.array(jt).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"})}),En=S.strictObject({paywallId:S.uuid(),requirement:Ve});import{z as $}from"zod";var qe=$.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ze=$.strictObject({tiers:$.array($.strictObject({id:qe,name:$.string().trim().min(1).max(80)})).min(1).max(8),assignments:$.array($.strictObject({productVersionId:$.string().min(1).max(200),tierId:qe,period:$.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 He(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 P=g.children[g.interaction.defaultIndex];P?.type==="stack"&&!P.hidden&&P.bind?.plan&&y.defaults.push(P.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 zt=["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(),Ke=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:k.optional(),couponId:f.uuid().optional(),offerId:f.uuid().optional(),unavailable:f.boolean().optional(),unavailableReason:f.string().optional(),missing:f.array(f.string()).optional()}).strict(),Ln=f.object({paywall:Be.optional(),nodes:f.record(f.string(),f.object({base:Ke,picker:f.string().optional(),byPlan:f.record(f.string(),Ke).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:k.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=>!zt.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 Tn(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 wn(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 Ct=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Ge=m.enum(Ct),Qe=m.object({source:Ge,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),We=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(),Lt=m.object({key:V,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:m.array(We).max(50),sourceCount:m.number().int().nonnegative(),sourcePage:m.number().int().positive(),hasNextSources:m.boolean(),hasPreviousSources:m.boolean()}).strict(),Tt=m.object({source:Ge,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(Lt).max(500),rows:m.array(We).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(),$n=m.object({nodes:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Tt)}).strict(),Un=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 Vn(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 Ye(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Zn(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:Ye(r),missing:c}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(l,d)=>t[d.trim()]===void 0?l:Ye(t[d.trim()])),missing:c}}import{z as n}from"zod";var wt=4,w={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}$/),x=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dt=n.enum(["none","xs","sm","md","lg","xl"]),Pt=n.enum(["none","sm","md","lg","full"]),ye=n.string().regex(/^#[0-9a-fA-F]{6}$/),et=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([et,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}$/)]),Xe=n.object({primary:ye,background:ye,text:ye,radius:Pt,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),Je=n.union([n.enum(["fit","fill"]),b(1,1200)]),vt=n.object({top:b(0,200),right:b(0,200),bottom:b(0,200),left:b(0,200)}).strict(),$t=n.object({top:b(-100,200),right:b(-100,200),bottom:b(-100,200),left:b(-100,200)}).strict(),tt=n.object({x:b(0,100),y:b(0,100)}).strict(),Ut=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:tt.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()]),Bt=n.object({width:b(0,12),color:J,style:n.enum(["solid","dashed"])}).strict(),qt=n.object({x:b(-40,40),y:b(-40,40),blur:b(0,80),spread:b(-20,40),color:J}).strict(),Zt=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(),q=n.object({width:Je,height:Je,padding:vt,margin:$t,gap:b(0,120),grow:n.union([n.boolean(),n.number().min(0).max(12)]),background:Ut,opacity:n.number().min(0).max(1),clipContent:n.boolean(),shape:Vt,border:Bt,shadow:qt,text:Zt}).strict().partial(),j={id:X,name:n.string().trim().min(1).max(60).optional(),hidden:n.boolean().optional(),style:q.optional(),fallback:x.optional()},Mt=n.object({...j,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:x,variant:n.enum(["title","heading","body","caption"])}).strict(),Ft=n.object({...j,type:n.literal("image"),src:be,localizedSrc:n.record(U,be).optional(),alt:x,aspect:n.enum(["auto","1:1","4:3","16:9","3:1"]),fit:n.enum(["cover","contain"]),position:tt.optional()}).strict(),Ht=n.object({...j,type:n.literal("button"),label:x,variant:n.enum(["primary","secondary","link"]),action:x,purpose:n.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Kt=n.object({...j,type:n.literal("divider")}).strict(),Gt=n.object({...j,type:n.literal("customer_data"),title:x,data:Qe}).strict(),Qt=n.object({...j,type:n.literal("spacer"),size:Dt}).strict(),Wt=n.object({...j,type:n.literal("custom_html"),html:n.record(U,n.string().max(w.customHtml)),css:n.string().max(w.customCss)}).strict(),Yt=n.object({...j,type:n.literal("price"),fallback:x,parts:n.object({current:q.optional(),original:q.optional(),period:q.optional()}).strict().optional()}).strict(),Xt=n.object({...j,type:n.literal("coupon_code"),label:x,fallback:x}).strict(),Jt=n.object({...j,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:x,fallback:x}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),er=n.object({...j,type:n.literal("plan_picker"),label:x,fallback:x,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:Ze.safeExtend({monthLabel:x,yearLabel:x,unavailableLabel:x}).optional(),states:n.object({selected:q.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"})}),tr=n.discriminatedUnion("type",[n.object({type:n.literal("input"),label:x,keyboard:n.enum(["text","email","tel","url"]),maxLength:b(1,500)}).strict(),n.object({type:n.literal("multiselect"),label:x,min:b(0,50),max:b(1,50)}).strict(),n.object({type:n.literal("select"),label:x,defaultIndex:b(0,49),purpose:n.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:q.optional()}).strict(),n.object({type:n.literal("tabs"),label:x,defaultIndex:b(0,49),purpose:n.literal("tier").optional()}).strict(),n.object({type:n.literal("toggle"),label:x,defaultEnabled:n.boolean()}).strict(),n.object({type:n.literal("carousel"),label:x}).strict()]),T={...j,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:tr.optional(),states:n.object({selected:q.optional()}).strict().optional(),purpose:n.literal("benefits").optional(),purchaseAction:x.optional(),buttonVariant:n.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},rt=n.lazy(()=>n.object({...j,type:T.type,direction:T.direction,align:T.align,justify:T.justify,children:n.array(rr).max(w.children),productSlot:T.productSlot,interaction:T.interaction,states:T.states,purpose:T.purpose,purchaseAction:T.purchaseAction,buttonVariant:T.buttonVariant,bind:T.bind}).strict()),rr=n.lazy(()=>n.union([rt,Mt,Ft,Ht,Kt,Qt,Wt,Yt,Xt,Jt,er,Gt])),nr=n.union([n.string().max(500),n.number().finite(),n.boolean(),n.null()]),Y={id:x,event:x,properties:n.record(x,nr).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ir=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:et}).strict(),n.object({...Y,type:n.literal("claim_offer"),close:n.boolean(),couponId:n.uuid()}).strict()]),or=n.object({defaultLocale:U,locales:n.record(U,n.record(x,n.string().max(w.stringLength)))}).strict(),ar=n.enum(["popup","paywall","onboarding","page"]),Xn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},sr=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()]),Jn={sm:360,md:420,lg:560},cr=n.object({kind:n.literal("screen"),schemaVersion:n.literal(wt),name:n.string().trim().min(1).max(80),surface:ar,initialPageId:X.optional(),presentation:sr,theme:Xe,pages:n.array(n.object({id:X,name:n.string().trim().min(1).max(60),root:rt,theme:Xe.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(w.pages),strings:or,actions:n.array(ir).max(w.actions)}).strict();function H(e,t){for(let r of e.pages)ee(r.root,t)}function ei(e,t){return{...e,pages:e.pages.map((r,i)=>i===0?{...r,root:t}:r)}}var lr=cr.superRefine((e,t)=>{let r=w;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>w.locales&&i(`\u6700\u591A ${w.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;H(e,(p,y)=>{if(g++,y>w.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 ${w.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 xe(e){let t=[],r=new Set;return H(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 ur(e,t,r){if(t.field==="html"){let i;return H(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 nt(e){let t=xe(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=>!ur(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 ti(e){return it(e,!0)}function ri(e){return it(e,!1)}function it(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(P=>P.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=lr.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}`);H(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=nt(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`));xe(e).length===0&&!e.pages.some(s=>pr(s.root))&&r.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let g=new Set;H(e,s=>{s.type==="button"&&g.add(s.action)});for(let s of e.actions)!g.has(s.id)&&!e.pages.some(p=>mr(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 pr(e){let t=!1;return ee(e,r=>{if(r.hidden)return!1;r.type==="image"&&(t=!0)}),t}function mr(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 dr(e){return nt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function ni(e,t){return ze(t,dr(e),e.strings.defaultLocale)}function ii(e,t){let r=e.strings.locales[t]??{},i=e.strings.locales[e.strings.defaultLocale]??{},a={};for(let l of xe(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 fr(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=fr(r.root,t);if(i)return i}return null}function oi(e){let t=de(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function ai(e,t,r){let i={};if(!t||typeof t!="object"||Array.isArray(t))return i;let a=t;if(H(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,He(e,c,r))}return i}import{z as Se}from"zod";var gr="[a-f0-9]{64}",ot="[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",yr="[a-zA-Z][a-zA-Z0-9_.-]{0,63}",br="[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?",Ie=new RegExp(`^/web-view/screens/(${gr})/(?:funnel/(${ot})/(${yr})|paywall/(${ot}))/(${br})$`),at=Se.string().max(256).regex(Ie,"Invalid screen render address"),ui=Se.union([at,Se.string().max(512).regex(new RegExp(`^(?:https://[a-z0-9.-]+(?::[0-9]{1,5})?|http://(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?)${Ie.source.slice(1)}`),"Invalid screen render URL")]);function pi(e){let t=e.kind==="funnel"?`/web-view/screens/${e.tag}/funnel/${e.versionId}/${e.screenId}/${e.locale}`:`/web-view/screens/${e.tag}/paywall/${e.versionId}/${e.locale}`;return at.parse(t)}function mi(e){let t=Ie.exec(e);if(!t)return null;let[,r,i,a,c,l]=t;return!r||!l||!U.safeParse(l).success?null:i&&a?{kind:"funnel",tag:r,versionId:i,screenId:a,locale:l}:c?{kind:"paywall",tag:r,versionId:c,locale:l}:null}var di={funnel:e=>`screen-render:funnel:${e}`,funnelVersion:e=>`screen-render:funnel-version:${e}`,paywall:e=>`screen-render:paywall:${e}`,paywallVersion:e=>`screen-render:paywall-version:${e}`};import{z as _}from"zod";var hi=_.discriminatedUnion("kind",[_.object({kind:_.literal("ledger"),cursor:oe}).strict(),_.object({kind:_.literal("billing"),cursor:_.uuid()}).strict()]),hr=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xr=_.record(_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_.union([_.string().max(500),_.boolean(),_.array(_.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),Sr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function _e(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(r=>_e(r,t+1)):Object.entries(e).some(([r,i])=>["__proto__","constructor","prototype"].includes(r)||Sr.test(r)||_e(i,t+1)))}var Ir=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,_r=_.record(hr,ue).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!_e(e)&&!Ir.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function xi(e){let t=Object.create(null);for(let[r,i]of new URL(e).searchParams)_.string().max(500).parse(i),Object.hasOwn(t,r)||(t[r]=i);return _r.parse(t),t}var st=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ar=_.array(_.object({variable:st,componentId:st,required:_.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=_.object({bindings:Ar,answers:xr,values:_.record(_.string(),ue).optional()}).strict();export{lt as a,k as b,pe as c,Nr as d,Rr as e,kr as f,te as g,A as h,ut as i,V as j,z as k,ke as l,pt as m,mt as n,dt as o,zr as p,U as q,de as r,ze as s,yt as t,Tr as u,re as v,Pr as w,vr as x,bt as y,ht as z,Ce as A,$r as B,xt as C,Ur as D,St as E,Le as F,It as G,Vr as H,Br as I,qr as J,ne as K,Hr as L,_t as M,Q as N,we as O,ie as P,Kr as Q,Gr as R,De as S,Xr as T,Pe as U,D as V,an as W,ve as X,oe as Y,sn as Z,Rt as _,cn as $,$e as aa,pn as ba,mn as ca,dn as da,Ue as ea,Ve as fa,An as ga,Ot as ha,jt as ia,Be as ja,En as ka,Ze as la,Me as ma,Fe as na,ae as oa,He as pa,zt as qa,fe as ra,Ke as sa,Ln as ta,se as ua,ce as va,Tn as wa,wn as xa,Ct as ya,Ge as za,Qe as Aa,Tt as Ba,$n as Ca,Un as Da,Vn as Ea,ge as Fa,Ye as Ga,Zn as Ha,wt as Ia,w as Ja,X as Ka,x as La,Dt as Ma,Pt as Na,be as Oa,Xe as Pa,J as Qa,Je as Ra,vt as Sa,$t as Ta,tt as Ua,Ut as Va,Vt as Wa,Bt as Xa,qt as Ya,Zt as Za,q as _a,Mt as $a,Ft as ab,Ht as bb,Kt as cb,Gt as db,Qt as eb,Wt as fb,Yt as gb,Xt as hb,Jt as ib,er as jb,tr as kb,rt as lb,rr as mb,ir as nb,or as ob,ar as pb,Xn as qb,sr as rb,Jn as sb,H as tb,ei as ub,lr as vb,ee as wb,xe as xb,ur as yb,nt as zb,ti as Ab,ri as Bb,dr as Cb,ni as Db,ii as Eb,fr as Fb,he as Gb,oi as Hb,ai as Ib,Ie as Jb,at as Kb,ui as Lb,pi as Mb,mi as Nb,di as Ob,hi as Pb,xr as Qb,_r as Rb,xi as Sb,Ar as Tb,Si as Ub};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
function J(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 j(e,t,n){return n===2?J(J(e+t)+"")%1e4/1e4:null}function be(e){return e<=0?[]:new Array(e).fill(1/e)}function D(e,t){return e>=t[0]&&e<t[1]}function W(e,t){for(let[n,r]of t.entries())if(D(e,r))return n;return-1}function z(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=be(e);n=n||r,n.length!==e&&(n=r);let s=n.reduce((u,c)=>c+u,0);(s<.99||s>1.01)&&(n=r);let i=0,o=t;return n.map(u=>{let c=i;return i+=u,[c,c+o*u]})}function Q(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let i=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return i!==void 0&&i>=0&&i<n?i:null}function X(e){try{return e()}catch{return!1}}function V(e){return typeof e=="string"?e:JSON.stringify(e)}function k(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 ge(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Y(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let s of t){let i=Ze(e,s.type,s.pattern);if(s.include===!1){if(i)return!1}else n=!0,i&&(r=!0)}return r||!n}function Xe(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 Ye(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((s,i)=>{r.push([e.searchParams.get(i)||"",s,!1])}),!r.some(s=>!Xe(s[0],s[1],s[2]))}catch{return!1}}function Ze(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let s=ge(n);return s?s.test(r.href)||s.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Ye(r,n);return!1}catch{return!1}}function Z(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 xe(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);H(e.savedGroups??{})}var et=e=>e/2**32|0,tt=e=>e>>>0;function ye(e,t,n,r){let s=et(n),i=tt(n);e.setUint32(t,r?i:s,r),e.setUint32(t+4,r?s:i,r)}function me(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ee=e=>e?`"${e}" `:"";function nt(e,t=""){if(typeof e!="number")throw new TypeError(ee(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ee(t)+"expected integer >= 0, got "+e);return e}function G(e,t,n=""){if(me(e)&&(t===void 0||e.length===t))return e;t!==void 0&&nt(t,"length");let r=me(e),s=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,o=ee(n)+"expected Uint8Array"+s+", got "+i;throw r?new RangeError(o):new TypeError(o)}var rt=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},ke=(e,t)=>{rt(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 te(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Se(e,t){G(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function ne(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function I(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function A(e,t){return e<<32-t|e>>>t}var st=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ot=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function we(e){if(G(e),st)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ot[e[n]];return t}function it(e,t,n="opts"){return ke(e,"defaults"),t!==void 0&&ke(t,n),Object.assign(Object.create(null),e,t)}function Ae(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=it({},t,"info");let n=(s,i)=>e(i).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}var ve=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ee(e,t,n){return e&t^~e&n}function Fe(e,t,n){return e&t^e&n^t&n}var P=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,s){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(t),this.view=I(this.buffer)}update(t){te(this),G(t);let{view:n,buffer:r,blockLen:s}=this,i=t.length,o=!1;for(let u=0;u<i;){let c=Math.min(s-this.pos,i-u);if(c===s){let l=I(t);for(;s<=i-u;u+=s)this.process(l,u);o=!0;continue}r.set(u===0&&c===i?t:t.subarray(u,u+c),this.pos),this.pos+=c,u+=c,this.pos===s&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){te(this),Se(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:s,isLE:i}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>s-o&&(this.process(r,0),n.fill(0)),ye(r,s-8,this.length*8,i),this.process(r,0),this.roundClean();let u=t===n?r:I(t),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let f=0;f<l;f++)u.setUint32(4*f,d[f],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:s,destroyed:i,pos:o}=this;return t.destroyed=i,t.finished=s,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},$e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var at=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]),R=new Uint32Array(64),re=class extends P{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:s,E:i,F:o,G:u,H:c}=this;return[t,n,r,s,i,o,u,c]}set(t,n,r,s,i,o,u,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=u|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let f=0;f<16;f++,n+=4)R[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let b=R[f-15],y=R[f-2],S=A(b,7)^A(b,18)^b>>>3,w=A(y,17)^A(y,19)^y>>>10;R[f]=w+R[f-7]+S+R[f-16]|0}let{A:r,B:s,C:i,D:o,E:u,F:c,G:l,H:d}=this;for(let f=0;f<64;f++){let b=A(u,6)^A(u,11)^A(u,25),y=d+b+Ee(u,c,l)+at[f]+R[f]|0,w=(A(r,2)^A(r,13)^A(r,22))+Fe(r,s,i)|0;d=l,l=c,c=u,u=o+y|0,o=i,i=s,s=r,r=y+w|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,s,i,o,u,c,l,d)}roundClean(){ne(R)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ne(this.buffer)}},se=class extends re{constructor(){super(32,$e)}};var Oe=Ae(()=>new se,ve(1));var Re=new Map,oe=32,Be=new WeakMap,Ce=new WeakMap;function ut(e){return we(Oe(new TextEncoder().encode(String(e))))}var N=e=>Array.isArray(e)?e.map(N):typeof e=="string"||typeof e=="number"?ut(e):null,K=e=>typeof e=="string"?e.toLowerCase():e;function Ue(e){let t=Be.get(e);return t||(t=new Set(e),Be.set(e,t)),t}function ct(e){let t=Ce.get(e);return t||(t=new Set(e.map(K)),Ce.set(e,t)),t}function Le(e){H(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=oe&&Ue(n)}return e}function v(e,t,n,r){n=n||{},r||H(n),r=r||new Set;for(let[s,i]of Object.entries(t))switch(s){case"$or":if(!De(e,i,n,r))return!1;break;case"$nor":if(De(e,i,n,r))return!1;break;case"$and":if(!pt(e,i,n,r))return!1;break;case"$not":if(v(e,i,n,r))return!1;break;case"$savedGroup":if(!ft(e,i,n,r))return!1;break;default:if(!U(i,_e(e,s),n,!1,r))return!1}return!0}function ft(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:s,attributeKey:i}=t;if(typeof s!="string"||r.has(s)||i!==void 0&&typeof i!="string")return!1;let o=n[s];if(!o||Array.isArray(o)||typeof o!="object")return!1;let u=new Set(r).add(s);if(o.type==="list"||o.type==="hashed"){let c=i??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let l=_e(e,c);return T(o.type==="hashed"?N(l):l,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:v(e,o.condition,n,u):!1}function _e(e,t){let n=t.split("."),r=e;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return null;return r}function Ve(e,t=!1){let n=`${e}${t?"/i":""}`,r=Re.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Re.set(n,r)),r}function U(e,t,n,r=!1,s=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)||!He(e))return JSON.stringify(t)===JSON.stringify(e);let i=e;for(let o in i)if(!ht(o,t,i[o],n,s))return!1;return!0}function He(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function lt(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 dt(e,t,n,r){if(!Array.isArray(e))return!1;let s=He(t)?i=>U(t,i,n,!1,r):i=>v(i,t,n,r);for(let i=0;i<e.length;i++)if((e[i]??null)!==null&&s(e[i]))return!0;return!1}function T(e,t,n=!1){if(n){let s;if(t.length>=oe){let i=ct(t);s=o=>{let u=K(o);return!(typeof u=="number"&&Number.isNaN(u))&&i.has(u)}}else s=i=>t.some(o=>K(i)===K(o));return Array.isArray(e)?e.some(i=>s(i)):s(e)}let r=t.length>=oe?(s=>i=>s.has(i))(Ue(t)):s=>t.includes(s);return Array.isArray(e)?e.some(s=>r(s)):r(e)}function Te(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function je(e,t,n,r=!1,s=new Set){if(!Array.isArray(e))return!1;for(let i=0;i<t.length;i++){let o=!1;for(let u=0;u<e.length;u++)if(U(t[i],e[u],n,r,s)){o=!0;break}if(!o)return!1}return!0}function ht(e,t,n,r,s=new Set){let i=t,o=n;switch(e){case"$veq":return k(t)===k(n);case"$vne":return k(t)!==k(n);case"$vgt":return k(t)>k(n);case"$vgte":return k(t)>=k(n);case"$vlt":return k(t)<k(n);case"$vlte":return k(t)<=k(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return i<o;case"$lte":return i<=o;case"$gt":return i>o;case"$gte":return i>=o;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 u=r[n],c=Te(u);return c===null?!1:T(u?.type==="hashed"?N(t):t,c)}case"$notInGroup":{let u=r[n],c=Te(u);return c===null?!1:!T(u?.type==="hashed"?N(t):t,c)}case"$nin":return Array.isArray(n)?!T(t,n):!1;case"$nini":return Array.isArray(n)?!T(t,n,!0):!1;case"$not":return!U(n,t,r,!1,s);case"$size":return Array.isArray(t)?U(n,t.length,r,!1,s):!1;case"$elemMatch":return dt(t,n,r,s);case"$all":return Array.isArray(n)?je(t,n,r,!1,s):!1;case"$alli":return Array.isArray(n)?je(t,n,r,!0,s):!1;case"$regex":try{return Ve(n).test(t)}catch{return!1}case"$regexi":try{return Ve(n,!0).test(t)}catch{return!1}case"$type":return lt(t)===n;default:return!1}}function De(e,t,n,r){if(!t.length)return!0;for(let s of t)if(v(e,s,n,r))return!0;return!1}function pt(e,t,n,r){for(let s of t)if(!v(e,s,n,r))return!1;return!0}function ie(e){return xe(e),{context:e,stack:{evaluatedFeatures:new Set}}}function ae(e){return{...e.attributes,...e.attributeOverrides}}function $(e,t,n){let r=t||"id",s="",i=ae(e);return i[r]&&(s=i[r]),!s&&n&&(i[n]&&(s=i[n]),s&&(r=n)),{hashAttribute:r,hashValue:s}}function h(e,t,n){e.context.log?.(t,n)}function L(e,t){return t=t||0,`${e}__${t}`}function M(e,t){return`${e}||${t}`}function bt(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:s,hashValue:i}=$(e,t),o=M(s,V(i)),{hashAttribute:u,hashValue:c}=$(e,n),l=c?M(u,V(c)):null,d={};return l&&r[l]&&Object.assign(d,r[l].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function ue({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:s,expMinBucketVersion:i,expMeta:o}){n=n||0,i=i||0,r=r||"id",o=o||[];let u=L(t,n),c=bt(e,r,s);if(i>0)for(let f=0;f<i;f++){let b=L(t,f);if(c[b]!==void 0)return{variation:-1,versionIsBlocked:!0}}let l=c[u];if(l===void 0)return{variation:-1};let d=o.findIndex(f=>f.key===l);return d<0?{variation:-1}:{variation:d}}function ce(e,t,n,r){let s=M(t,n),i=e.stickyBucketAssignmentDocs,o=i&&i[s]?i[s].assignments||{}:{},u={...o,...r},c=JSON.stringify(o)!==JSON.stringify(u);return{key:s,doc:{attributeName:t,attributeValue:n,assignments:u},changed:c}}function gt(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 xt(e,t=e.features||{}){let n={};return gt(t).forEach(r=>{let{hashValue:s}=$(e,r);n[r]=V(s)}),n}function x(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function yt(e){return x({...e,parentConditions:e.parentConditions?.map(t=>x(t)),filters:e.filters?.map(t=>x(t)),meta:e.meta?.map(t=>x(t))})}function Ge(e){return x({...e,parentConditions:e.parentConditions?.map(t=>x(t)),filters:e.filters?.map(t=>x(t)),meta:e.meta?.map(t=>x(t)),tracks:e.tracks?.map(t=>({experiment:yt(t.experiment),result:x(t.result)}))})}function Ie(e,t){let n=ie(t),r=Ne(e,null,n);return t.onExperimentEval?.(e,r),r}function Pe(e,t){return le(e,ie(t))}function mt(e){return e.forcedVariations||{}}function Ke(e,t,n){let{context:r}=e;if(r.trackedExperiments){let s=Je(t,n);if(r.trackedExperiments.has(s))return;r.trackedExperiments.add(s)}fe(()=>r.onExperimentViewed?.(t,n))}function kt(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let s=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===s)return;r.trackedFeatureUsage[t]=s}fe(()=>r.onFeatureUsage?.(t,n))}function fe(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function le(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return h(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),B(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let i of r?.rules??[])Z(i);let s=n.forcedFeatureValues;if(s&&s.has(e))return h(t,"Global override",{id:e,value:s.get(e)}),B(t,e,s.get(e),"override");if(!r)return h(t,"Unknown feature",{id:e}),B(t,e,null,"unknownFeature");if(r.rules){let i=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let l of o.parentConditions){t.stack.evaluatedFeatures=new Set(i);let d=le(l.id,t);if(d.source==="cyclicPrerequisite")return B(t,e,null,"cyclicPrerequisite");let f={value:d.value};if(!v(f,l.condition||{},n.savedGroups||{})){if(l.gate)return h(t,"Feature blocked by prerequisite",{id:e,rule:o}),B(t,e,null,"prerequisite");h(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&qe(o.filters,t)){h(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Me(o.condition,t)){h(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!St(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){h(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return h(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(l=>{Ke(t,l.experiment,l.result)}),B(t,e,o.force,"force",o.id)}if(!o.variations){h(t,"Skip invalid rule",{id:e,rule:o});continue}let u={variations:o.variations,key:o.key||e};"coverage"in o&&(u.coverage=o.coverage),o.weights&&(u.weights=o.weights),o.hashAttribute&&(u.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(u.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(u.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(u.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(u.minBucketVersion=o.minBucketVersion),o.meta&&(u.meta=o.meta),o.ranges&&(u.ranges=o.ranges),o.name&&(u.name=o.name),o.phase&&(u.phase=o.phase),o.seed&&(u.seed=o.seed),o.hashVersion&&(u.hashVersion=o.hashVersion),o.filters&&(u.filters=o.filters),o.condition&&(u.condition=o.condition);let c=Ne(u,e,t);if(n.onExperimentEval?.(u,c),c.inExperiment&&!c.passthrough)return B(t,e,c.value,"experiment",o.id,u,c)}}return h(t,"Use default value",{id:e,value:r.defaultValue}),B(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ne(e,t,n){let{context:r}=n;Z(e);let s=e.key,i=e.variations.length;if(i<2)return h(n,"Invalid experiment",{id:s}),g(n,e,-1,!1,t);if(r.enabled===!1)return h(n,"Context disabled",{id:s}),g(n,e,-1,!1,t);if(e.urlPatterns&&!Y(r.url||"",e.urlPatterns))return h(n,"Skip because of url targeting",{id:s}),g(n,e,-1,!1,t);let o=Q(s,r.url||"",i);if(o!==null)return h(n,"Force via querystring",{id:s,variation:o}),g(n,e,o,!1,t);let c=mt(r)[s];if(c!==void 0)return h(n,"Force via dev tools",{id:s,variation:c}),g(n,e,c,!1,t);if(e.active===!1)return h(n,"Skip because inactive",{id:s}),g(n,e,-1,!1,t);let{hashAttribute:l,hashValue:d}=$(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return h(n,"Skip because missing hashAttribute",{id:s}),g(n,e,-1,!1,t);let f=-1,b=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:m,versionIsBlocked:E}=ue(x({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));b=m>=0,f=m,y=!!E}if(!b){if(e.filters&&qe(e.filters,n))return h(n,"Skip because of filters",{id:s}),g(n,e,-1,!1,t);if(e.include&&!X(e.include))return h(n,"Skip because of include function",{id:s}),g(n,e,-1,!1,t);if(e.condition&&!Me(e.condition,n))return h(n,"Skip because of condition exp",{id:s}),g(n,e,-1,!1,t);if(e.parentConditions){let m=new Set(n.stack.evaluatedFeatures);for(let E of e.parentConditions){n.stack.evaluatedFeatures=new Set(m);let F=le(E.id,n);if(F.source==="cyclicPrerequisite")return g(n,e,-1,!1,t);let C={value:F.value};if(!v(C,E.condition||{},r.savedGroups||{}))return h(n,"Skip because prerequisite evaluation fails",{id:s}),g(n,e,-1,!1,t)}}}let S=j(e.seed||s,d,e.hashVersion??2);if(S===null)return h(n,"Skip because of invalid hash version",{id:s}),g(n,e,-1,!1,t);if(!b){let m=e.ranges||z(i,e.coverage===void 0?1:e.coverage,e.weights);f=W(S,m)}if(y)return h(n,"Skip because sticky bucket version is blocked",{id:s}),g(n,e,-1,!1,t,void 0,!0);if(f<0)return h(n,"Skip because of coverage",{id:s}),g(n,e,-1,!1,t);if("force"in e)return h(n,"Force variation",{id:s,variation:e.force}),g(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return h(n,"Skip because QA mode",{id:s}),g(n,e,-1,!1,t);let w=g(n,e,f,!0,t,S,b);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:m,key:E,doc:F}=ce(r,l,V(d),{[L(e.key,e.bucketVersion)]:w.key});if(m){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[E]=F;let C=r.saveStickyBucketAssignmentDoc;fe(()=>C(F))}}return Ke(n,e,w),h(n,"In experiment",{id:s,variation:w.variationId}),w}function B(e,t,n,r,s,i,o){let u={value:n,on:!!n,off:!n,source:r,ruleId:s||""};return i&&(u.experiment=i),o&&(u.experimentResult=o),r!=="override"&&kt(e,t,u),u}function Me(e,t){return v(ae(t.context),e,t.context.savedGroups||{})}function qe(e,t){return e.some(n=>{let{hashValue:r}=$(t.context,n.attribute);if(!r)return!0;let s=j(n.seed,r,n.hashVersion||2);return s===null?!0:!n.ranges.some(i=>D(s,i))})}function St(e,t,n,r,s,i,o){if(!s&&i===void 0)return!0;if(!s&&i===0)return!1;let{hashValue:u}=$(e.context,n,r);if(!u)return!1;let c=j(t,u,o??2);return c===null?!1:s?D(c,s):i!==void 0?c<=i:!0}function g(e,t,n,r,s,i,o){let u=!0;(n<0||n>=t.variations.length)&&(n=0,u=!1);let{hashAttribute:c,hashValue:l}=$(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},f=t.variations[0];for(let[y,S]of t.variations.entries())if(y===n){f=S;break}let b={key:d.key||""+n,featureId:s,inExperiment:u,hashUsed:r,variationId:n,value:f,hashAttribute:c,hashValue:l,stickyBucketUsed:!!o};return d.name&&(b.name=d.name),i!==void 0&&(b.bucket=i),d.passthrough&&(b.passthrough=d.passthrough),b}function Je(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
|
+
*/import{z as a}from"zod";var _=a.json().superRefine((e,t)=>{let n=0;function r(s,i){if(++n>1e4||i>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof s=="string"&&(s.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(s))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(s))s.forEach(o=>r(o,i+1));else if(s&&typeof s=="object")for(let[o,u]of Object.entries(s))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(u,i+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),he=a.record(a.string().min(1).max(128),_).superRefine((e,t)=>{(!_.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),wt=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"]),q=he.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[s,i]of Object.entries(r)){if(s==="$savedGroup"&&!a.strictObject({id:a.uuid(),attributeKey:a.string().min(1).max(128).optional()}).safeParse(i).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!s.startsWith("$")&&s.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),s.startsWith("$")&&!wt.has(s)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${s}`}),["$regex","$regexi"].includes(s)&&typeof i=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(i)||[...i.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||s==="$regexi"&&/[^\x00-\x7f]/.test(i.replace(/\\u([0-9a-f]{4})/gi,(o,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(i)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(i)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),At=a.discriminatedUnion("type",[a.strictObject({type:a.literal("condition"),condition:q}),a.strictObject({type:a.literal("list"),attributeKey:a.string().min(1).max(128),values:a.array(a.union([a.string(),a.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function vt(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[s,i]of Object.entries(r))s==="$savedGroup"&&i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.id=="string"?t.add(i.id):["$inGroup","$notInGroup"].includes(s)&&typeof i=="string"?t.add(i):["$eq","$ne","$in","$nin","$ini","$nini"].includes(s)||n(i)}return n(e),[...t]}var Et=a.record(a.uuid(),At).superRefine((e,t)=>{let n=new Set,r=new Set;function s(i){if(n.has(i)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(i))return;let o=e[i];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(i),o.type==="condition"&&vt(o.condition).forEach(s),n.delete(i),r.add(i)}Object.keys(e).forEach(s)}),pe=a.tuple([a.number().min(0).max(1),a.number().min(0).max(1)]).refine(([e,t])=>e<=t),We=a.strictObject({attribute:a.string().optional(),seed:a.string().min(1),hashVersion:a.literal(2),ranges:a.array(pe).min(1).max(100)}),Ft=a.strictObject({id:a.string().min(1).max(128),condition:q,gate:a.boolean().optional()}),de={id:a.string().max(128).optional(),condition:q.optional(),parentConditions:a.array(Ft).max(50).optional(),filters:a.array(We).max(20).optional()},$t=a.union([a.strictObject({...de}),a.strictObject({...de,force:_,coverage:a.number().min(0).max(1).optional(),range:pe.optional(),seed:a.string().min(1).optional(),hashAttribute:a.string().optional(),hashVersion:a.literal(2).optional()}),a.strictObject({...de,type:a.literal("experiment-ref"),experimentId:a.uuid(),values:a.record(a.string().min(1),_),meta:a.record(a.string().min(1),a.strictObject({passthrough:a.boolean()})).optional()})]),Ot=a.strictObject({defaultValue:_,rules:a.array($t).max(100)}),vn=a.record(a.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ot).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function s(i){if(n.has(i)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${i}`});return}if(r.has(i))return;let o=e[i];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${i}`});return}n.add(i);for(let u of o.rules)for(let c of u.parentConditions??[])s(c.id);n.delete(i),r.add(i)}Object.keys(e).forEach(s)}),Rt=a.strictObject({name:a.string().max(80),reason:a.string().max(500),dateStarted:a.iso.datetime({offset:!0}),dateEnded:a.iso.datetime({offset:!0}).nullable(),coverage:a.number().min(0).max(1),variationWeights:a.array(a.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:q,savedGroups:a.array(a.strictObject({match:a.enum(["any","all","none"]),ids:a.array(a.uuid()).min(1)})).max(50),namespace:a.strictObject({id:a.uuid(),ranges:a.array(pe).min(1)}).nullable(),seed:a.string().min(1).max(128)}),Bt=a.strictObject({key:a.string().min(1).max(128),name:a.string().min(1).max(80),hypothesis:a.string().max(2e3),status:a.enum(["draft","running","stopped"]),hashAttribute:a.string().min(1).max(128),fallbackAttribute:a.string().max(128).nullable(),hashVersion:a.literal(2),disableStickyBucketing:a.boolean(),bucketVersion:a.number().int().min(0).max(1e3),minBucketVersion:a.number().int().min(0).max(1e3),variations:a.array(a.strictObject({id:a.string().min(1),key:a.string().min(1),name:a.string().max(80),description:a.string().max(500)})).min(2).max(20),phases:a.array(Rt).min(1).max(100),releasedVariationId:a.string().nullable(),excludeFromPayload:a.boolean(),statusSchedule:a.strictObject({startAt:a.iso.datetime({offset:!0}).nullable(),stopAt:a.iso.datetime({offset:!0}).nullable(),stopAfter:a.strictObject({value:a.number().int().positive().max(36500),unit:a.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let s=e.phases[r-1];return!s?.dateEnded||Date.parse(n.dateStarted)<Date.parse(s.dateStarted)||Date.parse(s.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,s],i,o)=>r>=s||o.some(([u,c],l)=>l!==i&&r<c&&u<s)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function En(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,{defaultValue:s.defaultValue,rules:s.rules.flatMap(i=>{if(!("experimentId"in i))return[Ge({...i,hashVersion:2})];let o=t[i.experimentId];if(!o)throw new Error(`Missing experiment: ${i.experimentId}`);let u=o.phases.at(-1);if(!u)throw new Error("Experiment requires an active phase");let c=o.statusSchedule?.startAt?Date.parse(o.statusSchedule.startAt):null,l=ze(o),d=o.status!=="stopped"&&(o.status==="running"||c!==null&&n>=c)&&(c===null||n>=c)&&(l===null||n<l),{type:f,experimentId:b,values:y,meta:S,...w}=i,m=x({...w,parentConditions:w.parentConditions?.map(p=>x(p)),filters:w.filters?.map(p=>x(p))});if(o.variations.some(p=>!Object.hasOwn(y,p.key))||Object.keys(y).length!==o.variations.length||Object.keys(S??{}).some(p=>!o.variations.some(O=>O.key===p)))throw new Error("Every variation needs a Feature value");let E=p=>{let O=y[p];if(O===void 0)throw new Error("Every variation needs a Feature value");return O},F={$and:[u.condition,...m.condition?[m.condition]:[],...u.savedGroups.map(p=>{let O=p.ids.map(Qe=>({$savedGroup:{id:Qe}}));return p.match==="all"?{$and:O}:p.match==="none"?{$nor:O}:{$or:O}})]},C=o.variations.find(p=>p.id===o.releasedVariationId);return C&&!o.excludeFromPayload?S?.[C.key]?.passthrough?[{...m,condition:F}]:[{...m,condition:F,force:E(C.key)}]:[{...m,condition:F,key:o.key,variations:o.variations.map(p=>E(p.key)),meta:o.variations.map(p=>({key:p.key,name:p.name,...x(S?.[p.key]??{})})),weights:u.variationWeights,coverage:d?u.coverage:0,seed:u.seed,hashVersion:2,hashAttribute:o.hashAttribute,...o.fallbackAttribute===null?{}:{fallbackAttribute:o.fallbackAttribute},disableStickyBucketing:!d||o.disableStickyBucketing,bucketVersion:o.bucketVersion,minBucketVersion:o.minBucketVersion,filters:[...m.filters??[],...(o.filters??[]).map(p=>x(p))]}]})}]))}function ze(e){if(e.statusSchedule?.stopAt)return Date.parse(e.statusSchedule.stopAt);let t=e.statusSchedule?.stopAfter;if(!t||e.status==="draft"&&!e.statusSchedule?.startAt)return null;let n=e.statusSchedule?.startAt??e.phases.at(-1)?.dateStarted;if(!n)throw new Error("Experiment requires an active phase");return Date.parse(n)+t.value*(t.unit==="days"?864e5:36e5)}function Fn(e,t=Date.now()){let n=Object.values(e).filter(r=>r.status!=="stopped"&&!(r.releasedVariationId&&!r.excludeFromPayload)).flatMap(r=>[r.statusSchedule?.startAt?Date.parse(r.statusSchedule.startAt):null,ze(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var Ct=Bt.safeExtend({filters:a.array(We).optional()}),Vt=a.strictObject({experiments:a.record(a.uuid(),Ct),savedGroups:Et}),Tt=a.strictObject({attributeName:a.string(),attributeValue:a.string(),assignments:a.record(a.string(),a.string())}),$n=a.strictObject({snapshot:Vt,attributes:he,results:he,stickyBucketAssignmentDocs:a.record(a.string(),Tt)}),On=a.strictObject({variantKey:a.string().nullable(),bucketVersion:a.number().int().min(0),source:a.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:a.number().min(0).max(1).optional(),stickyBucketUsed:a.boolean().optional(),hashUsed:a.boolean().optional()});export{Q as a,V as b,Y as c,we as d,Oe as e,Le as f,v as g,xt as h,Ie as i,Pe as j,Je as k,_ as l,he as m,q as n,At as o,vt as p,Et as q,$t as r,Ot as s,vn as t,Rt as u,Bt as v,En as w,ze as x,Fn as y,Ct as z,Vt as A,Tt as B,$n as C,On as D};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t="https://api.tinker.cash";export{t as a};
|