@tinkerlandai/indiana-sdk 0.8.1 → 0.8.4
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 +15 -0
- package/README.md +44 -3
- package/README.zh-CN.md +8 -0
- package/dist/{ai-usage-JoM7ZWk-.d.ts → ai-usage-DUlre7JC.d.ts} +1 -1
- package/dist/{api-JVC7x2FV.d.ts → api-XDc4pRlN.d.ts} +444 -17
- package/dist/chunk-3F2NQOR2.js +1 -0
- package/dist/chunk-663UOBHL.js +1 -0
- package/dist/chunk-BUDTHBFF.js +173 -0
- package/dist/chunk-EJTBSGLV.js +10 -0
- package/dist/{chunk-USLZX2ZA.js → chunk-F2GOIBDQ.js} +1 -1
- package/dist/{chunk-YWFNWK7C.js → chunk-GRLMT5PR.js} +1 -1
- package/dist/chunk-LMR2TM3X.js +1 -0
- package/dist/chunk-OBYJWIRB.js +1 -0
- package/dist/chunk-RZBZ6LCT.js +4 -0
- package/dist/{chunk-6HG7U6AU.js → chunk-SOQO2RDZ.js} +1 -1
- package/dist/chunk-SSHUBTT3.js +1 -0
- package/dist/chunk-SSLZKIIU.js +1 -0
- package/dist/{chunk-KSNOXNTC.js → chunk-VVV3JNS3.js} +1 -1
- package/dist/{configuration-sync-BexM2qbg.d.ts → configuration-sync-Ce3dShy7.d.ts} +8 -3
- package/dist/content-2FCUY6XX.js +1 -0
- package/dist/{customer-page-WUQVK_tp.d.ts → customer-page-9B97Qdt_.d.ts} +21 -1
- package/dist/{errors-DrdTlPwf.d.ts → errors-C8lRYZ0n.d.ts} +48 -1
- package/dist/{funnel-local-client-D1Fe7CZ6.d.ts → funnel-local-client-CUGavICI.d.ts} +69 -40
- package/dist/{funnel-runtime-host-CAMI6BJS.js → funnel-runtime-host-ENRTSXPJ.js} +1 -1
- package/dist/index.d.ts +175 -35
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -3
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +2 -2
- package/dist/page.js +1 -1
- package/dist/paywall-734GWAS4.js +1 -0
- package/dist/popup.d.ts +15 -5
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +97 -4
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-DLXDQQKK.js +1 -0
- package/dist/server.d.ts +18 -15
- package/dist/server.js +1 -1
- package/dist/src-CLEFCTAU.js +1 -0
- package/dist/visual.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-3BQFJANQ.js +0 -1
- package/dist/chunk-56AYS7RS.js +0 -1
- package/dist/chunk-AE4CUTUE.js +0 -1
- package/dist/chunk-AEUFCOFG.js +0 -1
- package/dist/chunk-F767CM3T.js +0 -7
- package/dist/chunk-X747SY26.js +0 -4
- package/dist/chunk-X7JJAEQQ.js +0 -350
- package/dist/content-YNL2CRJZ.js +0 -1
- package/dist/paywall-MXRMMF3R.js +0 -1
- package/dist/screen-renderer-P7MLBHY5.js +0 -1
- package/dist/src-G7UQB3QE.js +0 -1
- package/dist/{screen-i6eHL11m.d.ts → screen-BpAejkn0.d.ts} +1 -1
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as K,b as N,c as fe,d as ye,e as ve,g as T,h as Ie,j as ge,k as Pe,l as Ue,m as Ve,n as Me}from"./chunk-56AYS7RS.js";import"./chunk-YWFNWK7C.js";import{a as Be,b as Ge,c as je,d as qe}from"./chunk-USLZX2ZA.js";import{a}from"./chunk-KSNOXNTC.js";import{a as A}from"./chunk-AEUFCOFG.js";import{Ai as q,Bi as se,Ci as ce,De as G,Ee as oe,Ei as D,Fi as ue,Ge as ae,Gj as de,Ij as me,Mb as B,Pb as X,Tb as ee,ei as r,ej as pe,fj as le,hf as _,if as O,jf as ie,mi as j,re as te}from"./chunk-F767CM3T.js";import{a as o}from"./chunk-6HG7U6AU.js";import{Mb as re}from"./chunk-3BQFJANQ.js";import{b as $,h as ne}from"./chunk-AE4CUTUE.js";import"./chunk-EXCPE2XH.js";import{b as Z,q as W}from"./chunk-RRII2DMC.js";import{d as J}from"./chunk-KQCTDXVD.js";function we(e){return{async getCustomer(t){let n=r.getCustomer;return a(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=r.listCustomers;return a(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=r.updateCustomer;return a(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=r.createGuestCustomer;return a(e,n,t)},async resumeGuestSession(t){let n=r.resumeGuestSession;return a(e,n,t)},async claimGuestCustomer(t){let n=r.claimGuestCustomer;return a(e,n,t)},async renewCustomerSession(t){let n=r.renewSession;return a(e,n,t)},async revokeCustomerSessions(t){let n=r.revokeSessions;return a(e,n,t)},async createCustomerSession(t){return a(e,r.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return a(e,r.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function s(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function he(e){return{async checkEntitlement(t){let n=r.checkEntitlement;return a(e,n,t,s)},async readHoldings(t){let n=r.readHoldings;return a(e,n,t,s)},async readSeats(t){let n=r.readSeats;return a(e,n,t,s)},async manageSeat(t){let n=r.manageSeat;return a(e,n,t,s)}}}function Se(e){return{async readAiPricing(t){let n=r.readAiPricing;return a(e,n,t,s)},async readUsage(t){let n=r.readUsage;return a(e,n,t,s)},async setUsage(t){let n=r.setUsage;return a(e,n,t,s)},async manageBalanceGrant(t){let n=r.manageBalanceGrant;return a(e,n,t,s)},async readBalanceSource(t){let n=r.readBalanceSource;return a(e,n,t,s)},async adjustBalance(t){let n=r.adjustBalance;return a(e,n,t,s)},async listBalanceGrants(t){let n=r.listBalanceGrants;return a(e,n,t,s)},async manageBillingLimits(t){let n=r.manageBillingLimits;return a(e,n,t,s)},async manageUsageEntity(t){let n=r.manageUsageEntity;return a(e,n,t,s)},async readUsageAnalytics(t){let n=r.readUsageAnalytics;return a(e,n,t,s)},async readCreditAnalytics(t){let n=r.readCreditAnalytics;return a(e,n,t,s)},async submitUsageBatch(t){let n=r.submitUsageBatch;return a(e,n,t,s)},async readUsageBatch(t){let n=r.readUsageBatch;return a(e,n,t,s)},async readLedger(t){let n=r.readLedger;return a(e,n,t,s)},async readCreditStatement(t){let n=r.readCreditStatement;return a(e,n,t,s)},async quoteBalance(t){let n=r.quoteBalance;return a(e,n,t,s)},async trackUsage(t){let n=r.trackUsage;return a(e,n,t,s)},async mutateBalance(t){let n=r.mutateBalance;return a(e,n,t,s)}}}function Ee(e){return{async listInvoiceTemplates(t={}){let n=r.listInvoiceTemplates;return a(e,n,t,s)},async previewInvoice(t){let n=r.previewInvoice;return a(e,n,t,s)},async createInvoice(t){let n=r.createInvoice;return a(e,n,t,s)},async manageInvoice(t){let n=r.manageInvoice;return a(e,n,t,s)},async readInvoiceOperation(t){let n=r.readInvoiceOperation;return a(e,n,t,s)},async listInvoices(t){let n=r.listInvoices;return a(e,n,t,s)},async getInvoice(t){let n=r.getInvoice;return a(e,n,t,s)},async setupPayment(t){let n=r.setupPayment;return a(e,n,t,s)},async readPaymentSetup(t){let n=r.readPaymentSetup;return a(e,n,t,s)},async readBillingInvoice(t){let n=r.readBillingInvoice;return a(e,n,t,s)},async previewRefund(t){let n=r.previewRefund;return a(e,n,t,s)},async refund(t){let n=r.refund;return a(e,n,t,s)},async readRefund(t){let n=r.readRefund;return a(e,n,t,s)}}}function Ae(e){return{async previewSubscriptionBatch(t){let n=r.previewSubscriptionBatch;return a(e,n,t,s)},async confirmSubscriptionBatch(t){let n=r.confirmSubscriptionBatch;return a(e,n,t,s)},async readSubscriptionBatch(t){let n=r.readSubscriptionBatch;return a(e,n,t,s)},async abandonSubscriptionBatch(t){let n=r.abandonSubscriptionBatch;return a(e,n,t,s)},async manageSubscriptionTrial(t){let n=r.manageSubscriptionTrial;return a(e,n,t,s)},async readSubscriptionTrial(t){let n=r.readSubscriptionTrial;return a(e,n,t,s)},async listSubscriptions(t){let n=r.listSubscriptions;return a(e,n,t,s)},async listPurchases(t){let n=r.listPurchases;return a(e,n,t,s)},async listSubscriptionConflicts(t){let n=r.listSubscriptionConflicts;return a(e,n,t,s)},async retrySubscriptionConflict(t){let n=r.retrySubscriptionConflict;return a(e,n,t,s)},async previewUpdate(t){let n=r.previewUpdate;return a(e,n,t,s)},async update(t){let n=r.update;return a(e,n,t,s)},async readSubscriptionUpdate(t){let n=r.readSubscriptionUpdate;return a(e,n,t,s)},async restoreNativePurchase(t){let n=r.restoreNativePurchase;return a(e,n,t,s)},async verifySubscriptions(t){let n=r.verifySubscriptions;return a(e,n,t,s)},async previewAttach(t){let n=r.previewAttach;return a(e,n,t,s)},async attach(t){let n=r.attach;return a(e,n,t,s)},async readSubscriptionOperation(t){let n=r.readSubscriptionOperation;return a(e,n,t,s)}}}function Fe(e){return{async recordCouponRedemption(t){return a(e,r.recordCouponRedemption,t,{request:"Invalid Coupon redemption facts",parseResponse:s})},async grantOffer(t){let n=r.grantOffer;return a(e,{...n,request:n.request.refine(c=>!!c.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function Ce(e){return{...he(e),...Se(e),...Ee(e),...Ae(e),...Fe(e)}}function Re(e){return{async getFeatures(t={}){let n=r.getFeatures;return a(e,n,t,s)},async evaluateFeatures(t){let n=r.evaluateFeatures;return a(e,n,t,s)}}}function Oe(e){return{async trackEvents(t){let n=r.trackEvents;return a(e,n,t,s)}}}function be(e){return{async resolveContent(t){let n=r.resolveContent;return a(e,n,t,s)},async resolvePaywall(t){let n=r.resolvePaywall;return a(e,n,t,s)},async resolveOffering(t){let n=r.resolveOffering;return a(e,n,t,s)}}}function Ke(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t=A(e);t.identify(e.apiKey);let n=t.request;return{...we(n),...Ce(n),...Re(n),...Oe(n),...be(n)}}function ze(){if(typeof window<"u")throw new o("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}async function Ye(e,t){if(typeof window<"u")throw new o("SERVER_ONLY","Renewal requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let{funnelCredentialCommandSchema:n,funnelCredentialResponseSchema:c}=await import("./src-G7UQB3QE.js"),p=A(e);p.identify(e.apiKey);let l=c.parse(await N(e,await p.request("funnels",n.parse({...t,operation:"renew_run"}))));if(l.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return l}function ke(e){let t=ye(e),n=i=>{throw new o("INVALID_RESPONSE",i)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let c=new Set(["entry","condition","feature","split","end","output"]);for(let i of t.nodes.values()){if(!c.has(i.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(i.type==="entry"&&i.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(i.type)&&!i.outputs.next&&n("Local next exit is unavailable"),i.type==="feature"){let u=i.resources.featureKey;(!u||!Object.hasOwn(e.evaluation.variables,i.writes.value)||!Object.hasOwn(t.features,u))&&n("Local Feature definition or declaration is unavailable")}if(i.type==="condition"){let u=e.conditions[i.id];(!u||!i.outputs.default||u.some((f,y)=>f.port!==`case:${y}`||!i.outputs[f.port]))&&n("Local Condition exits are unavailable")}if(i.type==="split"&&(!i.resources.experimentId||!Object.hasOwn(e.growth.experiments,i.resources.experimentId)||!i.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),i.type==="end"||i.type==="output"){let u=e.evaluation.terminals[i.id];if(!u)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(i.outputs).length&&n("A terminal cannot have outgoing edges"),u.output?.type==="feature"&&!Object.hasOwn(t.features,u.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let u of Object.values(i.outputs))t.nodes.has(u)||n("Local target is unavailable")}let p=new Set,l=new Set;function d(i){if(l.has(i)&&n("Local graph contains a cycle"),!p.has(i)){l.add(i);for(let u of Object.values(t.nodes.get(i).outputs))d(u);l.delete(i),p.add(i)}}return d(e.topology.entry),p.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(i){let u={},f=i.context;f.features=t.features,f.savedGroups=t.savedGroups;let y=()=>{f.attributes=te({declarations:e.evaluation.variables,attributes:i.attributes,parameters:i.parameters,answers:{},results:u,savedGroups:t.savedGroups})};y();let g=e.topology.entry,m=0;for(;;){let v=t.nodes.get(g);if(v.type==="end"||v.type==="output"){let I=e.evaluation.terminals[g],w=I.output,S=w?.type==="feature"?t.feature(w.featureKey,f):w?.type==="variable"?ee({source:"variable",key:w.key,...w.path?{path:w.path}:{}},{declarations:e.evaluation.variables,answers:{},results:u,parameters:i.parameters,attributes:i.attributes,savedGroups:t.savedGroups}):w?.value??null;return B(e.evaluation.outputSchema,S)||n("Local output does not match its declaration"),{outcome:I.outcome,value:S}}if(m++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(v.type==="entry")g=v.outputs.next;else{let I=t.evaluate(g,f);if(v.type==="feature"){let w=v.writes.value,S=I.value??null;B(e.evaluation.variables[w],S)||n("Local Feature value does not match its declaration"),X(e.evaluation.variables,{writes:v.writes},{[w]:S}),u[w]=S,y()}g=I.target}}}}}import{z as Le}from"zod";function xe(e,t,n){let c=Z.parse(e.attributes);if(["parameters","answers","results"].some(E=>Object.hasOwn(c,E)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let p=re.parse(e.parameters??{}),l=Le.record(Le.string(),W).parse(e.stickyBucketAssignmentDocs??{});for(let[E,h]of Object.entries(l))if(E!==`${h.attributeName}||${h.attributeValue}`||!Object.hasOwn(c,h.attributeName)||J(c[h.attributeName])!==h.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,i=e.onFeatureUsage,u=e.onExperimentViewed,f=e.onError,y=new Map,g=new Set,m={},v=Promise.resolve();function I(E){let h=v.then(()=>(n(),E()));return v=h.catch(()=>{}),h}function w(E){try{f?.(E)}catch{}}function S(E){try{let h=E();h&&typeof h.catch=="function"&&h.catch(w)}catch(h){w(h)}}async function k(){for(let[E,h]of y){if(n(),d)try{await d(structuredClone(h))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),y.delete(E)}}return{evaluate(E={}){let h=E.track===!0;return I(async()=>{let L=await t();n(L);let Y=new Set(g),H={...m},Q=new Map,V=[],_e={stickyBucketAssignmentDocs:structuredClone(l),saveStickyBucketAssignmentDoc(F){Q.set(`${F.attributeName}||${F.attributeValue}`,structuredClone(F))},...h?{trackedExperiments:Y,trackedFeatureUsage:H,onExperimentViewed(F,R){let M=structuredClone(F),Te=structuredClone(R);u&&V.push(()=>u(structuredClone(M),structuredClone(Te)))},onFeatureUsage(F,R){let M=structuredClone(R);i&&V.push(()=>i(F,structuredClone(M)))}}:{}},Ne=L.program.evaluate({attributes:c,parameters:p,context:_e});n(L);for(let[F,R]of Q)l[F]=R,y.set(F,R);await k(),n(L),h&&(g=Y,m=H);for(let F of V)S(F);let x=L.configuration;return structuredClone({evaluationMode:"local",scope:x.scope,funnelId:x.funnelId,versionId:x.versionId,evaluationRevision:x.evaluationRevision,generation:x.growth.generation,...Ne})})},flush:()=>I(k),get stickyBucketAssignmentDocs(){return n(),structuredClone(l)}}}var He=6e4;function P(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=$.parse(e.scope),n=e.funnelId,c=e.load,p,l,d,i=0,u=g=>Date.now()>=g.expiresAt;async function f(){if(l)return l;let g=i;p=void 0;let m=(async()=>{let v=await c();if(g!==i)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(v&&typeof v=="object"&&"evaluationMode"in v&&v.evaluationMode==="remote")throw s(D,v),new o("EVALUATION_MODE","This Funnel requires remote decide");let I=s(ue,v);if(g!==i)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(I.scope.projectId!==t.projectId||I.scope.environment!==t.environment||I.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(I.growth.scope.projectId!==t.projectId||I.growth.scope.environment!==t.environment||I.growth.expiresAt!==I.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let w=Math.min(Date.now()+He,I.expiresAt?Date.parse(I.expiresAt):1/0);if(Date.now()>=w)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let S=JSON.stringify([t.projectId,t.environment,n,I.versionId,I.evaluationRevision,I.growth.generation]),k=[I.topology,I.conditions,I.evaluation,I.growth.features,I.growth.experiments,I.growth.savedGroups];if(d?.key===S&&!Ie(d.body,k))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==S&&(d={key:S,body:k,program:ke(I)}),p={key:S,configuration:I,expiresAt:w,program:d.program},p})();l=m;try{return await m}finally{l===m&&(l=void 0)}}function y(){return l??(p&&!u(p)?Promise.resolve(p):f())}return{session(g){let m=i;return xe(g,y,v=>{if(e.assertUsable?.(),m!==i)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(v&&(u(v)||p?.key!==v.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){i++,p=void 0,l=void 0,d=void 0}}}function Qe(e,t){let n=e.snapshot?.generation,c=P({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),p=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,c.refresh().catch(()=>{}))}),l=c.session;return Object.assign(c,{session(d){let i=l(d),u=i.evaluate;return Object.assign(i,{async evaluate(...f){return e.fresh||await e.refresh(),u(...f)}})},destroy(){p(),c.reset()}})}function $e(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>ge(e,t)}}function De(e,t,n){return de(e,t,n,fe)}var b=class extends o{constructor(n,c){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,c);this.decisionId=n;this.decisionRequestId=c}decisionId;decisionRequestId};async function U(e,t,n,c){let{decisionId:p,requestId:l}=e,d=e,i=250,u=0;for(;;){if(d.decisionId!==p||d.requestId!==l||d.decision&&!T(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,l);if(Date.now()>=n)throw new b(p,l);if(await new Promise(f=>setTimeout(f,Math.min(Math.max(i,u-Date.now()),n-Date.now()))),Date.now()>=n)throw new b(p,l);i=Math.min(1e3,i*2);try{d=await c(p,n)}catch(f){if(f instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(f.code)){u=Date.now()+(f.retryAfterSeconds??0)*1e3;continue}throw f}}}function z(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new o("SERVER_ONLY","Funnel decisions are requested by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t,n,c=new Map;async function p(u,f){let y=u;y.status!=="pending"&&c.delete(y.decisionId);for(let g=0;g<32&&y.evaluation;g++){let m=y.evaluation;if(m.runId!==y.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let v=c.get(y.decisionId);if(!v&&m.type==="evaluate_segment"){let w=me.parse(await l({operation:"segment_configuration",funnelId:e.funnelId,versionId:m.versionId},f));if(w.configuration.scope.projectId!==e.scope.projectId||w.configuration.scope.environment!==e.scope.environment||w.configuration.funnelId!==e.funnelId||w.configuration.versionId!==m.versionId||w.configuration.evaluationRevision!==m.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(c.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");v={operation:"commit_decision_segment",decisionId:y.decisionId,requestId:j(y.decisionId,m.visit,`segment:${m.revision}`),nodeId:m.nodeId,visit:m.visit,revision:m.revision,policyRevision:m.policyRevision,generation:w.configuration.growth.generation,...ve(w.configuration,w.document,m)},c.set(y.decisionId,v)}if(!v){if(m.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==m.versionId||n.evaluationRevision!==m.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=D.parse(await l({operation:"configuration",funnelId:e.funnelId,versionId:m.versionId},f))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==m.versionId||n.evaluationRevision!==m.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(c.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");v={operation:"evaluate_decision",decisionId:y.decisionId,requestId:j(y.decisionId,m.visit,"evaluation"),nodeId:m.nodeId,visit:m.visit,revision:m.revision,receiptId:m.receiptId,policyRevision:m.policyRevision,generation:n.growth.generation,result:De(n,m.nodeId,m)},c.set(y.decisionId,v)}let I=O.parse(await l(v,f));if(I.decisionId!==u.decisionId||I.requestId!==u.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");c.delete(y.decisionId),y=I}return y}async function l(u,f,y=!1){let g=A({...e,fetch:(m,v)=>{let I=new Headers(v?.headers);return I.set("Accept-Encoding","identity"),y&&I.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(m,{...v,headers:I})},timeoutMs:Math.min(e.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)});return g.identify(e.apiKey),g.request("funnels",u)}async function d(u,f){let y=O.parse(await l(_.parse({operation:"read_decision",decisionId:u}),f));if(y.decisionId!==u)throw new o("INVALID_RESPONSE","Decision identity changed");return p(y,f)}async function i(u,f,y=!1){let g=_.options[0].parse({...u,operation:"decide",funnelId:e.funnelId}),m;try{m=O.parse(await l(g,f,y))}catch(v){throw v instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(v.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",v.status,u.requestId):v}if(m.requestId!==u.requestId||m.decision&&!T(m.decision,g.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await p(m,f),customer:g.customer}}return{local(){return t??=P({scope:e.scope,funnelId:e.funnelId,load:()=>l({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let u=D.parse(await l({operation:"configuration",funnelId:e.funnelId}));if(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment||u.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return u},features(u={}){return K({...u,scope:e.scope,load:async()=>ne.parse(await l({operation:"feature_config",funnelId:e.funnelId}))})},read:u=>d(u),async submit(u){return(await i(u,void 0,!0)).response},async decide(u){let f=Date.now()+3e4,y=await i(u,f);return U(y.response,y.customer,f,d)},async reportUsed(u){let f=ie.parse(await l(_.parse({...u,operation:"report_used"})));if(f.decisionId!==u.decisionId||f.eventId!==u.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function Je(e){if(typeof window<"u")throw new o("SERVER_ONLY","Native receipts are verified by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","Server API key required");let t=A({...e,timeoutMs:e.timeoutMs??35e3});return t.identify(e.apiKey),{async recover(n){let c=pe.parse(n);if(c.orderId!==c.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let p=c.nativeEvidence,l={requestId:c.requestId,customerToken:c.customerToken,purchaseIntentId:c.orderId,...p===null?{intent:"read"}:p.provider==="apple"?{provider:"apple",signedTransaction:p.signedTransaction}:{provider:"google",purchaseToken:p.purchaseToken}},d=r.restoreNativePurchase.response.parse(await t.request(r.restoreNativePurchase.path,l));if(d.operation.requestId!==c.requestId||d.operation.purchaseIntentId!==c.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let i=le.parse({scope:d.scope,requestId:c.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(i.requestId!==c.requestId||i.orderId!==c.orderId||i.receiptId!==c.receiptId||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return i}}}import{z as Ze}from"zod";var C=Ze.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function We(e,t){let n=C.parse(e.inputTokens.total),c=C.parse(e.outputTokens.total),p=C.parse(e.inputTokens.cacheRead??0),l=C.parse(e.inputTokens.cacheWrite??0),d=C.parse(e.outputTokens.reasoning??0);if(p+l>n||d>c||e.inputTokens.noCache!==void 0&&C.parse(e.inputTokens.noCache)!==n-p-l||e.outputTokens.text!==void 0&&C.parse(e.outputTokens.text)!==c-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-p-l,cache_read:p,cache_write:l,output:t==="output"?c:c-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Xe(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(c){await e.persist({context:c,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(c,p){let l={context:c,modelId:e.modelId,usage:p,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(l);let d=e.mapTokens?e.mapTokens(p):We(p,e.reasoning),i=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...l,tokens:d,quote:i,phase:"quoted"});let u=await e.pricing.trackTokens(e.client,{...c,quote:i});if(!u.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...l,tokens:d,quote:i,receipt:u,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:c}){let p=await e.context(),l;try{l=await c()}catch(d){throw await t(p),d}return await n(p,l.usage),l},async wrapStream({doStream:c}){let p=await e.context(),l;try{l=await c()}catch(y){throw await t(p),y}let d=!1,i=!1,u=l.stream.getReader();async function f(){d||i||(i=!0,await t(p))}return{...l,stream:new ReadableStream({async pull(y){try{let{value:g,done:m}=await u.read();if(m){if(!d)throw await f(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");y.close();return}if(g.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(p,g.usage)}y.enqueue(g)}catch(g){try{await f()}finally{y.error(g),await u.cancel(g)}}},async cancel(y){try{await f()}finally{await u.cancel(y)}}})}}}}function en(e){if(typeof window<"u")throw new o("SERVER_ONLY","Funnel receipts are sent by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t=A(e);return t.identify(e.apiKey),{async signal(n){let c=G.parse({...n,operation:"signal"}),p=oe.parse(await t.request("funnels",c));if(p.runId!==n.runId||p.eventId!==n.eventId||p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return p},async readResults(n){let c=G.parse({operation:"read_results",runId:n}),p=ae.parse(await t.request("funnels",c));if(p.runId!==n||p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return p}}}function nn(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new o("SERVER_ONLY","Campaign entry requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t=A({...e,timeoutMs:e.timeoutMs??35e3});return t.identify(e.apiKey),{async decide(n){let c=Date.now()+(e.timeoutMs??3e4),p=q.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),l=A({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,c-Date.now()))});l.identify(e.apiKey);let d=O.parse(await l.request("funnels",p));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return U(d,p.customer,c,(i,u)=>z({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,u-Date.now()))}).read(i))},async start(n){let c=q.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),p=ce.parse(await t.request("funnels",c)),l=se.parse("suppressed"in p?p:await N(e,p));if(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in l)&&(l.run.source.id!==e.funnelId||!l.customerId||c.customer.type==="id"&&l.customerId!==c.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return l}}}export{b as FunnelDecisionTimeoutError,o as IndianaError,Be as aiPriceSnapshotSchema,Ge as aiTokenQuoteSchema,je as createAiPricing,Xe as createAiUsageMiddleware,Pe as createConfigurationSync,qe as createConfiguredAiPricing,K as createFeatureClient,nn as createFunnelCampaignClient,z as createFunnelDecisionClient,P as createFunnelLocalEvaluator,en as createFunnelOrchestrationClient,Ve as createFunnelStartClient,ze as createGuestToken,Ke as createIndianaServer,Me as createLocalFunnelClient,Je as createNativeReceiptClient,$e as createPaywallStartClient,Qe as createSynchronizedFunnelLocalEvaluator,Ue as evaluateFunnelNode,Ye as renewFunnelRun};
|
|
1
|
+
import{a as K,b as N,c as fe,d as ye,e as ve,g as T,h as Ie,j as ge,k as Pe,l as Ue,m as Me,n as Ve}from"./chunk-3F2NQOR2.js";import"./chunk-GRLMT5PR.js";import{a as Be,b as Ge,c as je,d as qe}from"./chunk-F2GOIBDQ.js";import{a}from"./chunk-VVV3JNS3.js";import{a as A}from"./chunk-SSHUBTT3.js";import{$f as _,$j as le,Ak as de,Ck as me,Fc as B,Ic as X,Mc as ee,Yi as r,_j as pe,ag as O,bg as ie,ej as j,kf as te,sj as q,tj as se,uj as ce,vf as G,wf as oe,wj as D,xj as ue,yf as ae}from"./chunk-EJTBSGLV.js";import{a as o}from"./chunk-SOQO2RDZ.js";import{Mb as re}from"./chunk-LMR2TM3X.js";import{b as $,h as ne}from"./chunk-OBYJWIRB.js";import"./chunk-EXCPE2XH.js";import{b as Z,q as W}from"./chunk-RRII2DMC.js";import{d as J}from"./chunk-KQCTDXVD.js";function we(e){return{async getCustomer(t){let n=r.getCustomer;return a(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=r.listCustomers;return a(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=r.updateCustomer;return a(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=r.createGuestCustomer;return a(e,n,t)},async resumeGuestSession(t){let n=r.resumeGuestSession;return a(e,n,t)},async claimGuestCustomer(t){let n=r.claimGuestCustomer;return a(e,n,t)},async renewCustomerSession(t){let n=r.renewSession;return a(e,n,t)},async revokeCustomerSessions(t){let n=r.revokeSessions;return a(e,n,t)},async createCustomerSession(t){return a(e,r.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return a(e,r.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function u(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function he(e){return{async checkEntitlement(t){let n=r.checkEntitlement;return a(e,n,t,u)},async readHoldings(t){let n=r.readHoldings;return a(e,n,t,u)},async readSeats(t){let n=r.readSeats;return a(e,n,t,u)},async manageSeat(t){let n=r.manageSeat;return a(e,n,t,u)}}}function Se(e){return{async readAiPricing(t){let n=r.readAiPricing;return a(e,n,t,u)},async readUsage(t){let n=r.readUsage;return a(e,n,t,u)},async setUsage(t){let n=r.setUsage;return a(e,n,t,u)},async manageBalanceGrant(t){let n=r.manageBalanceGrant;return a(e,n,t,u)},async readBalanceSource(t){let n=r.readBalanceSource;return a(e,n,t,u)},async adjustBalance(t){let n=r.adjustBalance;return a(e,n,t,u)},async listBalanceGrants(t){let n=r.listBalanceGrants;return a(e,n,t,u)},async manageBillingLimits(t){let n=r.manageBillingLimits;return a(e,n,t,u)},async manageUsageEntity(t){let n=r.manageUsageEntity;return a(e,n,t,u)},async readUsageAnalytics(t){let n=r.readUsageAnalytics;return a(e,n,t,u)},async readCreditAnalytics(t){let n=r.readCreditAnalytics;return a(e,n,t,u)},async submitUsageBatch(t){let n=r.submitUsageBatch;return a(e,n,t,u)},async readUsageBatch(t){let n=r.readUsageBatch;return a(e,n,t,u)},async readLedger(t){let n=r.readLedger;return a(e,n,t,u)},async readCreditStatement(t){let n=r.readCreditStatement;return a(e,n,t,u)},async quoteBalance(t){let n=r.quoteBalance;return a(e,n,t,u)},async trackUsage(t){let n=r.trackUsage;return a(e,n,t,u)},async mutateBalance(t){let n=r.mutateBalance;return a(e,n,t,u)}}}function Ee(e){return{async listInvoiceTemplates(t={}){let n=r.listInvoiceTemplates;return a(e,n,t,u)},async previewInvoice(t){let n=r.previewInvoice;return a(e,n,t,u)},async createInvoice(t){let n=r.createInvoice;return a(e,n,t,u)},async manageInvoice(t){let n=r.manageInvoice;return a(e,n,t,u)},async readInvoiceOperation(t){let n=r.readInvoiceOperation;return a(e,n,t,u)},async listInvoices(t){let n=r.listInvoices;return a(e,n,t,u)},async getInvoice(t){let n=r.getInvoice;return a(e,n,t,u)},async setupPayment(t){let n=r.setupPayment;return a(e,n,t,u)},async readPaymentSetup(t){let n=r.readPaymentSetup;return a(e,n,t,u)},async readBillingInvoice(t){let n=r.readBillingInvoice;return a(e,n,t,u)},async previewRefund(t){let n=r.previewRefund;return a(e,n,t,u)},async refund(t){let n=r.refund;return a(e,n,t,u)},async readRefund(t){let n=r.readRefund;return a(e,n,t,u)}}}function Ae(e){return{async previewSubscriptionBatch(t){let n=r.previewSubscriptionBatch;return a(e,n,t,u)},async confirmSubscriptionBatch(t){let n=r.confirmSubscriptionBatch;return a(e,n,t,u)},async readSubscriptionBatch(t){let n=r.readSubscriptionBatch;return a(e,n,t,u)},async abandonSubscriptionBatch(t){let n=r.abandonSubscriptionBatch;return a(e,n,t,u)},async manageSubscriptionTrial(t){let n=r.manageSubscriptionTrial;return a(e,n,t,u)},async readSubscriptionTrial(t){let n=r.readSubscriptionTrial;return a(e,n,t,u)},async listSubscriptions(t){let n=r.listSubscriptions;return a(e,n,t,u)},async listPurchases(t){let n=r.listPurchases;return a(e,n,t,u)},async listSubscriptionConflicts(t){let n=r.listSubscriptionConflicts;return a(e,n,t,u)},async retrySubscriptionConflict(t){let n=r.retrySubscriptionConflict;return a(e,n,t,u)},async previewUpdate(t){let n=r.previewUpdate;return a(e,n,t,u)},async update(t){let n=r.update;return a(e,n,t,u)},async readSubscriptionUpdate(t){let n=r.readSubscriptionUpdate;return a(e,n,t,u)},async restoreNativePurchase(t){let n=r.restoreNativePurchase;return a(e,n,t,u)},async verifySubscriptions(t){let n=r.verifySubscriptions;return a(e,n,t,u)},async previewAttach(t){let n=r.previewAttach;return a(e,n,t,u)},async attach(t){let n=r.attach;return a(e,n,t,u)},async readSubscriptionOperation(t){let n=r.readSubscriptionOperation;return a(e,n,t,u)}}}function Fe(e){return{async recordCouponRedemption(t){return a(e,r.recordCouponRedemption,t,{request:"Invalid Coupon redemption facts",parseResponse:u})},async grantOffer(t){let n=r.grantOffer;return a(e,{...n,request:n.request.refine(c=>!!c.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function Ce(e){return{...he(e),...Se(e),...Ee(e),...Ae(e),...Fe(e)}}function Re(e){return{async getFeatures(t={}){let n=r.getFeatures;return a(e,n,t,u)},async evaluateFeatures(t){let n=r.evaluateFeatures;return a(e,n,t,u)}}}function Oe(e){return{async trackEvents(t){let n=r.trackEvents;return a(e,n,t,u)}}}function be(e){return{async resolveContent(t){let n=r.resolveContent;return a(e,n,t,u)},async resolvePaywall(t){let n=r.resolvePaywall;return a(e,n,t,u)},async resolveOffering(t){let n=r.resolveOffering;return a(e,n,t,u)}}}function Ke(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t=A(e);t.identify(e.apiKey);let n=t.request;return{async sendMessage(c){let i=r.sendMessage;return i.response.parse(await n(i.path,i.request.parse(c)))},async readMessage(c){let i=r.readMessage;return i.response.parse(await n(i.path,i.request.parse(c)))},...we(n),...Ce(n),...Re(n),...Oe(n),...be(n)}}function ze(){if(typeof window<"u")throw new o("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}async function Ye(e,t){if(typeof window<"u")throw new o("SERVER_ONLY","Renewal requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let{funnelCredentialCommandSchema:n,funnelCredentialResponseSchema:c}=await import("./src-CLEFCTAU.js"),i=A(e);i.identify(e.apiKey);let l=c.parse(await N(e,await i.request("funnels",n.parse({...t,operation:"renew_run"}))));if(l.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return l}function ke(e){let t=ye(e),n=s=>{throw new o("INVALID_RESPONSE",s)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let c=new Set(["entry","condition","feature","split","end","output"]);for(let s of t.nodes.values()){if(!c.has(s.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(s.type==="entry"&&s.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(s.type)&&!s.outputs.next&&n("Local next exit is unavailable"),s.type==="feature"){let p=s.resources.featureKey;(!p||!Object.hasOwn(e.evaluation.variables,s.writes.value)||!Object.hasOwn(t.features,p))&&n("Local Feature definition or declaration is unavailable")}if(s.type==="condition"){let p=e.conditions[s.id];(!p||!s.outputs.default||p.some((f,y)=>f.port!==`case:${y}`||!s.outputs[f.port]))&&n("Local Condition exits are unavailable")}if(s.type==="split"&&(!s.resources.experimentId||!Object.hasOwn(e.growth.experiments,s.resources.experimentId)||!s.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),s.type==="end"||s.type==="output"){let p=e.evaluation.terminals[s.id];if(!p)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(s.outputs).length&&n("A terminal cannot have outgoing edges"),p.output?.type==="feature"&&!Object.hasOwn(t.features,p.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let p of Object.values(s.outputs))t.nodes.has(p)||n("Local target is unavailable")}let i=new Set,l=new Set;function d(s){if(l.has(s)&&n("Local graph contains a cycle"),!i.has(s)){l.add(s);for(let p of Object.values(t.nodes.get(s).outputs))d(p);l.delete(s),i.add(s)}}return d(e.topology.entry),i.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(s){let p={},f=s.context;f.features=t.features,f.savedGroups=t.savedGroups;let y=()=>{f.attributes=te({declarations:e.evaluation.variables,attributes:s.attributes,parameters:s.parameters,answers:{},results:p,savedGroups:t.savedGroups})};y();let g=e.topology.entry,m=0;for(;;){let v=t.nodes.get(g);if(v.type==="end"||v.type==="output"){let I=e.evaluation.terminals[g],w=I.output,S=w?.type==="feature"?t.feature(w.featureKey,f):w?.type==="variable"?ee({source:"variable",key:w.key,...w.path?{path:w.path}:{}},{declarations:e.evaluation.variables,answers:{},results:p,parameters:s.parameters,attributes:s.attributes,savedGroups:t.savedGroups}):w?.value??null;return B(e.evaluation.outputSchema,S)||n("Local output does not match its declaration"),{outcome:I.outcome,value:S}}if(m++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(v.type==="entry")g=v.outputs.next;else{let I=t.evaluate(g,f);if(v.type==="feature"){let w=v.writes.value,S=I.value??null;B(e.evaluation.variables[w],S)||n("Local Feature value does not match its declaration"),X(e.evaluation.variables,{writes:v.writes},{[w]:S}),p[w]=S,y()}g=I.target}}}}}import{z as Le}from"zod";function xe(e,t,n){let c=Z.parse(e.attributes);if(["parameters","answers","results"].some(E=>Object.hasOwn(c,E)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let i=re.parse(e.parameters??{}),l=Le.record(Le.string(),W).parse(e.stickyBucketAssignmentDocs??{});for(let[E,h]of Object.entries(l))if(E!==`${h.attributeName}||${h.attributeValue}`||!Object.hasOwn(c,h.attributeName)||J(c[h.attributeName])!==h.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,s=e.onFeatureUsage,p=e.onExperimentViewed,f=e.onError,y=new Map,g=new Set,m={},v=Promise.resolve();function I(E){let h=v.then(()=>(n(),E()));return v=h.catch(()=>{}),h}function w(E){try{f?.(E)}catch{}}function S(E){try{let h=E();h&&typeof h.catch=="function"&&h.catch(w)}catch(h){w(h)}}async function k(){for(let[E,h]of y){if(n(),d)try{await d(structuredClone(h))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),y.delete(E)}}return{evaluate(E={}){let h=E.track===!0;return I(async()=>{let L=await t();n(L);let Y=new Set(g),H={...m},Q=new Map,M=[],_e={stickyBucketAssignmentDocs:structuredClone(l),saveStickyBucketAssignmentDoc(F){Q.set(`${F.attributeName}||${F.attributeValue}`,structuredClone(F))},...h?{trackedExperiments:Y,trackedFeatureUsage:H,onExperimentViewed(F,R){let V=structuredClone(F),Te=structuredClone(R);p&&M.push(()=>p(structuredClone(V),structuredClone(Te)))},onFeatureUsage(F,R){let V=structuredClone(R);s&&M.push(()=>s(F,structuredClone(V)))}}:{}},Ne=L.program.evaluate({attributes:c,parameters:i,context:_e});n(L);for(let[F,R]of Q)l[F]=R,y.set(F,R);await k(),n(L),h&&(g=Y,m=H);for(let F of M)S(F);let x=L.configuration;return structuredClone({evaluationMode:"local",scope:x.scope,funnelId:x.funnelId,versionId:x.versionId,evaluationRevision:x.evaluationRevision,generation:x.growth.generation,...Ne})})},flush:()=>I(k),get stickyBucketAssignmentDocs(){return n(),structuredClone(l)}}}var He=6e4;function P(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=$.parse(e.scope),n=e.funnelId,c=e.load,i,l,d,s=0,p=g=>Date.now()>=g.expiresAt;async function f(){if(l)return l;let g=s;i=void 0;let m=(async()=>{let v=await c();if(g!==s)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(v&&typeof v=="object"&&"evaluationMode"in v&&v.evaluationMode==="remote")throw u(D,v),new o("EVALUATION_MODE","This Funnel requires remote decide");let I=u(ue,v);if(g!==s)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(I.scope.projectId!==t.projectId||I.scope.environment!==t.environment||I.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(I.growth.scope.projectId!==t.projectId||I.growth.scope.environment!==t.environment||I.growth.expiresAt!==I.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let w=Math.min(Date.now()+He,I.expiresAt?Date.parse(I.expiresAt):1/0);if(Date.now()>=w)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let S=JSON.stringify([t.projectId,t.environment,n,I.versionId,I.evaluationRevision,I.growth.generation]),k=[I.topology,I.conditions,I.evaluation,I.growth.features,I.growth.experiments,I.growth.savedGroups];if(d?.key===S&&!Ie(d.body,k))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==S&&(d={key:S,body:k,program:ke(I)}),i={key:S,configuration:I,expiresAt:w,program:d.program},i})();l=m;try{return await m}finally{l===m&&(l=void 0)}}function y(){return l??(i&&!p(i)?Promise.resolve(i):f())}return{session(g){let m=s;return xe(g,y,v=>{if(e.assertUsable?.(),m!==s)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(v&&(p(v)||i?.key!==v.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){s++,i=void 0,l=void 0,d=void 0}}}function Qe(e,t){let n=e.snapshot?.generation,c=P({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),i=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,c.refresh().catch(()=>{}))}),l=c.session;return Object.assign(c,{session(d){let s=l(d),p=s.evaluate;return Object.assign(s,{async evaluate(...f){return e.fresh||await e.refresh(),p(...f)}})},destroy(){i(),c.reset()}})}function $e(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>ge(e,t)}}function De(e,t,n){return de(e,t,n,fe)}var b=class extends o{constructor(n,c){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,c);this.decisionId=n;this.decisionRequestId=c}decisionId;decisionRequestId};async function U(e,t,n,c){let{decisionId:i,requestId:l}=e,d=e,s=250,p=0;for(;;){if(d.decisionId!==i||d.requestId!==l||d.decision&&!T(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,l);if(Date.now()>=n)throw new b(i,l);if(await new Promise(f=>setTimeout(f,Math.min(Math.max(s,p-Date.now()),n-Date.now()))),Date.now()>=n)throw new b(i,l);s=Math.min(1e3,s*2);try{d=await c(i,n)}catch(f){if(f instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(f.code)){p=Date.now()+(f.retryAfterSeconds??0)*1e3;continue}throw f}}}function z(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new o("SERVER_ONLY","Funnel decisions are requested by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t,n,c=new Map;async function i(p,f){let y=p;y.status!=="pending"&&c.delete(y.decisionId);for(let g=0;g<32&&y.evaluation;g++){let m=y.evaluation;if(m.runId!==y.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let v=c.get(y.decisionId);if(!v&&m.type==="evaluate_segment"){let w=me.parse(await l({operation:"segment_configuration",funnelId:e.funnelId,versionId:m.versionId},f));if(w.configuration.scope.projectId!==e.scope.projectId||w.configuration.scope.environment!==e.scope.environment||w.configuration.funnelId!==e.funnelId||w.configuration.versionId!==m.versionId||w.configuration.evaluationRevision!==m.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(c.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");v={operation:"commit_decision_segment",decisionId:y.decisionId,requestId:j(y.decisionId,m.visit,`segment:${m.revision}`),nodeId:m.nodeId,visit:m.visit,revision:m.revision,policyRevision:m.policyRevision,generation:w.configuration.growth.generation,...ve(w.configuration,w.document,m)},c.set(y.decisionId,v)}if(!v){if(m.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==m.versionId||n.evaluationRevision!==m.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=D.parse(await l({operation:"configuration",funnelId:e.funnelId,versionId:m.versionId},f))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==m.versionId||n.evaluationRevision!==m.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(c.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");v={operation:"evaluate_decision",decisionId:y.decisionId,requestId:j(y.decisionId,m.visit,"evaluation"),nodeId:m.nodeId,visit:m.visit,revision:m.revision,receiptId:m.receiptId,policyRevision:m.policyRevision,generation:n.growth.generation,result:De(n,m.nodeId,m)},c.set(y.decisionId,v)}let I=O.parse(await l(v,f));if(I.decisionId!==p.decisionId||I.requestId!==p.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");c.delete(y.decisionId),y=I}return y}async function l(p,f,y=!1){let g=A({...e,fetch:(m,v)=>{let I=new Headers(v?.headers);return I.set("Accept-Encoding","identity"),y&&I.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(m,{...v,headers:I})},timeoutMs:Math.min(e.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)});return g.identify(e.apiKey),g.request("funnels",p)}async function d(p,f){let y=O.parse(await l(_.parse({operation:"read_decision",decisionId:p}),f));if(y.decisionId!==p)throw new o("INVALID_RESPONSE","Decision identity changed");return i(y,f)}async function s(p,f,y=!1){let g=_.options[0].parse({...p,operation:"decide",funnelId:e.funnelId}),m;try{m=O.parse(await l(g,f,y))}catch(v){throw v instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(v.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",v.status,p.requestId):v}if(m.requestId!==p.requestId||m.decision&&!T(m.decision,g.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await i(m,f),customer:g.customer}}return{local(){return t??=P({scope:e.scope,funnelId:e.funnelId,load:()=>l({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let p=D.parse(await l({operation:"configuration",funnelId:e.funnelId}));if(p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment||p.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return p},features(p={}){return K({...p,scope:e.scope,load:async()=>ne.parse(await l({operation:"feature_config",funnelId:e.funnelId}))})},read:p=>d(p),async submit(p){return(await s(p,void 0,!0)).response},async decide(p){let f=Date.now()+3e4,y=await s(p,f);return U(y.response,y.customer,f,d)},async reportUsed(p){let f=ie.parse(await l(_.parse({...p,operation:"report_used"})));if(f.decisionId!==p.decisionId||f.eventId!==p.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function Je(e){if(typeof window<"u")throw new o("SERVER_ONLY","Native receipts are verified by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","Server API key required");let t=A({...e,timeoutMs:e.timeoutMs??35e3});return t.identify(e.apiKey),{async recover(n){let c=pe.parse(n);if(c.orderId!==c.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let i=c.nativeEvidence,l={requestId:c.requestId,customerToken:c.customerToken,purchaseIntentId:c.orderId,...i===null?{intent:"read"}:i.provider==="apple"?{provider:"apple",signedTransaction:i.signedTransaction}:{provider:"google",purchaseToken:i.purchaseToken}},d=r.restoreNativePurchase.response.parse(await t.request(r.restoreNativePurchase.path,l));if(d.operation.requestId!==c.requestId||d.operation.purchaseIntentId!==c.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let s=le.parse({scope:d.scope,requestId:c.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(s.requestId!==c.requestId||s.orderId!==c.orderId||s.receiptId!==c.receiptId||s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return s}}}import{z as Ze}from"zod";var C=Ze.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function We(e,t){let n=C.parse(e.inputTokens.total),c=C.parse(e.outputTokens.total),i=C.parse(e.inputTokens.cacheRead??0),l=C.parse(e.inputTokens.cacheWrite??0),d=C.parse(e.outputTokens.reasoning??0);if(i+l>n||d>c||e.inputTokens.noCache!==void 0&&C.parse(e.inputTokens.noCache)!==n-i-l||e.outputTokens.text!==void 0&&C.parse(e.outputTokens.text)!==c-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-i-l,cache_read:i,cache_write:l,output:t==="output"?c:c-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Xe(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(c){await e.persist({context:c,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(c,i){let l={context:c,modelId:e.modelId,usage:i,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(l);let d=e.mapTokens?e.mapTokens(i):We(i,e.reasoning),s=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...l,tokens:d,quote:s,phase:"quoted"});let p=await e.pricing.trackTokens(e.client,{...c,quote:s});if(!p.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...l,tokens:d,quote:s,receipt:p,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:c}){let i=await e.context(),l;try{l=await c()}catch(d){throw await t(i),d}return await n(i,l.usage),l},async wrapStream({doStream:c}){let i=await e.context(),l;try{l=await c()}catch(y){throw await t(i),y}let d=!1,s=!1,p=l.stream.getReader();async function f(){d||s||(s=!0,await t(i))}return{...l,stream:new ReadableStream({async pull(y){try{let{value:g,done:m}=await p.read();if(m){if(!d)throw await f(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");y.close();return}if(g.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(i,g.usage)}y.enqueue(g)}catch(g){try{await f()}finally{y.error(g),await p.cancel(g)}}},async cancel(y){try{await f()}finally{await p.cancel(y)}}})}}}}function en(e){if(typeof window<"u")throw new o("SERVER_ONLY","Funnel receipts are sent by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t=A(e);return t.identify(e.apiKey),{async signal(n){let c=G.parse({...n,operation:"signal"}),i=oe.parse(await t.request("funnels",c));if(i.runId!==n.runId||i.eventId!==n.eventId||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return i},async readResults(n){let c=G.parse({operation:"read_results",runId:n}),i=ae.parse(await t.request("funnels",c));if(i.runId!==n||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return i}}}function nn(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new o("SERVER_ONLY","Campaign entry requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new o("INVALID_TOKEN","A server API key is required");let t=A({...e,timeoutMs:e.timeoutMs??35e3});return t.identify(e.apiKey),{async decide(n){let c=Date.now()+(e.timeoutMs??3e4),i=q.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),l=A({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,c-Date.now()))});l.identify(e.apiKey);let d=O.parse(await l.request("funnels",i));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return U(d,i.customer,c,(s,p)=>z({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,p-Date.now()))}).read(s))},async start(n){let c=q.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),i=ce.parse(await t.request("funnels",c)),l=se.parse("suppressed"in i?i:await N(e,i));if(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in l)&&(l.run.source.id!==e.funnelId||!l.customerId||c.customer.type==="id"&&l.customerId!==c.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return l}}}export{b as FunnelDecisionTimeoutError,o as IndianaError,Be as aiPriceSnapshotSchema,Ge as aiTokenQuoteSchema,je as createAiPricing,Xe as createAiUsageMiddleware,Pe as createConfigurationSync,qe as createConfiguredAiPricing,K as createFeatureClient,nn as createFunnelCampaignClient,z as createFunnelDecisionClient,P as createFunnelLocalEvaluator,en as createFunnelOrchestrationClient,Me as createFunnelStartClient,ze as createGuestToken,Ke as createIndianaServer,Ve as createLocalFunnelClient,Je as createNativeReceiptClient,$e as createPaywallStartClient,Qe as createSynchronizedFunnelLocalEvaluator,Ue as evaluateFunnelNode,Ye as renewFunnelRun};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as Ha,$a as lc,$b as td,$c as lg,$d as lh,$e as ri,$f as xj,$g as xk,$h as xl,$i as xm,$j as yn,A as Y,Aa as Hb,Ab as Mc,Ac as ce,Ad as Mg,Ae as Mh,Af as Yi,Ag as Yj,Ah as Yk,Ai as Yl,Aj as Ym,Ak as co,B as Z,Ba as Ib,Bb as Nc,Bc as Nf,Bd as Ng,Be as Nh,Bf as Zi,Bg as Zj,Bh as Zk,Bi as Zl,Bj as Zm,Bk as eo,C as _,Ca as Jb,Cb as Oc,Cc as Of,Cd as Og,Ce as Oh,Cf as _i,Cg as _j,Ch as _k,Ci as _l,Cj as _m,Ck as fo,D as $,Da as Kb,Db as Pc,Dc as Pf,Dd as Pg,De as Ph,Df as $i,Dg as $j,Dh as $k,Di as $l,Dj as $m,E as aa,Ea as Lb,Eb as Qc,Ec as Qf,Ed as Qg,Ee as Qh,Ef as aj,Eg as ak,Eh as al,Ei as am,Ej as an,F as ba,Fa as Mb,Fb as Rc,Fc as Rf,Fd as Rg,Fe as Rh,Ff as bj,Fg as bk,Fh as bl,Fi as bm,Fj as bn,G as ma,Ga as Nb,Gb as Sc,Gc as Sf,Gd as Sg,Ge as Sh,Gf as cj,Gg as ck,Gh as cl,Gi as cm,Gj as cn,H as na,Ha as Tb,Hb as Tc,Hc as Tf,Hd as Tg,He as Th,Hf as dj,Hg as dk,Hh as dl,Hi as dm,Hj as dn,I as oa,Ia as Ub,Ib as Uc,Ic as Uf,Id as Ug,Ie as Uh,If as ej,Ig as ek,Ih as el,Ii as em,Ij as en,J as pa,Ja as Vb,Jb as Vc,Jc as Vf,Jd as Vg,Je as Vh,Jf as fj,Jg as fk,Jh as fl,Ji as fm,Jj as fn,K as qa,Ka as Wb,Kb as Wc,Kc as Wf,Kd as Wg,Ke as Wh,Kf as gj,Kg as gk,Kh as gl,Ki as gm,Kj as gn,L as ra,La as Xb,Lb as Xc,Lc as Xf,Ld as Xg,Le as Xh,Lf as hj,Lg as hk,Lh as hl,Li as hm,Lj as hn,M as sa,Ma as Yb,Mb as Yc,Mc as Yf,Md as Yg,Me as Yh,Mf as ij,Mg as ik,Mh as il,Mi as im,Mj as jn,N as ta,Na as Zb,Nb as Zc,Nc as Zf,Nd as Zg,Ne as Zh,Nf as jj,Ng as jk,Nh as jl,Ni as jm,Nj as kn,O as ua,Oa as _b,Ob as _c,Oc as _f,Od as _g,Oe as _h,Of as kj,Og as kk,Oh as kl,Oi as km,Oj as ln,P as va,Pa as $b,Pb as $c,Pc as $f,Pd as $g,Pe as $h,Pf as lj,Pg as lk,Ph as ll,Pi as lm,Pj as mn,Q as wa,Qa as ac,Qb as ad,Qc as ag,Qd as ah,Qe as ai,Qf as mj,Qg as mk,Qh as ml,Qi as mm,Qj as nn,R as xa,Ra as bc,Rb as bd,Rc as bg,Rd as bh,Re as bi,Rf as nj,Rg as nk,Rh as nl,Ri as nm,Rj as on,S as ya,Sa as cc,Sb as cd,Sc as cg,Sd as ch,Se as ci,Sf as oj,Sg as ok,Sh as ol,Si as om,Sj as pn,T as za,Ta as dc,Tb as dd,Tc as dg,Td as dh,Te as di,Tf as pj,Tg as pk,Th as pl,Ti as pm,Tj as qn,U as Aa,Ua as ec,Ub as ed,Uc as eg,Ud as eh,Ue as ei,Uf as qj,Ug as qk,Uh as ql,Ui as qm,Uj as rn,V as Ba,Va as fc,Vb as fd,Vc as fg,Vd as fh,Ve as fi,Vf as rj,Vg as rk,Vh as rl,Vi as rm,Vj as sn,W as Ca,Wa as gc,Wb as gd,Wc as gg,Wd as gh,We as gi,Wf as sj,Wg as sk,Wh as sl,Wi as sm,Wj as tn,X as Da,Xa as hc,Xb as hd,Xc as hg,Xd as hh,Xe as hi,Xf as tj,Xg as tk,Xh as tl,Xi as tm,Xj as un,Y as Ea,Ya as ic,Yb as qd,Yc as ig,Yd as ih,Ye as ii,Yf as uj,Yg as uk,Yh as ul,Yi as um,Yj as vn,Z as Fa,Za as jc,Zb as rd,Zc as jg,Zd as jh,Ze as ji,Zf as vj,Zg as vk,Zh as vl,Zi as vm,Zj as wn,_ as Ga,_a as kc,_b as sd,_c as kg,_d as kh,_e as ki,_f as wj,_g as wk,_h as wl,_i as wm,_j as xn,a as c,aa as Ia,ab as mc,ac as ud,ad as mg,ae as mh,af as si,ag as yj,ah as yk,ai as yl,aj as ym,ak as zn,b as d,ba as Ja,bb as nc,bc as vd,bd as ng,be as nh,bf as ti,bg as zj,bh as zk,bi as zl,bj as zm,bk as An,c as e,ca as Ka,cb as oc,cc as wd,cd as og,ce as oh,cf as ui,cg as Aj,ch as Ak,ci as Al,cj as Am,ck as Bn,d as f,da as La,db as pc,dc as xd,dd as pg,de as ph,df as vi,dg as Bj,dh as Bk,di as Bl,dj as Bm,dk as Cn,e as g,ea as Ma,eb as qc,ec as yd,ed as qg,ee as qh,ef as wi,eg as Cj,eh as Ck,ei as Cl,ej as Cm,ek as Dn,f as h,fa as Na,fb as rc,fc as zd,fd as rg,fe as rh,ff as xi,fg as Dj,fh as Dk,fi as Dl,fj as Dm,fk as En,g as i,ga as Oa,gb as sc,gc as Kd,gd as sg,ge as sh,gf as yi,gg as Ej,gh as Ek,gi as El,gj as Em,gk as Fn,h as j,ha as Pa,hb as tc,hc as Ld,hd as tg,he as th,hf as zi,hg as Fj,hh as Fk,hi as Fl,hj as Fm,hk as Gn,i as k,ia as Qa,ib as uc,ic as Md,id as ug,ie as uh,if as Ai,ig as Gj,ih as Gk,ii as Gl,ij as Gm,ik as Hn,j as l,ja as Ra,jb as vc,jc as Nd,jd as vg,je as vh,jf as Bi,jg as Hj,jh as Hk,ji as Hl,jj as Hm,jk as In,k as m,ka as Sa,kb as wc,kc as Od,kd as wg,ke as wh,kf as Ci,kg as Ij,kh as Ik,ki as Il,kj as Im,kk as Jn,l as n,la as Ta,lb as xc,lc as Pd,ld as xg,le as xh,lf as Di,lg as Jj,lh as Jk,li as Jl,lj as Jm,lk as Kn,m as o,ma as Ua,mb as yc,mc as Qd,md as yg,me as yh,mf as Ki,mg as Kj,mh as Kk,mi as Kl,mj as Km,mk as Ln,n as p,na as Va,nb as zc,nc as Rd,nd as zg,ne as zh,nf as Li,ng as Lj,nh as Lk,ni as Ll,nj as Lm,nk as Rn,o as G,oa as Wa,ob as Ac,oc as Sd,od as Ag,oe as Ah,of as Mi,og as Mj,oh as Mk,oi as Ml,oj as Mm,ok as Sn,p as H,pa as Xa,pb as Bc,pc as Td,pd as Bg,pe as Bh,pf as Ni,pg as Nj,ph as Nk,pi as Nl,pj as Nm,pk as Tn,q as I,qa as Ya,qb as Cc,qc as Ud,qd as Cg,qe as Ch,qf as Oi,qg as Oj,qh as Ok,qi as Ol,qj as Om,qk as Un,r as J,ra as Za,rb as Dc,rc as Vd,rd as Dg,re as Dh,rf as Pi,rg as Pj,rh as Pk,ri as Pl,rj as Pm,rk as Vn,s as K,sa as _a,sb as Ec,sc as Wd,sd as Eg,se as Eh,sf as Qi,sg as Qj,sh as Qk,si as Ql,sj as Qm,sk as Wn,t as L,ta as Ab,tb as Fc,tc as Xd,td as Fg,te as Fh,tf as Ri,tg as Rj,th as Rk,ti as Rl,tj as Rm,tk as Xn,u as M,ua as Bb,ub as Gc,uc as Yd,ud as Gg,ue as Gh,uf as Si,ug as Sj,uh as Sk,ui as Sl,uj as Sm,uk as Yn,v as N,va as Cb,vb as Hc,vc as Zd,vd as Hg,ve as Hh,vf as Ti,vg as Tj,vh as Tk,vi as Tl,vj as Tm,vk as Zn,w as O,wa as Db,wb as Ic,wc as _d,wd as Ig,we as Ih,wf as Ui,wg as Uj,wh as Uk,wi as Ul,wj as Um,wk as _n,x as P,xa as Eb,xb as Jc,xc as $d,xd as Jg,xe as Jh,xf as Vi,xg as Vj,xh as Vk,xi as Vl,xj as Vm,xk as $n,y as Q,ya as Fb,yb as Kc,yc as ae,yd as Kg,ye as Kh,yf as Wi,yg as Wj,yh as Wk,yi as Wl,yj as Wm,yk as ao,z as R,za as Gb,zb as Lc,zc as be,zd as Lg,ze as Lh,zf as Xi,zg as Xj,zh as Xk,zi as Xl,zj as Xm,zk as bo}from"./chunk-EJTBSGLV.js";import{$ as Id,$a as bf,A as ga,Aa as Ce,Ab as Df,B as ha,Ba as De,Bb as Ef,C as ia,Ca as Ee,Cb as Ff,D as ja,Da as Fe,Db as Gf,E as ka,Ea as Ge,Eb as Hf,F as la,Fa as He,Fb as If,G as Ob,Ga as Ie,Gb as Jf,H as Pb,Ha as Je,Hb as Kf,I as Qb,Ia as Ke,Ib as Lf,J as Rb,Ja as Le,Jb as Mf,K as Sb,Ka as Me,Kb as Ei,L as id,La as Ne,Lb as Fi,M as jd,Ma as Oe,Mb as Gi,N as kd,Na as Pe,Nb as Hi,O as ld,Oa as Qe,Ob as Ii,P as md,Pa as Re,Pb as Ji,Q as nd,Qa as Se,R as od,Ra as Te,S as pd,Sa as Ue,T as Ad,Ta as Ve,U as Bd,Ua as We,V as Cd,Va as Xe,W as Dd,Wa as Ye,X as Ed,Xa as Ze,Y as Fd,Ya as _e,Z as Gd,Za as $e,_ as Hd,_a as af,a as q,aa as Jd,ab as cf,b as r,ba as de,bb as df,c as s,ca as ee,cb as ef,d as t,da as fe,db as ff,e as u,ea as ge,eb as gf,f as v,fa as he,fb as hf,g as w,ga as ie,gb as jf,h as x,ha as je,hb as kf,i as y,ia as ke,ib as lf,j as z,ja as le,jb as mf,k as A,ka as me,kb as nf,l as B,la as ne,lb as of,m as C,ma as oe,mb as pf,n as D,na as pe,nb as qf,o as E,oa as qe,ob as rf,p as F,pa as re,pb as sf,q as S,qa as se,qb as tf,r as T,ra as te,rb as uf,s as U,sa as ue,sb as vf,t as V,ta as ve,tb as wf,u as W,ua as we,ub as xf,v as X,va as xe,vb as yf,w as ca,wa as ye,wb as zf,x as da,xa as ze,xb as Af,y as ea,ya as Ae,yb as Bf,z as fa,za as Be,zb as Cf}from"./chunk-LMR2TM3X.js";import{a,b,c as li,d as mi,e as ni,f as oi,g as pi,h as qi,j as Mn,k as Nn,l as On,m as Pn,n as Qn}from"./chunk-OBYJWIRB.js";import{a as hb,b as ib,c as jb,d as kb,e as lb,f as mb,g as nb,h as ob,i as pb,j as qb,k as rb,l as sb,m as tb,n as ub,o as vb,p as wb,q as xb,r as yb,s as zb}from"./chunk-RRII2DMC.js";import{c as $a,d as ab,e as bb,h as cb,i as db,j as eb,k as fb,l as gb}from"./chunk-KQCTDXVD.js";export{Ml as CODE_REFERENCE_LIMITS,Rb as COMMON_LOCALES,Ek as CONFIGURATION_POLICY,fg as CONTENT_DOCUMENT_BYTES,Tb as COUPON_TERM_LOCALES,Be as CUSTOMER_DATA_SOURCES,Cg as CreateInvoiceParamsSchema,Bg as CreateInvoicePreviewSchema,Pi as DEFAULT_FUNNEL_EXECUTION_POLICY,Jj as FUNNEL_API_CAPABILITIES,Wj as FUNNEL_EXECUTION_LIMITS,Xi as FUNNEL_LIMITS,Xj as FUNNEL_RECORDING_LIMITS,Tn as FUNNEL_SEGMENT_BYTES,Sn as FUNNEL_SEGMENT_LIMIT,Mm as FUNNEL_SERVER_KEY_HEADER,Zj as FUNNEL_TRANSITION_BUDGET_MESSAGE,Am as FunnelCalculationError,$n as FunnelLocalCalculationError,zg as InvoiceModeParamsSchema,Ag as InvoiceTemplateSchema,Sd as MSG_CHANNEL_METERS,Pd as MSG_CHANNEL_PROVIDERS,Bh as OFFERING_MAX_DEPTH,Dh as OFFERING_MAX_ITEMS,Ch as OFFERING_MAX_PRODUCTS,wf as POPUP_WIDTHS,vk as PUBLIC_PAYWALL_UNSUPPORTED_NODES,yg as ReissueInvoiceParamsSchema,Me as SCREEN_LIMITS,Le as SCREEN_SCHEMA_VERSION,G as SDK_PROTOCOL_HEADER,I as SDK_SUPPORT_HEADER,J as SDK_SUPPORT_POLICY,H as SDK_VERSION_HEADER,uf as SURFACE_PATHS,oe as SURFACE_VARIABLES,P as SdkProtocolError,Yi as UNBOUND_PRODUCT_VERSION_ID,N as addSupportMonths,Ra as aiCreditSystemConfigSchema,$k as aiMarkupSchema,_k as aiModelIdSchema,al as aiModelRatesSchema,bl as aiPricingConfigurationSchema,Zk as aiTokenPools,V as amountToMinor,ii as analyticsConfigSchema,ki as analyticsEventEnabled,v as apiErrorCatalog,w as apiErrorCodeForStatus,q as apiErrorCodeSchema,um as apiOperations,nm as apiPermissionSchema,zm as archiveSurfaceTemplateSchema,tc as autoTopupPurchaseLimitSchema,Fc as autoTopupStateSchema,Jn as autumnAmountToMinor,hn as autumnCustomerAutoTopupSchema,nn as autumnCustomerControlsSchema,pn as autumnCustomerMetadataSchema,mn as autumnCustomerOverageAllowedSchema,rn as autumnCustomerProductSummarySchema,qn as autumnCustomerProfileRecordSchema,jn as autumnCustomerSpendLimitSchema,ln as autumnCustomerUsageAlertSchema,kn as autumnCustomerUsageLimitSchema,on as autumnEntityControlsSchema,Kn as autumnMinorToAmount,Ln as autumnUsageUnitAmountDecimal,Uk as balanceAdjustmentCommandSchema,Vk as balanceAdjustmentStateSchema,md as balanceAllocationSchema,jd as balanceCommandSchema,rd as balanceGrantCommandSchema,qd as balanceGrantCreateSchema,ud as balanceGrantPageSchema,td as balanceGrantReadSchema,sd as balanceGrantSchema,pd as balanceOperationSchema,kd as balancePricingSegmentSchema,od as balanceQuoteSchema,ld as balanceReceiptUnitsSchema,nd as balanceRejectionReasonSchema,Wk as balanceSourceStateSchema,_m as bannerVersionReferenceSchema,mc as billingAccruedMinorSchema,lc as billingAmountMinorSchema,wc as billingAuthorizationSchema,vc as billingAuthorizationTermsSchema,nc as billingBudgetMinorSchema,Gc as billingControlInputSchema,Hc as billingControlsSchema,Pc as billingCouponsSchema,Y as billingCurrencies,Ic as billingInvoiceLineSchema,Jc as billingInvoiceSchema,Mc as billingInvoicesSchema,Ac as billingLimitSchema,aa as billingSettingsMutationSchema,_ as billingSettingsSchema,$ as billingSettingsScopeSchema,Ec as billingUsageWindowSchema,_e as borderSchema,ef as buttonNodeSchema,Bm as calculateFunnelNode,co as calculateLocalFunnelEvaluation,eo as calculateLocalFunnelSegment,Pb as canonicalLocale,pe as capabilityBindingSchema,rc as cashPriceSchema,pc as cashPricingSchema,oc as cashPricingTiersSchema,kc as cashUnitAmountMinorSchema,Cl as claimRewardProductRequestSchema,Pl as codeReferenceBranchSchema,Vl as codeReferenceConfigRequestSchema,Ul as codeReferenceConfigureSchema,$l as codeReferenceFeatureSummarySchema,Nl as codeReferenceKeySchema,Ql as codeReferencePathSchema,Yl as codeReferenceReceiptSchema,Ol as codeReferenceRepoSchema,Xl as codeReferenceReportSchema,Sl as codeReferenceRepositoryInputSchema,Tl as codeReferenceRepositorySchema,Wl as codeReferenceScanConfigSchema,Zl as codeReferenceScanSchema,_l as codeReferenceSettingsSchema,am as codeReferenceSummarySchema,fe as commerceAccessSchema,he as commerceContextSchema,mh as commerceCursorSchema,nh as commerceListQuerySchema,ge as commerceMoneySchema,An as commerceProductKind,ee as commerceProductKindSchema,de as commerceProviderSchema,sb as compileGrowthFeatures,Jb as conditionUsesMerchandise,Hk as configurationArtifactSchema,Nk as configurationDependencies,Gk as configurationDependenciesSchema,Lk as configurationDigest,Ik as configurationFunnelSchema,Mk as configurationGeneration,Kk as configurationJson,Dk as configurationPaywallSchema,Fk as configurationScopeSchema,Kc as confirmBillingAdjustmentInputSchema,yc as confirmBillingAuthorizationInputSchema,s as consoleErrorCodeSchema,E as consoleErrorResponseSchema,Yg as consoleRefundRequestSchema,ng as contentCollectionSchema,hg as contentContractSchema,ig as contentDocumentDraftSchema,kg as contentDocumentSchema,eg as contentKindSchema,mg as contentRecordSchema,lg as contentSummarySchema,jg as contentValueMatches,gg as contentValueSchema,og as contentVersionSchema,pg as contentVersionSummarySchema,qg as contentWriteSchema,mf as countdownNodeSchema,_b as couponAppliesToSchema,ec as couponChangeErrors,lf as couponCodeNodeSchema,gi as couponContentDigestSchema,Yb as couponDiscountSchema,tk as couponDisplaySchema,Zb as couponDurationSchema,ac as couponEligibilitySchema,bc as couponInputSchema,Lb as couponMerchandiseCondition,Mb as couponMerchandiseScope,$b as couponPublicAppliesToSchema,bm as couponRedemptionCommandSchema,cm as couponRedemptionReceiptSchema,Xb as couponStatusSchema,hc as couponWindow,qm as createCustomerRequestSchema,rm as createCustomerResponseSchema,El as createReferralCodeRequestSchema,ca as creditAmountSchema,el as creditAnalyticsFilterSchema,gl as creditAnalyticsPageSchema,fl as creditAnalyticsQuerySchema,cl as creditAnalyticsRangeSchema,dl as creditAnalyticsTimezoneSchema,ia as creditDimensionSchema,ja as creditMultiplierSchema,ea as creditPriceAdjustmentSchema,ka as creditPricingSchema,ga as creditPropertiesSchema,da as creditQuantitySchema,la as creditRateSchema,Rc as creditResetCountSchema,Qc as creditResetSchema,fa as creditResourceKeySchema,Sc as creditRolloverSchema,Ka as creditSchemaItemSchema,yd as creditStatementInputSchema,zd as creditStatementSchema,Qa as creditSystemConfigSchema,ha as creditTiersSchema,S as currencies,Z as currencyAmountOptionsSchema,U as currencyDecimals,T as currencySchema,vm as currentApiOperations,jf as customHtmlNodeSchema,Ha as customerActivitySchema,fj as customerAttributesSchema,De as customerDataConfigSchema,Ge as customerDataIntentSchema,gf as customerDataNodeSchema,lj as customerDataReferenceMessage,kj as customerDataReferenced,jj as customerDataSchema,Ce as customerDataSourceSchema,tm as customerEntitlementsSchema,sj as customerFiltersSchema,gj as customerFingerprintSchema,qj as customerGetSchema,Ed as customerHoldingsSchema,hj as customerInputSchema,Id as customerLedgerEntrySchema,Jd as customerLedgerPageSchema,Hd as customerLedgerQuerySchema,oj as customerLookupSchema,nj as customerMutationSchema,Fe as customerPageDataSchema,Ee as customerPageNodeStateSchema,tj as customerPageSchema,pj as customerPatchSchema,Ga as customerPlanSchema,mj as customerProfileSchema,ij as customerReferenceSchema,ej as customerTagsSchema,rj as customerUpdateRequestSchema,Rl as defaultCodeReferenceMethods,Lm as deliveredFunnelResponse,Sk as deliveredPaywall,zi as deliveredScreenDocument,Nb as deriveSavedGroupSubjects,fc as describeCoupon,bd as diffProductVariant,ff as dividerNodeSchema,He as emptyCustomerPageNode,je as entitlementCheckInputSchema,ke as entitlementCheckReasonSchema,me as entitlementCheckResultSchema,ie as entitlementRequirementSchema,Da as entitlementSnapshotSchema,sm as entitlementStatusSchema,a as environmentSchema,z as errorCodeMatchesStatus,F as errorMetadata,B as errorMetadataSchema,y as errorPolicy,u as errorReasonSchema,t as errorRecoverySchema,C as errorResponseSchema,Je as escapeHtmlText,fn as estimateMsgSmsSegments,db as evalCondition,gb as evalFeature,ti as evaluateFeaturesRequestSchema,vi as evaluateFeaturesResultSchema,bo as evaluateLocalFunnelNode,Hm as executionSourceSchema,_n as expandFunnelSegment,rb as experimentConfigurationSchema,qb as experimentPhaseSchema,vb as experimentSnapshotSchema,Va as featureCollectionSchema,Oa as featureConfigOverrideSchema,Sa as featureDefinitionSchema,ri as featureDeliveryPayloadSchema,Ia as featureIdSchema,wa as featureInputSchema,Na as featureMarkupsOverrideSchema,Wa as featureOptionsSchema,qi as featurePayloadSchema,Ua as featureRecordSchema,xa as featureSchema,Ta as featureUpdateRulesSchema,Ad as featureUsageReadSchema,Bd as featureUsageSetSchema,Cd as featureUsageStateSchema,Ja as featureUsageTypeSchema,Xa as featureWriteSchema,Cf as fieldValue,Ye as fillSchema,Dd as financialAmountSchema,Gd as financialCursorSchema,Fd as financialEntryTypeSchema,Kf as findDocumentNode,Jf as findNode,en as formatCouponConditions,Vb as formatCouponDiscount,Ub as formatCouponMoney,Wb as formatCouponTerms,X as formatCurrencyMinor,Dn as formatProductBillingPeriod,gc as formatUsd,Kj as funnelApiBindingSchema,Hj as funnelApiProjectionSchema,an as funnelAuthorDraftSchema,Aj as funnelBundleDefinitionSchema,Ej as funnelBundleLiterals,Dj as funnelBundleResultSchema,Bj as funnelBundleSelectionSchema,Qm as funnelCampaignCommandSchema,Sm as funnelCampaignStartDeliverySchema,Rm as funnelCampaignStartResponseSchema,Lj as funnelCapabilitySchema,rk as funnelCommandSchema,Um as funnelConfigurationSchema,$j as funnelConsumedVariables,$m as funnelContentDraftSchema,bn as funnelContentPublishedSchema,Zm as funnelContentReferenceSchema,Zn as funnelContextDelta,Nm as funnelCredentialCommandSchema,Pm as funnelCredentialDeliverySchema,Om as funnelCredentialResponseSchema,qk as funnelDataQueriesSchema,wj as funnelDecideShape,xj as funnelDecisionCommandSchema,aj as funnelDecisionEvaluationSchema,uj as funnelDecisionOutputSchema,yj as funnelDecisionResponseSchema,vj as funnelDecisionSchema,dj as funnelDecisionSegmentEvaluationSchema,zj as funnelDecisionUsedResponseSchema,ik as funnelDocumentDraftSchema,mk as funnelDocumentSchema,Ci as funnelEvaluationAttributes,$i as funnelEvaluationInstructionSchema,Zi as funnelEvaluationModeSchema,_i as funnelEvaluationResultSchema,Oi as funnelExecutionPolicySchema,fk as funnelExecutionStateSchema,Nj as funnelExternalPageUrlSchema,Ni as funnelExternalTaskSchema,Qj as funnelGraphDraftSchema,Pj as funnelGraphNodeSchema,Rj as funnelGraphSchema,Sj as funnelGraphTargets,Gm as funnelInstructionSchema,Cm as funnelInvocationId,Vm as funnelLocalConfigurationSchema,Dm as funnelLocalScreenCommandSchema,Em as funnelLocalScreenResponseSchema,cj as funnelLocalSegmentStepSchema,dk as funnelNodeInputSchema,bk as funnelNodeKindSchema,Tf as funnelNodeProjections,ek as funnelNodeResultSchema,_j as funnelNodeVisitAllowed,Qf as funnelNodeWritesSchema,Oj as funnelOpenInSchema,Ti as funnelOrchestrationCommandSchema,Hi as funnelParametersFromUrl,pk as funnelPresentationSubmissionSchema,Fj as funnelProjectionFilterValueSchema,Gj as funnelProjectionWhereSchema,ok as funnelPublicationDraftSchema,kk as funnelPublicationRules,nk as funnelPublicationSchema,lk as funnelPublishableDraftSchema,Un as funnelPureNode,ck as funnelResourceReferenceSchema,sn as funnelResultsCursorSchema,tn as funnelResultsQuerySchema,Wi as funnelResultsResponseSchema,un as funnelResultsSchema,Im as funnelRunViewSchema,Km as funnelRuntimeDeliverySchema,Jm as funnelRuntimeResponseSchema,Fm as funnelRuntimeStatusSchema,ag as funnelScreenReads,$f as funnelScreenTokens,bg as funnelScreenValues,fo as funnelSegmentConfigurationSchema,bj as funnelSegmentEvaluationInstructionSchema,Vn as funnelSegmentPositionSchema,Xn as funnelSegmentSchema,Wn as funnelSegmentStepSchema,Ui as funnelSignalResponseSchema,Yn as funnelStepId,Mi as funnelTaskBindingSchema,Ki as funnelTaskDataSchema,Li as funnelTaskOutputsSchema,Qi as funnelTaskResponseSchema,Vi as funnelTaskResultsSchema,Wm as funnelTopology,Tm as funnelTopologySchema,gk as funnelTraceEventSchema,Wf as funnelValueBindingSchema,Nf as funnelValueDeclarationSchema,Rf as funnelValueMatches,Vf as funnelValuePathSchema,Bi as funnelValueSchema,Of as funnelVariableDeclarationSchema,Pf as funnelVariableDeclarationsSchema,_f as funnelVariableRead,Sf as funnelVariableValues,Yj as funnelVisitAllowed,ak as funnelWaitKindSchema,mi as gbRuntimeExperimentResultSchema,li as gbRuntimeExperimentSchema,ni as gbRuntimeFeatureRuleSchema,oi as gbRuntimeFeatureSchema,pi as gbRuntimeSavedGroupsSchema,$a as getQueryStringOverride,eb as getStickyBucketAttributes,ib as growthAttributesSchema,lb as growthConditionGroupIds,Ab as growthConditionPaths,jb as growthConditionSchema,tb as growthExperimentStop,ub as growthFeatureExpiry,nb as growthFeatureRuleSchema,ob as growthFeatureSchema,pb as growthFeaturesSchema,kb as growthGroupSchema,yb as growthRuleContextSchema,mb as growthSavedGroupsSchema,wb as growthSnapshotSchema,zb as growthSplitResultSchema,Kb as guardMerchandiseCondition,Ie as htmlVariableErrors,Tk as hydratePaywall,Oe as identifierSchema,df as imageNodeSchema,Xe as imagePositionSchema,Ve as insetsSchema,hm as invoiceCommandSchema,vd as invoiceDetailInputSchema,xd as invoiceDetailSchema,km as invoiceOperationSchema,wd as invoiceProductItemSchema,Xg as invoiceRefundsSchema,gm as invoiceTemplateCommandSchema,fm as invoiceTemplatePageSchema,dm as invoiceTemplateValuesSchema,sc as isInvoiceCreditPrice,Ib as isMerchandiseAttribute,we as isProductGroup,zn as isRecurringMembership,Lf as isRtlLocale,M as isStableSdkProtocol,bb as isURLTargeted,qc as itemBillingCycleSchema,dg as jsonStorageBytes,hb as jsonValueSchema,ba as licenseOfferSchema,Lc as listBillingInvoicesInputSchema,x as localErrorRecovery,Sb as localeLabel,Ob as localeSchema,Df as localeStatuses,If as localizeScreen,Cc as manageBillingLimitsInputSchema,Bc as manageOveragePolicyInputSchema,jm as managedInvoiceDetailSchema,lm as managedInvoicePageSchema,im as managedInvoiceSchema,em as managedInvoiceTemplateSchema,r as managementErrorCodeSchema,D as managementErrorResponseSchema,We as marginSchema,Qb as matchLocale,Di as matchesGrowthCondition,cn as materializeFunnelContent,qa as membershipActionSchema,Bn as membershipBillingCount,ra as membershipChangeSchema,sa as membershipHoldingSchema,oa as membershipRulesSchema,ta as membershipStateSchema,pa as membershipTimingSchema,Cb as merchandiseInputSchema,Eb as merchandiseReferenceSchema,Db as merchandiseSchema,Bb as merchandiseStatusSchema,n as messagingPreferenceSchema,o as messagingPreferenceSetSchema,va as metadataSchema,Pa as meteredConfigSchema,W as minorToAmount,Ma as modelMarkupsSchema,Zd as msgAudienceSchema,_d as msgBroadcastDraftSchema,Nd as msgChannelSchema,Xd as msgContentSchema,ae as msgDispatchStateSchema,Td as msgEmailContentSchema,Rd as msgMeterSchema,Qd as msgPhoneSchema,$d as msgPreferenceInputSchema,Od as msgProviderSchema,Wd as msgPushContentSchema,be as msgReceiptKindSchema,Yd as msgSendInputSchema,Ud as msgSmsContentSchema,ce as msgUsageSummarySchema,gn as msgVoiceBillableSeconds,Vd as msgVoiceContentSchema,wn as nativeCompletionSchema,rg as nativeCouponStoreOfferLinkWriteSchema,sg as nativeCouponStoreOfferLinksSchema,vn as nativeProofSchema,xg as nativePurchaseInstructionSchema,xn as nativeReceiptCommandSchema,yn as nativeReceiptResponseSchema,xh as nativeRestoreCommandSchema,yh as nativeRestoreResultSchema,vg as nativeStoreOfferForProduct,tg as nativeStoreOfferSelectionSchema,ug as nativeStoreOfferSelectionsSchema,wg as nativeStoreSelectionMatches,Pg as nativeSubscriptionUpdatePreviewSchema,Qg as nativeSubscriptionUpdateResultSchema,dc as newCouponInput,ji as newEnvironmentAnalyticsConfig,Ne as nodeIdSchema,jk as offerCopyUnscoped,ic as offerSchema,jc as offerUnavailableReasonSchema,Mh as offeringCollectionSchema,Ih as offeringDocumentSchema,Eh as offeringItemSchema,Fh as offeringItemsSchema,Ah as offeringMetadataSchema,Jh as offeringProductEvidenceSchema,zh as offeringProductIdSchema,Gh as offeringProductIds,Qh as offeringProductOptionSchema,Hh as offeringProductPaths,Sh as offeringPublicationIssues,Kh as offeringRecordSchema,Ph as offeringSelectorSchema,Th as offeringValueSchema,Lh as offeringVersionSchema,Rh as offeringWorkspaceSchema,Oh as offeringWriteResultSchema,Nh as offeringWriteSchema,id as overageBehaviorSchema,Dc as overagePolicySchema,hk as ownedFunnelScreenSchema,Gn as pageExperimentEventSchema,Hn as pageExperimentEventsRequestSchema,In as pageExperimentEventsResponseSchema,Fn as pageExperimentPayloadSchema,En as pageExperimentSchema,Te as paintColorSchema,Ok as parsePublicFunnel,A as parseRetryAfter,gh as paymentSetupCommandSchema,hh as paymentSetupReadSchema,jh as paymentSetupSchema,le as paywallCandidateSchema,Yh as paywallClientActionSchema,ci as paywallCollectionSchema,Rk as paywallDeliverySchema,Zh as paywallDocumentDraftSchema,_h as paywallDocumentSchema,ai as paywallFlowIssues,fi as paywallLibrarySchema,$h as paywallProductIssues,Uh as paywallProductsSchema,bi as paywallRecordSchema,ne as paywallRequestSchema,Qk as paywallResolutionSchema,Pk as paywallResolveInputSchema,di as paywallSummarySchema,ei as paywallWriteSchema,Aa as planConfigSchema,Ba as planInputSchema,za as planItemSchema,nf as planPickerNodeSchema,Ca as planSchema,Ea as planVersionSchema,gd as prepaidAllowanceAmount,Za as prepaidPriceAmount,_a as prepaidQuantityAmount,hd as prepaidQuantitySchema,Ya as prepaidTierPricingSchema,uc as prepareBillingAuthorizationInputSchema,ao as prepareLocalFunnelNodes,cb as prepareSavedGroups,xc as preparedBillingAuthorizationSchema,vf as presentationSchema,kf as priceNodeSchema,ya as priceSchema,Vc as productAllowanceSchema,ed as productCollectionSchema,Yc as productConfigurationSchema,$c as productDefinitionSchema,fd as productEditorOptionsSchema,Ae as productGroupingMatches,ze as productGroupingSchema,Xc as productLicenseSchema,cd as productOptionsSchema,Uc as productPrepaidPriceSchema,Tc as productPricesSchema,dd as productRecordSchema,Wh as productSelectionSchema,Wc as productTrialSchema,Zc as productVariantOverridesSchema,_c as productVariantSchema,Ij as projectFunnelApiOutputs,Xm as projectFunnelConfiguration,Ym as projectFunnelLocalConfiguration,cc as promotionCodeInputSchema,L as protocolForSdkVersion,La as providerMarkupsSchema,hi as publicCouponScreenDataSchema,si as publicFeatureConfigurationSchema,Rn as publicFunnelDocument,xk as publicPaywallBenefitSchema,Bk as publicPaywallButtonSchema,yk as publicPaywallChannelsSchema,Ak as publicPaywallCouponSchema,wk as publicPaywallPriceSchema,zk as publicPaywallProductSchema,Ck as publicPaywallSchema,Ai as publicScreenDocument,yi as publicScreenIssues,Ef as publishChecks,ph as purchaseListItemSchema,vh as purchaseListPageSchema,i as pushAddressRequestSchema,f as pushBindRequestSchema,h as pushDetachRequestSchema,e as pushInstallationProofSchema,m as pushInstallationStateSchema,c as pushPermissionSchema,d as pushPlatformSchema,p as pushProofPayload,g as pushReadRequestSchema,k as pushRecoveryConfirmSchema,j as pushRecoveryRequestSchema,l as pushRecoveryRequestedSchema,Qe as radiusSchema,Xf as readFunnelValuePath,Bl as redeemRewardRequestSchema,Fl as referralCodeSchema,Hl as referralProgramCollectionSchema,ul as referralProgramInputSchema,wl as referralProgramRecordSchema,zl as referralProgramWriteSchema,ui as remoteFeatureResultSchema,cg as renameFunnelScreenVariable,yf as replaceFirstPageRoot,uk as resolveCouponDisplay,Cj as resolveFunnelBundle,Mj as resolveFunnelCapabilityInputs,Si as resolveFunnelTaskInputs,Yf as resolveFunnelValueBinding,Zf as resolveFunnelValueBindings,ad as resolveProductVariant,Hf as resolveScreenLocale,Q as resolveSdkProtocol,pm as responseMetaSchema,zc as revokeBillingAuthorizationInputSchema,Jl as rewardActivityRedemptionSchema,Kl as rewardActivitySchema,tl as rewardCodeInputSchema,Il as rewardCodeSchema,Ll as rewardCodeWriteSchema,Gl as rewardCollectionSchema,ql as rewardConfigurationSchema,ol as rewardGrantExpirySchema,pl as rewardGrantSchema,sl as rewardInputSchema,rl as rewardKeySchema,xl as rewardOptionSchema,Dl as rewardProductCheckoutSchema,vl as rewardRecordSchema,Al as rewardRedemptionSchema,nl as rewardStatusSchema,ml as rewardTypeSchema,yl as rewardWriteSchema,fb as runExperiment,Cn as sameMembershipBillingCycle,ym as saveSurfaceTemplateSchema,b as scopeSchema,rf as screenActionSchema,Fi as screenAnswersSchema,Ei as screenDataCursorSchema,zf as screenDocumentSchema,Re as screenImageSourceSchema,Ii as screenInputBindingsSchema,qf as screenNodeSchema,Gi as screenParametersSchema,Xh as screenPresentationSchema,xe as screenProductScopes,ye as screenProductSelections,Ji as screenRendererInputSchema,Mf as screenSelections,sf as screenStringsSchema,Jk as sdkConfigurationManifestSchema,K as sdkProtocolRegistry,R as sdkProtocolResponseHeaders,Ld as seatCommandSchema,Kd as seatReadSchema,Md as seatsStateSchema,Uj as selectFunnelCondition,Vh as selectedPaywallProduct,ve as selectedSurfaceValue,Gf as servableLocales,Oc as setBillingCouponsInputSchema,$e as shadowSchema,Ze as shapeSchema,Ue as sizeSchema,Pe as spaceSchema,hf as spacerNodeSchema,ua as stableKeySchema,of as stackInteractionSchema,pf as stackNodeSchema,xb as stickyAssignmentDocumentSchema,Gg as stripeAppendContextSchema,Fg as stripeCouponTermsSchema,Hg as stripePurchaseExecutionSchema,Ug as stripeRefundExecutionSchema,ih as stripeSetupExecutionSchema,Mg as stripeSubscriptionUpdateExecutionSchema,Ng as stripeSubscriptionUpdatePreviewSchema,Og as stripeSubscriptionUpdateResultSchema,dh as stripeTrialExecutionSchema,bf as styleSchema,Dg as subscriptionAttachCommandSchema,Ig as subscriptionAttachQuoteSchema,Zg as subscriptionBatchCommandSchema,$g as subscriptionBatchGroupSchema,_g as subscriptionBatchReadSchema,ah as subscriptionBatchSchema,Kg as subscriptionCarryOptionsSchema,wh as subscriptionConflictPageSchema,rh as subscriptionConflictQuerySchema,th as subscriptionConflictRetryResultSchema,sh as subscriptionConflictRetrySchema,qh as subscriptionConflictSchema,Nc as subscriptionCouponExecutionSchema,mm as subscriptionInvoiceModeSchema,oh as subscriptionListItemSchema,uh as subscriptionListPageSchema,Eg as subscriptionOperationInputSchema,Jg as subscriptionOperationSchema,Tg as subscriptionRefundCommandSchema,Vg as subscriptionRefundPreviewSchema,Wg as subscriptionRefundResultSchema,bh as subscriptionTrialCommandSchema,fh as subscriptionTrialPolicySchema,ch as subscriptionTrialReadSchema,eh as subscriptionTrialResultSchema,Lg as subscriptionUpdateCommandSchema,Rg as subscriptionUpdatePreviewSchema,Sg as subscriptionUpdateResultSchema,kh as subscriptionVerificationInputSchema,lh as subscriptionVerificationSchema,Ke as substituteHtmlVariables,ue as substituteSurfaceVariables,re as surfaceDataSchema,tf as surfaceSchema,xm as surfaceTemplateSchema,qe as surfaceValueSchema,se as surfaceVariableNames,Gb as targetingAttributeSourceSchema,Fb as targetingEntitySchema,Hb as targetingSubjectSchema,Ff as templateChecks,wm as templateCoverImageSchema,cf as textNodeSchema,af as textStyleSchema,Se as themeSchema,ab as toAttributeString,wi as trackEventsRequestSchema,xi as trackEventsResultSchema,Vj as transitionFunnelGraph,Bf as translatableFields,ma as trialPolicySchema,na as trialRecordSchema,te as unknownSurfaceVariables,il as usageAnalyticsPageSchema,hl as usageAnalyticsQuerySchema,ll as usageBatchPageSchema,kl as usageBatchReadSchema,jl as usageBatchSubmitSchema,Xk as usageEntityCommandSchema,Yk as usageEntitySchema,dn as validateFunnelContentPublication,Tj as validateFunnelGraph,Uf as validateFunnelProjections,Ri as validateFunnelTaskData,sk as validateScreenAnswers,O as validateSdkProtocolRegistry,Fa as validitySchema,om as verifiedPrincipalSchema,Nn as visualChangeSchema,Qn as visualExperimentPayloadSchema,Pn as visualExperimentSchema,Mn as visualMutationSchema,On as visualVariationSchema,xf as walkDocument,Af as walkScreen};
|
package/dist/visual.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as pe,b as me,c as he,d as ge,f as be}from"./chunk-X747SY26.js";import"./chunk-AE4CUTUE.js";import"./chunk-EXCPE2XH.js";import"./chunk-RRII2DMC.js";import{h as de,k as fe,m as D}from"./chunk-KQCTDXVD.js";async function ye(e,t,r,n={}){let o=n.message??"Invalid SDK JSON response",a=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||a!==null&&(!/^\d+$/.test(a)||Number(a)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let i=e.body.getReader(),s=[],l=0,u=!1,p=()=>{},d=new Promise((f,y)=>{p=()=>y(Error(o)),r.addEventListener("abort",p,{once:!0}),r.aborted&&p()});try{for(;;){let w=await Promise.race([i.read(),d]);if(w.done){u=!0;break}if(l+=w.value.byteLength,l>t)throw Error(o);s.push(w.value)}let f=new Uint8Array(l),y=0;for(let w of s)f.set(w,y),y+=w.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f))}finally{r.removeEventListener("abort",p),u||i.cancel().catch(()=>{}),i.releaseLock()}}async function ve(e,t){let r=e?.body;if(!r)return;let n=r.getReader(),o=0,a=!1,i,s=new Promise((p,d)=>{i=setTimeout(()=>d(Error("Exposure response timeout")),2e3)}),l=()=>{},u=new Promise((p,d)=>{l=()=>d(t?.reason),t?.addEventListener("abort",l,{once:!0}),t?.aborted&&l()});try{for(;;){let p=await Promise.race([n.read(),s,u]);if(p.done){a=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(i),t?.removeEventListener("abort",l),a||n.cancel().catch(()=>{}),n.releaseLock()}}var we=2*1024*1024,Rt=256*1024;async function Ee(e,t,r,n){let o=()=>{},a=new Promise((i,s)=>{o=()=>s(n.reason),n.addEventListener("abort",o,{once:!0}),n.aborted&&o()});try{let i=e(t,{...r,signal:n});return i.then(s=>{n.aborted&&s.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([i,a])}finally{n.removeEventListener("abort",o)}}async function Ae(e,t,r,n=!1){if(new TextEncoder().encode(r).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,a=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let i=await Ee(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:r,credentials:"omit",keepalive:n,redirect:"error"},o.signal);await ve(i,o.signal)}finally{clearTimeout(a)}}function Me(e){let t,r=!1;return{async read(n,o){if(r)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:i}=a,s=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let l=await Ee(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},i),u=await ye(l,o,i);return i.throwIfAborted(),u}finally{clearTimeout(s),t===a&&(t=void 0)}},destroy(){r=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}function C(e,t=()=>{}){let r=new WeakMap,n=0,o=a=>{let i=r.get(a);if(i!==void 0)return i;let s=[],l=a,u=!0;for(;l;){let p=r.get(l);if(p!==void 0){u=p;break}if(++n>8192||s.length>=256)throw Error("IAM render ancestry budget exceeded");if(s.push(l),t(),l.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(l.getAttribute("style")??"")){u=!1;break}l=l.parentElement}for(let p of s)r.set(p,u);return u};return a=>{let i=0,s=e.querySelectorAll(a);for(let l=0;l<s.length;l++){let u=s[l];if(!u)throw Error("IAM render selection changed");o(u)&&i++,t()}return i}}var ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function J(e){if(!ze(e)||Object.keys(e).some(a=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(a))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(a=>typeof a!="string"||a.length>512||!/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/.test(a))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,o=[...r,...n];if(new Set(t).size!==t.length||o.length!==t.length||new Set(o).size!==o.length||o.some(a=>typeof a!="number"||!Number.isInteger(a)||a<0||a>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function He(e,t){let r=e.split("/").filter(Boolean),n="";for(let o of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(o)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(o)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(o)?n+="/[^/]+":n+="/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Ve(e,t,r,n,o=C(t,n)){if(!He(e.routeTemplate,r))return!1;let a=new Set(e.present),i=!0;for(let s=0;s<e.selectors.length;s++){let l=o(e.selectors[s]);if(a.has(s)&&l>1)throw new Error("IAM render anchor is ambiguous");(a.has(s)?l!==1:l!==0)&&(i=!1),n()}return i}var Y=new WeakMap,Z=new WeakSet;function Q(e){Z.add(e)}function $e(e){let t=new Set,r=new Set,n,o=0,a=!1,i=()=>{t.size||o||(n?.disconnect(),e.removeEventListener("visibilitychange",l),Y.delete(e))};function s(u){if(e.hidden)return;let p=performance.now(),d=new Map,f=new Map,y=()=>{if(performance.now()-p>8)throw Error("IAM page check exceeded its work budget")},w=c=>{y();let h=d.get(c);return h||(h=e.querySelectorAll(c),d.set(c,h)),y(),h},R=C({querySelectorAll:w},y),b={query:w,checkpoint:y,matches(c,h){let m=f.get(h);if(!m){try{m={match:Ve(c,e,location.pathname,y,R)}}catch(g){m={error:g}}f.set(h,m)}if("error"in m)throw m.error;return m.match}},k=[],v=[],M=[];for(let c of u)if(t.has(c))try{k.push({job:c,commit:c.prepare(b)})}catch(h){v.push({job:c,error:h})}try{y()}catch(c){for(let h of[...t])h.fail(c);return}for(let{job:c,error:h}of v)t.has(c)&&c.fail(h);for(let{job:c,commit:h}of k)if(t.has(c))try{y(),h(m=>M.push(m))}catch(m){c.fail(m)}for(let c of M)c()}function l(){a||!t.size||e.hidden||(a=!0,queueMicrotask(()=>{a=!1,s([...t])}))}return{begin(){o++},end(){--o===0&&(r.clear(),s([...t])),i()},add(u){return n||(n=new MutationObserver(p=>{let d=f=>Z.has(f)||!!(f.parentNode&&Z.has(f.parentNode));p.some(f=>!d(f.target)&&!(f.type==="childList"&&[...f.addedNodes,...f.removedNodes].length>0&&[...f.addedNodes,...f.removedNodes].every(d)))&&l()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",l)),t.add(u),o?r.add(u):s([u]),()=>{t.delete(u),r.delete(u),i()}}}}function Se(){let e=Y.get(document);return e||(e=$e(document),Y.set(document,e)),e}function ke(e){return Se().add(e)}function Re(e){let t=Se();t.begin();try{e()}finally{t.end()}}async function We(e,t,r){let n=new URL(e,t.baseURI),o=t.defaultView?.location.origin,a=/^\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(n.pathname)?.[1];if(!a||n.origin!==o||n.search||n.hash||n.username||n.password)throw Error("Invalid IAM release URL");let i=AbortSignal.any([r,AbortSignal.timeout(2e3)]),s=await fetch(n,{credentials:"omit",redirect:"error",cache:"force-cache",signal:i}),l=s.headers.get("content-length");if(!s.ok||!/^application\/json(?:;|$)/i.test(s.headers.get("content-type")??"")||l!==null&&(!/^\d+$/.test(l)||Number(l)>512))throw s.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let u=s.body?.getReader();if(!u)throw Error("IAM release is unavailable");let p=[],d=0,f=()=>{},y=new Promise((M,c)=>{f=()=>c(Error("IAM release timeout")),i.addEventListener("abort",f,{once:!0}),i.aborted&&f()}),w=!1;try{for(;;){let M=await Promise.race([u.read(),y]);if(M.done){w=!0;break}if(d+=M.value.length,d>512)throw Error("IAM release budget");p.push(M.value)}}finally{i.removeEventListener("abort",f),w||u.cancel().catch(()=>{}),u.releaseLock()}let R=new Uint8Array(d),b=0;for(let M of p)R.set(M,b),b+=M.length;let k=new TextDecoder("utf-8",{fatal:!0}).decode(R),v=JSON.parse(k);if(k.trim()!==JSON.stringify(v))throw Error("Noncanonical IAM release descriptor");if(!v||typeof v!="object"||Array.isArray(v)||Object.keys(v).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(v,"format")!=="indiana-app-manifest-release"||Reflect.get(v,"schemaVersion")!==2||Reflect.get(v,"releaseId")!==a||!/^[a-f0-9]{64}$/.test(String(Reflect.get(v,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(v,"manifestDigest")}var xe=new WeakMap;function Ie(e,t=document){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Invalid IAM manifest digest");let r=xe.get(t);r||(r=new Map,xe.set(t,r));let n="data-indiana-release",o=t.documentElement,a=()=>new Set((o.getAttribute(n)??"").split(/\s+/).filter(Boolean)),i=r.get(e);if(!i){let l=a();i={count:0,owned:!l.has(e)},r.set(e,i),l.add(e),o.setAttribute(n,[...l].join(" "))}i.count++;let s=!1;return{attributes:{indianaAppManifestRelease:e},destroy(){if(!s&&(s=!0,i.count--,!i.count&&(r.delete(e),i.owned))){let l=a();l.delete(e),l.size?o.setAttribute(n,[...l].join(" ")):o.removeAttribute(n)}}}}var Fe=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,te={revert:function(){}},H=new Map,re=new Set;function Ke(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function $(e){var t=H.get(e);return t||(t={element:e,attributes:{}},H.set(e,t)),t}function W(e,t,r,n,o){var a=r(e),i={isDirty:!1,originalValue:a,virtualValue:a,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!mt&&!(t==="position"&&i._positionTimeout)){t==="position"&&(i._positionTimeout=setTimeout(function(){i._positionTimeout=null},1e3));var s=r(e);t==="position"&&s.parentNode===i.virtualValue.parentNode&&s.insertBeforeNode===i.virtualValue.insertBeforeNode||s!==i.virtualValue&&(i.originalValue=s,o(i))}}),mutationRunner:o,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?i.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):i.observer.observe(e,Ke(t)),i}function F(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Te()):e!==r&&(t.isDirty=!0,Te())}function _e(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),F(ut(t),e)}function Ye(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),F(Array.from(t).filter(Boolean).join(" "),e)}function Ze(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),F(t,e)}function Qe(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var o=r?document.querySelector(r):null;return r&&!o?null:{parentNode:n,insertBeforeNode:o}}function Xe(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),o=Qe(n);t=o||t}),F(t,e)}var et=function(t){return t.innerHTML},tt=function(t,r){return t.innerHTML=r};function Ne(e){var t=$(e);return t.html||(t.html=W(e,"html",et,tt,_e)),t.html}var rt=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},nt=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Pe(e){var t=$(e);return t.position||(t.position=W(e,"position",rt,nt,Xe)),t.position}var ot=function(t,r){return r?t.className=r:t.removeAttribute("class")},it=function(t){return t.className};function Oe(e){var t=$(e);return t.classes||(t.classes=W(e,"class",it,ot,Ye)),t.classes}var st=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},at=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function De(e,t){var r=$(e);return r.attributes[t]||(r.attributes[t]=W(e,t,st(t),at(t),Ze)),r.attributes[t]}function lt(e,t){var r=H.get(e);if(r)if(t==="html"){var n,o;(n=r.html)==null||(o=n.observer)==null||o.disconnect(),delete r.html}else if(t==="class"){var a,i;(a=r.classes)==null||(i=a.observer)==null||i.disconnect(),delete r.classes}else if(t==="position"){var s,l;(s=r.position)==null||(l=s.observer)==null||l.disconnect(),delete r.position}else{var u,p,d;(u=r.attributes)==null||(p=u[t])==null||(d=p.observer)==null||d.disconnect(),delete r.attributes[t]}}var U;function ut(e){return U||(U=document.createElement("div")),U.innerHTML=e,U.innerHTML}function G(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||lt(e,t),r.setValue(e,n)}}function ct(e,t){e.html&&G(t,"html",e.html),e.classes&&G(t,"class",e.classes),e.position&&G(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){G(t,r,e.attributes[r])})}function Te(){H.forEach(ct)}function dt(e,t){var r=null;e.kind==="html"?r=Ne(t):e.kind==="class"?r=Oe(t):e.kind==="attribute"?r=De(t,e.attribute):e.kind==="position"&&(r=Pe(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function ft(e,t){var r=null;if(e.kind==="html"?r=Ne(t):e.kind==="class"?r=Oe(t):e.kind==="attribute"?r=De(t,e.attribute):e.kind==="position"&&(r=Pe(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function qe(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),dt(e,n))})}}function pt(e){e.elements.forEach(function(t){return ft(e,t)}),e.elements.clear(),re.delete(e)}function Le(){re.forEach(qe)}var mt=!1;var X;function ht(){typeof document>"u"||(X||(X=new MutationObserver(function(){Le()})),Le(),X.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ht();function K(e){return typeof document>"u"?te:(re.add(e),qe(e),{revert:function(){pt(e)}})}function ee(e,t){return K({kind:"html",elements:new Set,mutate:t,selector:e})}function Be(e,t){return K({kind:"position",elements:new Set,mutate:t,selector:e})}function q(e,t){return K({kind:"class",elements:new Set,mutate:t,selector:e})}function z(e,t,r){return Fe.test(t)?t==="class"||t==="className"?q(e,function(n){var o=r(Array.from(n).join(" "));n.clear(),o&&o.split(/\s+/g).filter(Boolean).forEach(function(a){return n.add(a)})}):K({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):te}function gt(e){var t=e.selector,r=e.action,n=e.value,o=e.attribute,a=e.parentSelector,i=e.insertBeforeSelector;if(o==="html"){if(r==="append")return ee(t,function(s){return s+(n??"")});if(r==="set")return ee(t,function(){return n??""})}else if(o==="class"){if(r==="append")return q(t,function(s){n&&s.add(n)});if(r==="remove")return q(t,function(s){n&&s.delete(n)});if(r==="set")return q(t,function(s){s.clear(),n&&s.add(n)})}else if(o==="position"){if(r==="set"&&a)return Be(t,function(){return{insertBeforeSelector:i,parentSelector:a}})}else{if(r==="append")return z(t,o,function(s){return s!==null?s+(n??""):n??""});if(r==="set")return z(t,o,function(){return n??""});if(r==="remove")return z(t,o,function(){return null})}return te}var bt={html:ee,classes:q,attribute:z,position:Be,declarative:gt},ne=bt;import yt from"dompurify";var oe,je;function vt(e){return(!oe||je!==window)&&(oe=yt(window),je=window),oe.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function Ce(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=vt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Je(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return wt(e,t);let r=e.domMutations.map(Ce),n=[],o=!1,a=!1,i,s=()=>{if(!o){o=!0,i?.disconnect();for(let u of n.reverse())u()}},l=()=>{o||a||(!r.length||e.css||t.allowJs&&e.js||r.some(u=>document.querySelector(u.selector)))&&(a=!0,t.onApplied?.())};try{if(e.css){let d=document.createElement("style");t.nonce&&(d.nonce=t.nonce),d.textContent=e.css,document.head.append(d),n.push(()=>d.remove())}for(let d of r){let f=ne.declarative(d);n.push(()=>f.revert())}if(t.allowJs&&e.js){let d=document.createElement("script");t.nonce&&(d.nonce=t.nonce),d.textContent=e.js,document.head.append(d),n.push(()=>d.remove())}let u=performance.now(),p=new WeakMap;i=new MutationObserver(d=>{if(!o){performance.now()-u>1e3&&(u=performance.now(),p=new WeakMap);for(let f of d){let y=(p.get(f.target)??0)+1;if(p.set(f.target,y),y>40){s(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}l()}}),i.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),l()}catch(u){throw s(),u}return{revert:s,get applied(){return a}}}function wt(e,t){let r=t?.boundVariations??[e],n=new Set,o=new Set,a=[],i=new Map,s=r.flatMap(c=>c.renderGuard?[J(c.renderGuard)]:[]),l=s[0];if(s.some(c=>JSON.stringify(c)!==JSON.stringify(l)))throw new Error("IAM variations use different render states");if(e.js||r.some(c=>c.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((c,h)=>c+h.css.length,0)>262144)throw Error("IAM target budget");let u=(c,h)=>{for(let g of c.domMutations){if(g.action!=="set"||g.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(g.selector),o.add(g.selector)}if(!c.css)return;let m=document.createElement("style");Q(m),m.media="not all",t?.nonce&&(m.nonce=t.nonce),m.textContent=c.css;try{if(document.head.append(m),!m.sheet)throw Error("IAM CSS is blocked");for(let g of m.sheet.cssRules){if(!("selectorText"in g)||typeof g.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(g.selectorText),h&&a.push({selector:g.selectorText,css:g.cssText})}}finally{m.remove()}};for(let c of r)u(c,!1);if(u(e,!0),n.size>200)throw Error("IAM target budget");let p=e.domMutations.map(Ce),d=!1,f=!1,y=!1,w={},R=l?JSON.stringify(l):"",b,k="",v=()=>{if(!d){d=!0,w.unsubscribe?.();for(let c of i.values())c.revert();i.clear(),b?.remove(),b=void 0,f=!1}},M=()=>{for(let c of i.values())c.revert();i.clear(),b?.remove(),b=void 0,k="",f=!1};return w.unsubscribe=ke({fail(c){v(),t?.onError?.(c)},prepare(c){if(l&&!c.matches(l,R))return()=>{d||M()};let h=new Map;for(let m of n){let g=c.query(m);if(g.length>1)throw Error("IAM target is ambiguous in this rendered state");if(g.length){if(o.has(m)&&g[0].children.length)throw Error("IAM text target is no longer a leaf");h.set(m,g[0])}c.checkpoint()}return m=>{if(d)return;for(let[E,I]of i)h.get(E)!==I.element&&(I.revert(),i.delete(E));for(let E of new Set(p.map(I=>I.selector))){let I=h.get(E);if(!I||i.has(E))continue;let _=p.filter(T=>T.selector===E).map(T=>ne.declarative(T));i.set(E,{element:I,revert:()=>_.forEach(T=>T.revert())})}let g=a.filter(E=>h.has(E.selector)).map(E=>E.css).join(`
|
|
2
|
-
`);g
|
|
1
|
+
import{a as me,b as he,c as ge,d as ye,e as ve,f as be,g as we,i as Ee}from"./chunk-RZBZ6LCT.js";import"./chunk-DSPLGTQI.js";import"./chunk-OBYJWIRB.js";import"./chunk-EXCPE2XH.js";import"./chunk-RRII2DMC.js";import{h as fe,k as pe,m as j}from"./chunk-KQCTDXVD.js";function H(e,t=()=>{}){let r=new WeakMap,n=0,i=l=>{let o=r.get(l);if(o!==void 0)return o;let s=[],a=l,u=!0;for(;a;){let m=r.get(a);if(m!==void 0){u=m;break}if(++n>8192||s.length>=256)throw Error("IAM render ancestry budget exceeded");if(s.push(a),t(),a.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(a.getAttribute("style")??"")){u=!1;break}a=a.parentElement}for(let m of s)r.set(m,u);return u};return l=>{let o=0,s=e.querySelectorAll(l);for(let a=0;a<s.length;a++){let u=s[a];if(!u)throw Error("IAM render selection changed");i(u)&&o++,t()}return o}}var Je=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function $(e){if(!Je(e)||Object.keys(e).some(l=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(l))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(l=>typeof l!="string"||l.length>512||!/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/.test(l))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,i=[...r,...n];if(new Set(t).size!==t.length||i.length!==t.length||new Set(i).size!==i.length||i.some(l=>typeof l!="number"||!Number.isInteger(l)||l<0||l>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function Ge(e,t){let r=e.split("/").filter(Boolean),n="";for(let i of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(i)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(i)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(i)?n+="/[^/]+":n+="/"+i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Me(e,t,r,n,i=H(t,n)){if(!Ge(e.routeTemplate,r))return!1;let l=new Set(e.present),o=!0;for(let s=0;s<e.selectors.length;s++){let a=i(e.selectors[s]);if(l.has(s)&&a>1)throw new Error("IAM render anchor is ambiguous");(l.has(s)?a!==1:a!==0)&&(o=!1),n()}return o}var ee=new WeakMap,te=new WeakSet;function re(e){te.add(e)}function ze(e){let t=new Set,r=new Set,n,i=0,l=!1,o=()=>{t.size||i||(n?.disconnect(),e.removeEventListener("visibilitychange",a),ee.delete(e))};function s(u){if(e.hidden)return;let m=performance.now(),c=new Map,f=new Map,M=()=>{if(performance.now()-m>8)throw Error("IAM page check exceeded its work budget")},x=d=>{M();let g=c.get(d);return g||(g=e.querySelectorAll(d),c.set(d,g)),M(),g},T=H({querySelectorAll:x},M),A={query:x,checkpoint:M,matches(d,g){let w=f.get(g);if(!w){try{w={match:Me(d,e,location.pathname,M,T)}}catch(B){w={error:B}}f.set(g,w)}if("error"in w)throw w.error;return w.match}},N=[],b=[],S=[];for(let d of u)if(t.has(d))try{N.push({job:d,commit:d.prepare(A)})}catch(g){b.push({job:d,error:g})}try{M()}catch(d){for(let g of[...t])g.fail(d);return}for(let{job:d,error:g}of b)t.has(d)&&d.fail(g);for(let{job:d,commit:g}of N)if(t.has(d))try{M(),g(w=>S.push(w))}catch(w){d.fail(w)}for(let d of S)d()}function a(){l||!t.size||e.hidden||(l=!0,queueMicrotask(()=>{l=!1,s([...t])}))}return{begin(){i++},end(){--i===0&&(r.clear(),s([...t])),o()},add(u){return n||(n=new MutationObserver(m=>{let c=f=>te.has(f)||!!(f.parentNode&&te.has(f.parentNode));m.some(f=>!c(f.target)&&!(f.type==="childList"&&[...f.addedNodes,...f.removedNodes].length>0&&[...f.addedNodes,...f.removedNodes].every(c)))&&a()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",a)),t.add(u),i?r.add(u):s([u]),()=>{t.delete(u),r.delete(u),o()}}}}function Ve(){let e=ee.get(document);return e||(e=ze(document),ee.set(document,e)),e}function Ae(e){return Ve().add(e)}function Se(e){let t=Ve();t.begin();try{e()}finally{t.end()}}async function Ue(e,t,r){let n=new URL(e,t.baseURI),i=t.defaultView?.location.origin,l=/^\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(n.pathname)?.[1];if(!l||n.origin!==i||n.search||n.hash||n.username||n.password)throw Error("Invalid IAM release URL");let o=AbortSignal.any([r,AbortSignal.timeout(2e3)]),s=await fetch(n,{credentials:"omit",redirect:"error",cache:"force-cache",signal:o}),a=s.headers.get("content-length");if(!s.ok||!/^application\/json(?:;|$)/i.test(s.headers.get("content-type")??"")||a!==null&&(!/^\d+$/.test(a)||Number(a)>512))throw s.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let u=s.body?.getReader();if(!u)throw Error("IAM release is unavailable");let m=[],c=0,f=()=>{},M=new Promise((S,d)=>{f=()=>d(Error("IAM release timeout")),o.addEventListener("abort",f,{once:!0}),o.aborted&&f()}),x=!1;try{for(;;){let S=await Promise.race([u.read(),M]);if(S.done){x=!0;break}if(c+=S.value.length,c>512)throw Error("IAM release budget");m.push(S.value)}}finally{o.removeEventListener("abort",f),x||u.cancel().catch(()=>{}),u.releaseLock()}let T=new Uint8Array(c),A=0;for(let S of m)T.set(S,A),A+=S.length;let N=new TextDecoder("utf-8",{fatal:!0}).decode(T),b=JSON.parse(N);if(N.trim()!==JSON.stringify(b))throw Error("Noncanonical IAM release descriptor");if(!b||typeof b!="object"||Array.isArray(b)||Object.keys(b).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(b,"format")!=="indiana-app-manifest-release"||Reflect.get(b,"schemaVersion")!==2||Reflect.get(b,"releaseId")!==l||!/^[a-f0-9]{64}$/.test(String(Reflect.get(b,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(b,"manifestDigest")}var ke=new WeakMap;function Ie(e,t=document){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Invalid IAM manifest digest");let r=ke.get(t);r||(r=new Map,ke.set(t,r));let n="data-indiana-release",i=t.documentElement,l=()=>new Set((i.getAttribute(n)??"").split(/\s+/).filter(Boolean)),o=r.get(e);if(!o){let a=l();o={count:0,owned:!a.has(e)},r.set(e,o),a.add(e),i.setAttribute(n,[...a].join(" "))}o.count++;let s=!1;return{attributes:{indianaAppManifestRelease:e},destroy(){if(!s&&(s=!0,o.count--,!o.count&&(r.delete(e),o.owned))){let a=l();a.delete(e),a.size?i.setAttribute(n,[...a].join(" ")):i.removeAttribute(n)}}}}var He=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,oe={revert:function(){}},Y=new Map,se=new Set;function $e(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function Z(e){var t=Y.get(e);return t||(t={element:e,attributes:{}},Y.set(e,t)),t}function _(e,t,r,n,i){var l=r(e),o={isDirty:!1,originalValue:l,virtualValue:l,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!dt&&!(t==="position"&&o._positionTimeout)){t==="position"&&(o._positionTimeout=setTimeout(function(){o._positionTimeout=null},1e3));var s=r(e);t==="position"&&s.parentNode===o.virtualValue.parentNode&&s.insertBeforeNode===o.virtualValue.insertBeforeNode||s!==o.virtualValue&&(o.originalValue=s,i(o))}}),mutationRunner:i,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?o.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):o.observer.observe(e,$e(t)),o}function Q(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Re()):e!==r&&(t.isDirty=!0,Re())}function We(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),Q(st(t),e)}function Fe(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),Q(Array.from(t).filter(Boolean).join(" "),e)}function Ke(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),Q(t,e)}function Ye(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var i=r?document.querySelector(r):null;return r&&!i?null:{parentNode:n,insertBeforeNode:i}}function Ze(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),i=Ye(n);t=i||t}),Q(t,e)}var _e=function(t){return t.innerHTML},Qe=function(t,r){return t.innerHTML=r};function Te(e){var t=Z(e);return t.html||(t.html=_(e,"html",_e,Qe,We)),t.html}var Xe=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},et=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Ne(e){var t=Z(e);return t.position||(t.position=_(e,"position",Xe,et,Ze)),t.position}var tt=function(t,r){return r?t.className=r:t.removeAttribute("class")},rt=function(t){return t.className};function Le(e){var t=Z(e);return t.classes||(t.classes=_(e,"class",rt,tt,Fe)),t.classes}var nt=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},it=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function Oe(e,t){var r=Z(e);return r.attributes[t]||(r.attributes[t]=_(e,t,nt(t),it(t),Ke)),r.attributes[t]}function ot(e,t){var r=Y.get(e);if(r)if(t==="html"){var n,i;(n=r.html)==null||(i=n.observer)==null||i.disconnect(),delete r.html}else if(t==="class"){var l,o;(l=r.classes)==null||(o=l.observer)==null||o.disconnect(),delete r.classes}else if(t==="position"){var s,a;(s=r.position)==null||(a=s.observer)==null||a.disconnect(),delete r.position}else{var u,m,c;(u=r.attributes)==null||(m=u[t])==null||(c=m.observer)==null||c.disconnect(),delete r.attributes[t]}}var W;function st(e){return W||(W=document.createElement("div")),W.innerHTML=e,W.innerHTML}function F(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||ot(e,t),r.setValue(e,n)}}function at(e,t){e.html&&F(t,"html",e.html),e.classes&&F(t,"class",e.classes),e.position&&F(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){F(t,r,e.attributes[r])})}function Re(){Y.forEach(at)}function lt(e,t){var r=null;e.kind==="html"?r=Te(t):e.kind==="class"?r=Le(t):e.kind==="attribute"?r=Oe(t,e.attribute):e.kind==="position"&&(r=Ne(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function ut(e,t){var r=null;if(e.kind==="html"?r=Te(t):e.kind==="class"?r=Le(t):e.kind==="attribute"?r=Oe(t,e.attribute):e.kind==="position"&&(r=Ne(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function De(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),lt(e,n))})}}function ct(e){e.elements.forEach(function(t){return ut(e,t)}),e.elements.clear(),se.delete(e)}function xe(){se.forEach(De)}var dt=!1;var ne;function ft(){typeof document>"u"||(ne||(ne=new MutationObserver(function(){xe()})),xe(),ne.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ft();function X(e){return typeof document>"u"?oe:(se.add(e),De(e),{revert:function(){ct(e)}})}function ie(e,t){return X({kind:"html",elements:new Set,mutate:t,selector:e})}function Be(e,t){return X({kind:"position",elements:new Set,mutate:t,selector:e})}function C(e,t){return X({kind:"class",elements:new Set,mutate:t,selector:e})}function K(e,t,r){return He.test(t)?t==="class"||t==="className"?C(e,function(n){var i=r(Array.from(n).join(" "));n.clear(),i&&i.split(/\s+/g).filter(Boolean).forEach(function(l){return n.add(l)})}):X({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):oe}function pt(e){var t=e.selector,r=e.action,n=e.value,i=e.attribute,l=e.parentSelector,o=e.insertBeforeSelector;if(i==="html"){if(r==="append")return ie(t,function(s){return s+(n??"")});if(r==="set")return ie(t,function(){return n??""})}else if(i==="class"){if(r==="append")return C(t,function(s){n&&s.add(n)});if(r==="remove")return C(t,function(s){n&&s.delete(n)});if(r==="set")return C(t,function(s){s.clear(),n&&s.add(n)})}else if(i==="position"){if(r==="set"&&l)return Be(t,function(){return{insertBeforeSelector:o,parentSelector:l}})}else{if(r==="append")return K(t,i,function(s){return s!==null?s+(n??""):n??""});if(r==="set")return K(t,i,function(){return n??""});if(r==="remove")return K(t,i,function(){return null})}return oe}var mt={html:ie,classes:C,attribute:K,position:Be,declarative:pt},ae=mt;import ht from"dompurify";var le,qe;function gt(e){return(!le||qe!==window)&&(le=ht(window),qe=window),le.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function Pe(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=gt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function je(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return yt(e,t);let r=e.domMutations.map(Pe),n=[],i=!1,l=!1,o,s=()=>{if(!i){i=!0,o?.disconnect();for(let u of n.reverse())u()}},a=()=>{i||l||(!r.length||e.css||t.allowJs&&e.js||r.some(u=>document.querySelector(u.selector)))&&(l=!0,t.onApplied?.())};try{if(e.css){let c=document.createElement("style");t.nonce&&(c.nonce=t.nonce),c.textContent=e.css,document.head.append(c),n.push(()=>c.remove())}for(let c of r){let f=ae.declarative(c);n.push(()=>f.revert())}if(t.allowJs&&e.js){let c=document.createElement("script");t.nonce&&(c.nonce=t.nonce),c.textContent=e.js,document.head.append(c),n.push(()=>c.remove())}let u=performance.now(),m=new WeakMap;o=new MutationObserver(c=>{if(!i){performance.now()-u>1e3&&(u=performance.now(),m=new WeakMap);for(let f of c){let M=(m.get(f.target)??0)+1;if(m.set(f.target,M),M>40){s(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}a()}}),o.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),a()}catch(u){throw s(),u}return{revert:s,get applied(){return l}}}function yt(e,t){let r=t?.boundVariations??[e],n=new Set,i=new Set,l=[],o=new Map,s=r.flatMap(p=>p.renderGuard?[$(p.renderGuard)]:[]),a=s[0];if(s.some(p=>JSON.stringify(p)!==JSON.stringify(a)))throw new Error("IAM variations use different render states");if(e.js||r.some(p=>p.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((p,V)=>p+V.css.length,0)>262144)throw Error("IAM target budget");let u=(p,V)=>{for(let h of p.domMutations){if(h.action!=="set"||h.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(h.selector),i.add(h.selector)}if(!p.css)return;let y=document.createElement("style");re(y),y.media="not all",t?.nonce&&(y.nonce=t.nonce),y.textContent=p.css;try{if(document.head.append(y),!y.sheet)throw Error("IAM CSS is blocked");for(let h of y.sheet.cssRules){if(!("selectorText"in h)||typeof h.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(h.selectorText),V&&l.push({selector:h.selectorText,css:h.cssText})}}finally{y.remove()}};for(let p of r)u(p,!1);if(u(e,!0),n.size>200)throw Error("IAM target budget");let m=e.domMutations.map(Pe),c=!1,f=!1,M=!1,x=!1,T="",A=0,N=(p,V)=>{let y=`${p}:${V}`;if(!(!t?.onTargetStatus||y===T||A>=32)){T=y,A++;try{t.onTargetStatus({status:p,total:n.size,matched:V})}catch{}}},b={},S=a?JSON.stringify(a):"",d,g="",w=()=>{if(!c){c=!0,b.unsubscribe?.();for(let p of o.values())p.revert();o.clear(),d?.remove(),d=void 0,f=!1}},B=()=>{for(let p of o.values())p.revert();o.clear(),d?.remove(),d=void 0,g="",f=!1};return b.unsubscribe=Ae({fail(p){w(),t?.onError?.(p)},prepare(p){if(a&&!p.matches(a,S))return y=>{c||(B(),x=!1,y(()=>{c||N("inactive",null)}))};let V=new Map;for(let y of n){let h=p.query(y);if(h.length>1)throw Error("IAM target is ambiguous in this rendered state");if(h.length){if(i.has(y)&&h[0].children.length)throw Error("IAM text target is no longer a leaf");V.set(y,h[0])}p.checkpoint()}return y=>{if(c)return;for(let[I,L]of o)V.get(I)!==L.element&&(L.revert(),o.delete(I));for(let I of new Set(m.map(L=>L.selector))){let L=V.get(I);if(!L||o.has(I))continue;let z=m.filter(v=>v.selector===I).map(v=>ae.declarative(v));o.set(I,{element:L,revert:()=>z.forEach(v=>v.revert())})}let h=l.filter(I=>V.has(I.selector)).map(I=>I.css).join(`
|
|
2
|
+
`);h!==g&&(g=h,h?(d||(d=document.createElement("style"),re(d),t?.nonce&&(d.nonce=t.nonce),document.head.append(d)),d.textContent=h):(d?.remove(),d=void 0)),f=n.size===0||V.size>0;let G=V.size===n.size?"matched":V.size>0?"partial":x?"missing":"waiting";V.size&&(x=!0),y(()=>{c||N(G,V.size)}),f&&!M&&(M=!0,y(()=>{c||t?.onApplied?.()}))}}}),c&&b.unsubscribe(),{revert:w,get applied(){return f}}}var J=e=>!!e&&typeof e=="object"&&!Array.isArray(e),P=(e,t)=>typeof e=="string"&&e.length<=t,vt=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function bt(e){if(!J(e)||!P(e.css??"",1e5)||!P(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let t=e.domMutations??[];for(let r of t)if(!J(r)||!P(r.selector,2048)||!r.selector||!vt(r.attribute)||!["set","append","remove"].includes(String(r.action))||r.value!==void 0&&!P(r.value,5e4)||r.parentSelector!==void 0&&!P(r.parentSelector,2048)||r.insertBeforeSelector!==void 0&&!P(r.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:t,...e.renderGuard===void 0?{}:{renderGuard:$(e.renderGuard)}}}function Ce(e){if(!J(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!J(e.savedGroups))throw new Error("Invalid visual experiment payload");let t=e.experiments.map(r=>{if(!J(r)||!["key","changeId"].every(n=>typeof r[n]=="string"&&r[n])||!/^[a-f0-9]{64}$/.test(String(r.changeId))||["namespace","status","groups","url"].some(n=>Object.hasOwn(r,n))||r.hashVersion!==void 0&&r.hashVersion!==2||!Array.isArray(r.variations)||r.variations.length<2||r.variations.length>20||r.urlPatterns!==void 0&&!Array.isArray(r.urlPatterns))throw new Error("Invalid visual experiment");return{...r,variations:r.variations.map(bt)}});return{...e,experiments:t}}function Ht(e){let t=ge(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=we(r),i=`${t}/api/v1/visual-experiments/${e.environmentId}`,l=e.appManifestRelease?`${i}?iam=${e.appManifestRelease}`:i,o=me(e.deviceIdCookie??"indiana_did"),s=he(),a=null,u=!1,m=!1,c="",f={...e.attributes??{}},M,x,T=0,A=new Map,N=new Map,b=new Set,S=[],d,g,w;function B(){clearTimeout(g),w?.remove(),w=void 0}function p(v=!1){clearTimeout(d),d=void 0;let k=S.splice(0,20);return k.length?be(r,`${i}/events`,JSON.stringify({events:k}),v).catch(O=>e.log?.("Visual exposure not sent",{error:O})):Promise.resolve()}function V(v,k){let O=j(v,k);b.has(O)||e.trackExposures===!1||a?.trackExposures===!1||u||(b.add(O),S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:o,...s?{sessionId:s}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:v.key,variationKey:k.key}),S.length>=20?p():d??=setTimeout(()=>{p()},1e3))}function y(v){if(!a||u)return;let k=new Set,O={onExperimentViewed:(E,D)=>{k.add(j(E,D))},url:location.href,attributes:{...Ee(o,location),...f,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:fe(a.savedGroups),log:e.log},U=new Set;for(let E of a.experiments){let D=E;try{let R=pe(D,O);if(N.set(E.changeId,R),!R.inExperiment)continue;U.add(E.changeId);let ue=JSON.stringify([R.key,R.value]),ce=A.get(E.changeId);if(ce?.signature===ue){k.has(j(D,R))&&v.push(()=>{ce.applied()&&V(D,R)});continue}A.get(E.changeId)?.revert(),A.delete(E.changeId);let de=je(R.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(E.condition?.$and)&&E.condition.$and.some(q=>q!==null&&typeof q=="object"&&!Array.isArray(q)&&q.indianaAppManifestRelease===e.appManifestRelease),boundVariations:E.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{k.has(j(D,R))&&V(D,R)},onError:q=>e.log?.("Visual experiment stopped",{experiment:E.key,changeId:E.changeId,variation:R.key,error:String(q)}),onTargetStatus:e.log?q=>e.log?.("Visual target status changed",{experiment:E.key,changeId:E.changeId,variation:R.key,...q}):void 0});A.set(E.changeId,{signature:ue,revert:de.revert,applied:()=>de.applied})}catch(R){e.log?.("Skipping visual experiment",{experiment:E.key,error:String(R)})}}for(let[E,D]of A)U.has(E)||(D.revert(),A.delete(E));B()}let h=()=>{let v=[];Se(()=>y(v));for(let k of v)k()};async function G(){let v=++T,k;try{k=await n.read(l,ve)}catch(U){if(u||v!==T)return!1;throw U}let O=Ce(k);if(O.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return u||v!==T?!1:(a=O,!0)}let I=()=>{c!==location.href&&(c=location.href,h())},L=()=>{p(!0)},z=()=>{M||u||(M=ye(I),addEventListener("pagehide",L),c=location.href)};return{async start(){if(!(m||u)){m=!0,e.appManifestRelease&&(x=Ie(e.appManifestRelease)),e.antiFlicker&&(w=document.createElement("style"),e.nonce&&(w.nonce=e.nonce),w.textContent="body { visibility: hidden !important }",document.head.append(w),g=setTimeout(B,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await G()||u)return;z(),h()}finally{B()}}},async refresh(){u||await G()&&(m&&z(),h())},setAttributes(v){f={...v},h()},flush:()=>p(),getResults(){return new Map(N)},get generation(){return a?.generation??null},destroy(){u=!0,T++,n.destroy(),M?.(),x?.destroy(),removeEventListener("pagehide",L),B();for(let v of A.values())v.revert();A.clear(),p(!0),a=null,N.clear(),b.clear(),f={}}}}export{Ht as createVisualExperiments,Ue as loadAppManifestRelease};
|
package/package.json
CHANGED
package/dist/chunk-3BQFJANQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as ue}from"./chunk-RRII2DMC.js";import{z as A}from"zod";var te=A.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Sr=A.enum([...te.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),xr=A.enum([...te.options,"stale_revision"]),ot=A.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),at=A.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Ee={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function _r(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}var Ie={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function st(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Ie,e)){let i=Ie[e];return{retryable:i==="retry_same_request",recovery:i}}let n=te.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Ee[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Ir(e,t){let n=te.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Ee[n.data].status===t;let i={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(i,e)&&(i[e]?.includes(t)??!1)}function ct(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let a=Number(n);return Number.isSafeInteger(a)?a:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let i=Date.parse(n);return Number.isFinite(i)?Math.max(0,Math.ceil((i-t)/1e3)):void 0}var Ae=A.object({retryable:A.boolean(),recovery:ot,reason:at.optional(),retryAfterSeconds:A.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),lt=A.object({requestId:A.uuid().optional(),error:A.object({code:A.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:A.string(),...Ae.partial().shape})}),Er=A.object({error:lt.shape.error.extend({requestId:A.uuid().optional()})}),Ar=A.object({error:A.string(),code:A.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:A.uuid(),...Ae.shape});function Nr(e,t,n={}){let i=st(e,t),a=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??i.recovery,c=i.retryable&&n.retryable!==!1&&a!=="recover_operation",l=c?ct(n.retryAfter??null):void 0;return{...i,retryable:c,recovery:a,...l===void 0?{}:{retryAfterSeconds:l},...n.reason?{reason:n.reason}:{}}}import{z as ut}from"zod";var pt=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],O=ut.enum(pt);function pe(e){let t=O.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function kr(e,t){let n=pe(t),i=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!i?.[1]||(i[2]?.length??0)>n)throw new Error("Amount has invalid currency precision");let a=BigInt(i[1])*BigInt(10**n)+BigInt((i[2]??"").padEnd(n,"0")||"0");if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(a)}function Cr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=pe(t),i=String(e).padStart(n+1,"0");return n?`${i.slice(0,-n)}.${i.slice(-n)}`:i}function Lr(e,t,n="en",i={}){let a=O.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as _}from"zod";var re=_.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),E=_.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),mt=_.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),me=E.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ne=_.string().min(1).max(64),V=_.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Re=_.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),L=_.record(Ne,_.union([_.string().max(120),_.number().finite(),_.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Oe=_.record(Ne,_.union([_.string().max(120),_.number().finite(),_.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),q=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,i=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let a=BigInt(n)*BigInt("1000000")+BigInt(i.padEnd(6,"0"));return t?-a:a},ke=_.array(_.object({upTo:me.nullable(),cost:E}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let i=e[n-1]?.upTo;return t.upTo!==null&&(n===0||i!=null&&q(t.upTo)>q(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),dt=_.object({key:Re,match:Oe,priority:_.number().int().default(0),cost:E.optional(),tiers:ke.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),ft=_.object({key:Re,match:Oe,factor:me.optional(),add:mt.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),gt=_.object({units:me.default("1"),cost:E,tiers:ke.optional(),dimensions:_.array(dt).max(12).optional(),multipliers:_.array(ft).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],i=e.multipliers??[];(new Set(n.map(l=>l.key)).size!==n.length||new Set(i.map(l=>l.key)).size!==i.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[l,d]of n.entries())for(let g of n.slice(l+1))Object.keys(d.match).length===Object.keys(g.match).length&&d.priority===g.priority&&!Object.keys(d.match).some(s=>g.match[s]!==void 0&&g.match[s]!==d.match[s])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let a=[e.cost,...(e.tiers??[]).map(l=>l.cost),...n.flatMap(l=>[...l.cost===void 0?[]:[l.cost],...(l.tiers??[]).map(d=>d.cost)])],c=q(e.units);for(let l of a)for(let d=0;d<1<<i.length;d++){let g=i.filter((v,R)=>d&1<<R);if(g.some((v,R)=>g.slice(R+1).some(_e=>Object.keys(v.match).some(le=>_e.match[le]!==void 0&&_e.match[le]!==v.match[le]))))continue;let s=q(l),p=BigInt("1"),b=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=q(R.factor??"1"),p*=BigInt("1000000"),b+=q(R.add??"0"));let h=(s+b*p)*BigInt("1000000"),w=p*c;(h<BigInt("0")||h%w!==BigInt("0")||h/w>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Dr=gt.safeExtend({featureKey:V});import{z as bt}from"zod";var Le=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,M=bt.string().max(16).regex(Le,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function de(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:i,region:a}=new Intl.Locale(t),c=[n,i,a].filter(Boolean).join("-");return Le.test(c)?c:null}catch{return null}}var yt=new Set(["TW","HK","MO"]);function Ce(e){let[t,n,i]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let a=n?.length===4?n:void 0,c=n?.length===4?i:n;return a?`zh-${a}`:c&&yt.has(c)?"zh-Hant":"zh-Hans"}function Te(e,t,n){let i=t.map(a=>({code:M.parse(a),normalized:a}));for(let a of e){let c=de(a);if(!c)continue;let l=i.find(p=>p.normalized===c);if(l)return l.code;let d=Ce(c),g=i.filter(p=>Ce(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return n}var ht=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function wr(e){return ht.find(t=>t.code===e)?.label??e}import{z as u}from"zod";var $=E.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),H=u.string().min(1).max(120),ne=u.enum(["cap","overflow"]),k=(e,t)=>{let[n,i=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(i.padEnd(t,"0"))},K=e=>{try{return e()}catch{return!1}},$r=u.discriminatedUnion("operation",[u.object({operation:u.literal("quote"),overageBehavior:ne.optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L}).strict(),u.object({operation:u.literal("consume"),overageBehavior:ne.optional(),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:E,properties:L,idempotencyKey:H}).strict(),u.object({operation:u.literal("reserve"),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L,idempotencyKey:H,expiresInSeconds:u.number().int().min(1).max(86400)}).strict(),u.object({operation:u.literal("confirm"),operationId:u.uuid(),quantity:$,properties:L.optional(),idempotencyKey:H}).strict(),u.object({operation:u.literal("refund"),operationId:u.uuid(),quantity:$,idempotencyKey:H}).strict(),u.object({operation:u.literal("release"),operationId:u.uuid(),idempotencyKey:H}).strict()]),St=u.object({internal_credit_feature_id:u.uuid().nullable(),internal_metered_feature_id:u.uuid(),dimension:u.string().min(1).max(64),counterKey:u.string().min(1).max(240),cycleStart:u.iso.datetime({offset:!0}),unitCost:E,units:$,amount:re,tier:u.number().int().min(1).max(12).nullable()}).strict(),Q=u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function je(e,t){let n=e.reduce((i,a)=>i+k(a.units,12),0n)-k(t,12);return e.some(i=>i.funding==="balance")?n>=-100n&&n<=100n:n===0n}var De=u.discriminatedUnion("funding",[u.strictObject({funding:u.literal("balance"),sourceId:u.uuid(),rolloverId:u.uuid().nullable(),units:Q.refine(e=>/[1-9]/.test(e)),amount:re}),u.strictObject({funding:u.literal("unbilled"),units:Q.refine(e=>/[1-9]/.test(e))}),u.object({funding:u.literal("prepaid"),sourceId:u.uuid(),units:$,amount:re,pricing:u.array(St).min(1).max(12)}).strict().refine(e=>K(()=>e.pricing.reduce((t,n)=>t+k(n.units,6),0n)===k(e.units,6)&&e.pricing.reduce((t,n)=>t+k(n.amount,12),0n)===k(e.amount,12)&&e.pricing.every(t=>k(t.unitCost,6)*k(t.units,6)===k(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),u.object({funding:u.literal("postpaid"),invoiceLineId:u.uuid().nullable(),units:$,authorizationId:u.uuid()}).strict()]),ie=u.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Br=u.object({allowed:u.boolean(),internal_feature_id:u.uuid(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),reason:ie.nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.allowed?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),qr=u.object({id:u.uuid(),internal_feature_id:u.uuid(),kind:u.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:u.uuid().nullable(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),accepted:u.boolean(),reason:u.enum([...ie.options,"expired"]).nullable(),createdAt:u.iso.datetime({offset:!0}),reservationStatus:u.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:u.iso.datetime({offset:!0}).nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.accepted?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as T}from"zod";var xt=T.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),_t=T.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ze=T.strictObject({internal_feature_id:T.uuid(),entityId:T.uuid().nullable()}),Gr=ze.extend({quantity:E,expectedRevision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:T.string().min(1).max(120),properties:L.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Pe=ze.extend({operationId:T.uuid().nullable(),usage:E,capacity:xt.nullable(),remaining:_t.nullable(),withinLimit:T.boolean(),revision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:T.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=i=>{let a=i.startsWith("-"),[c,l=""]=(a?i.slice(1):i).split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(c)*10n**12n+BigInt(l.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});import{z as o}from"zod";var P=o.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),j=o.iso.datetime({offset:!0}),It=o.enum(["access","metered","credit"]),W={internal_feature_id:o.uuid(),key:V,name:o.string().min(1).max(120),kind:It},Jr=o.object({customerId:o.uuid(),snapshotAt:j,memberships:o.array(o.object({id:o.uuid(),productId:o.string().min(1).max(255),productVersionId:o.uuid(),billingProductVersionId:o.uuid(),version:o.number().int().positive(),key:o.string().min(1).max(64),name:o.string().min(1).max(120),groupId:o.string().max(255).nullable(),membershipType:o.enum(["main","addon"]),status:o.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:o.boolean(),accessEnabled:o.boolean(),renewalChange:o.object({productVersionId:o.uuid(),name:o.string().min(1).max(120),version:o.number().int().positive(),effectiveAt:j,benefitsAppliedAt:j.nullable(),timing:o.enum(["immediate","renewal"]),changeKind:o.enum(["plan","seats","quantity"]),feature:o.strictObject({internal_feature_id:o.uuid(),name:o.string().min(1).max(80),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).optional(),seat:o.object({key:o.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).strict().nullable(),status:o.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:o.object({phase:o.enum(["paid","trial"]),startsAt:j,endsAt:j.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:o.boolean(),balances:o.array(o.object({...W,usageType:o.enum(["consumable","non_consumable"]).nullable(),accessible:o.boolean(),unlimited:o.boolean(),available:P,held:P,debt:P,nextExpiresAt:j.nullable(),usage:Pe.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:o.boolean()}).strict(),we=o.enum(["source","usage","transaction","invoice","debt","settlement"]),oe=o.object({at:j,id:o.uuid(),type:we}).strict(),en=o.object({type:we.nullable(),resourceKey:V.optional(),kind:o.enum(["purchase","refund"]).optional(),topup:o.boolean().optional(),from:o.iso.date().nullable(),to:o.iso.date().nullable(),after:oe.nullable(),limit:o.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),F={id:o.uuid(),occurredAt:j},Et=o.discriminatedUnion("type",[o.strictObject({...F,type:o.literal("invoice"),status:o.string().min(1).max(80),paid:P,refunded:P,currency:O,externalId:o.string().nullable()}),o.object({...F,...W,type:o.literal("source"),reason:o.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:P,unlimited:o.boolean(),status:o.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:j,expiresAt:j.nullable(),orderId:o.uuid().nullable(),parentSourceId:o.uuid().nullable()}).strict(),o.object({...F,type:o.literal("usage"),internal_feature_id:o.uuid(),name:o.string().min(1).max(120),kind:o.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:o.uuid().nullable(),quantity:E,accepted:o.boolean(),reason:o.enum([...ie.options,"expired"]).nullable(),properties:L,reservationStatus:o.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:j.nullable(),charges:o.array(o.discriminatedUnion("funding",[o.strictObject({funding:o.literal("balance"),sourceId:o.uuid(),rolloverId:o.uuid().nullable(),units:Q,amount:P}),o.strictObject({funding:o.literal("unbilled"),units:Q}),o.object({...W,funding:o.literal("prepaid"),amount:P}).strict(),o.object({funding:o.literal("postpaid"),invoiceId:o.uuid(),invoiceLineId:o.uuid(),authorizationId:o.uuid(),units:E,currency:O}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),o.object({...F,type:o.literal("transaction"),purpose:o.enum(["product","invoice"]),productVersionId:o.uuid().nullable(),productName:o.string().min(1).max(120).nullable(),productVersion:o.number().int().positive().nullable(),invoiceId:o.uuid().nullable(),orderId:o.uuid(),originalId:o.uuid().nullable(),kind:o.enum(["purchase","refund"]),amountMinor:o.number().int().nonnegative().max(2e8).nullable(),currency:O.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),o.object({...F,...W,type:o.literal("debt"),sourceId:o.uuid(),transactionId:o.uuid(),amount:P}).strict(),o.object({...F,...W,type:o.literal("settlement"),sourceId:o.uuid(),debtId:o.uuid(),kind:o.enum(["payment","usage_refund","payment_return"]),amount:P}).strict()]),tn=o.object({customerId:o.uuid(),rows:o.array(Et).max(50),nextCursor:oe.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as Z}from"zod";var ve=Z.enum(["stripe","apple","google"]),on=Z.enum(["membership","credit_pack","lifetime"]),an=Z.enum(["active","grace","suspended","inactive","revoked"]),sn=Z.strictObject({currency:Z.string().regex(/^[A-Z]{3}$/),micros:Z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as At}from"zod";var Ue=At.object({provider:ve,currency:O}).strict();import{z as x}from"zod";var Ve=x.strictObject({internal_feature_id:x.uuid(),quantity:E.refine(e=>/[1-9]/.test(e)),properties:L,entityId:x.uuid().optional()}),yn=x.strictObject({requirement:Ve,commerce:Ue.optional(),paywallId:x.uuid().optional()}),Nt=x.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Rt=x.strictObject({productId:x.string().min(1),productVersionId:x.string().min(1),name:x.string().min(1).max(120),action:x.enum(["purchase","upgrade","addon","topup"]),membershipId:x.string().min(1).nullable(),currency:O,amountMinor:x.string().regex(/^(0|[1-9]\d{0,8})$/),interval:x.enum(["free","week","month","year","one_time"]),intervalCount:x.number().int().min(1).max(156)}),$e=x.strictObject({internal_feature_id:x.string().min(1),name:x.string().min(1).max(120),kind:x.enum(["access","metered","credit"]),quantity:E,allowed:x.boolean(),reason:Nt.nullable(),preview:x.strictObject({scenario:x.enum(["feature_flag","usage_limit"]),candidates:x.array(Rt).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),hn=x.strictObject({paywallId:x.uuid(),requirement:Ve});import{z as f}from"zod";var Ot=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],fe=f.object({plan:f.string().min(1).max(200).optional(),coupon:f.uuid().optional(),promotionCode:f.uuid().optional(),picker:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Be=f.object({text:f.string().optional(),label:f.string().optional(),alt:f.string().optional(),html:f.string().max(32768).optional(),price:f.object({current:f.string(),original:f.string().nullable(),period:f.string()}).optional(),code:f.string().optional(),countdownAt:f.iso.datetime().optional(),planId:f.string().min(1).max(200).optional(),planVersionId:f.string().min(1).max(200).optional(),currency:O.optional(),couponId:f.uuid().optional(),offerId:f.uuid().optional(),unavailable:f.boolean().optional(),unavailableReason:f.string().optional(),missing:f.array(f.string()).optional()}).strict(),En=f.object({paywall:$e.optional(),nodes:f.record(f.string(),f.object({base:Be,picker:f.string().optional(),byPlan:f.record(f.string(),Be).optional()}).strict()),plans:f.record(f.string(),f.object({id:f.string().min(1).max(200),versionId:f.string().min(1).max(200),available:f.boolean(),name:f.string(),price:f.string(),period:f.string(),currency:O.optional()}).strict()),pickers:f.record(f.string(),f.object({options:f.array(f.string().min(1).max(200)).max(20),selected:f.string().min(1).max(200).nullable()}).strict()),diagnostics:f.array(f.object({nodeId:f.string(),message:f.string()}).strict())}).strict();function ae(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function se(e){let t=ae(e).filter(i=>!Ot.includes(i)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(i)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function An(e,t,n,i=!1){let a=ae(e).filter(c=>!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(c)&&t[c]===void 0);return a.length&&!i?{value:n,missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(c,l)=>t[l.trim()]??c),missing:a}}function Nn(e,t,n={}){let i=e?.nodes[t];if(!i)return;let a=i.picker?n[i.picker]??e?.pickers[i.picker]?.selected:void 0;return typeof a=="string"?i.byPlan?.[a]??i.base:i.base}function qe(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function ce(e){let t={};function n(i){if(qe(i)){let a=t[i.interaction.pickerId]??={ids:[],defaultId:null};for(let l of i.children){let d=l.type==="stack"?l.bind?.plan:void 0;d&&!a.ids.includes(d)&&a.ids.push(d)}let c=i.children[i.interaction.defaultIndex];!a.defaultId&&c?.type==="stack"&&(a.defaultId=c.bind?.plan??null)}i.type==="stack"&&i.children.forEach(n)}return e.pages.forEach(i=>n(i.root)),t}function Me(e,t,n){let i={};function a(g){if(g.hidden)return;if(g.type==="plan_picker"){let b=n.pickers[g.id];i[g.id]={ids:b?.options??[],defaults:b?.selected?[b.selected]:[],remembered:[]};return}if(g.type!=="stack")return;let s=g.children.filter(b=>!b.hidden),p=g.interaction;if(qe(g)){let b=i[g.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},h=n.pickers[g.interaction.pickerId]?.options??[];for(let v of s){let R=v.type==="stack"?v.bind?.plan:void 0;R&&h.includes(R)&&!b.ids.includes(R)&&b.ids.push(R),R&&v.id===t[g.id]&&b.remembered.push(R)}let w=g.children[g.interaction.defaultIndex];w?.type==="stack"&&!w.hidden&&w.bind?.plan&&b.defaults.push(w.bind.plan)}if(p?.type==="tabs"){let b=s.find(h=>h.id===t[g.id])??g.children[p.defaultIndex];b&&a(b)}else if(p?.type==="toggle"){let b=typeof t[g.id]=="boolean"?t[g.id]:p.defaultEnabled,h=g.children[b?0:1];h&&a(h)}else s.forEach(a)}let c=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,l=e.pages.find(g=>g.id===c);l&&a(l.root);let d={};for(let[g,s]of Object.entries(i)){let p=t[g],b=s.remembered[0]??(s.ids.includes(n.pickers[g]?.selected??"")?n.pickers[g]?.selected:s.defaults[0]);d[g]=typeof p=="string"?s.ids.includes(p)?p:"":b&&s.ids.includes(b)?b:""}for(let g of Object.keys(ce(e)))d[g]??="";return d}import{z as U}from"zod";var Fe=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ze=U.strictObject({tiers:U.array(U.strictObject({id:Fe,name:U.string().trim().min(1).max(80)})).min(1).max(8),assignments:U.array(U.strictObject({productVersionId:U.string().min(1).max(200),tierId:Fe,period:U.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(i=>i.id);(new Set(n).size!==n.length||new Set(e.assignments.map(i=>i.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(i=>`${i.tierId}:${i.period}`)).size!==e.assignments.length||e.assignments.some(i=>!n.includes(i.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Ge(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as m}from"zod";var kt=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],He=m.enum(kt),Ke=m.object({source:He,layout:m.enum(["full","compact"]),resourceKey:V.optional(),pageSize:m.number().int().min(1).max(50),showSources:m.boolean(),allowPurchase:m.boolean(),outputs:m.object({billing_adjustment:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),N=m.string().max(2e3),Qe=m.object({id:m.string().max(100),label:N,detail:m.array(N).max(12),value:N.optional(),status:N.optional(),facts:m.array(m.object({label:N,value:N}).strict()).max(1e3),purchaseId:m.uuid().optional(),invoiceUrl:m.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:m.array(m.strictObject({action:m.literal("invoice_open"),label:N})).max(1).optional(),membershipActions:m.array(m.object({value:m.string().max(100),label:N}).strict()).max(3).optional()}).strict(),Ct=m.object({key:V,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:m.array(Qe).max(50),sourceCount:m.number().int().nonnegative(),sourcePage:m.number().int().positive(),hasNextSources:m.boolean(),hasPreviousSources:m.boolean()}).strict(),Lt=m.object({source:He,status:m.enum(["idle","loading","ready","error"]),stale:m.boolean(),preview:m.boolean(),errorCode:m.string().max(80).optional(),errorMessage:N.optional(),resources:m.array(Ct).max(500),rows:m.array(Qe).max(50),hasNext:m.boolean(),hasPrevious:m.boolean(),page:m.number().int().positive(),filter:m.string().max(40),updatedAt:m.iso.datetime().optional(),buyingId:m.uuid().optional(),membershipBusy:m.boolean().optional(),billingBusy:m.boolean().optional(),membershipReview:m.object({title:N,note:N,facts:m.array(m.object({label:N,value:N}).strict()).max(100)}).strict().optional(),membershipResult:N.optional()}).strict(),jn=m.object({nodes:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Lt)}).strict(),Dn=m.object({nodeId:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:m.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:m.string().max(100).optional()}).strict();function zn(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function ge(e){let t=se(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let i=n;if(e.startsWith("<!--",n)){let a=e.indexOf("-->",n+4);n=a<0?e.length:a+2}else{let a="";for(n++;n<e.length;n++){let c=e[n];if(a)c===a&&(a="");else if(c==='"'||c==="'")a=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(i,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function We(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function vn(e,t,n,i=!1){let a=ge(e);if(a.length)throw new Error(a[0]);let c=[...new Set(ae(e).filter(l=>!l.startsWith("variables.")&&t[l]===void 0))];return c.length&&!i?{value:We(n),missing:c}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(l,d)=>t[d.trim()]===void 0?l:We(t[d.trim()])),missing:c}}import{z as r}from"zod";var Tt=4,z={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},X=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),S=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),jt=r.enum(["none","xs","sm","md","lg","xl"]),Dt=r.enum(["none","sm","md","lg","full"]),be=r.string().regex(/^#[0-9a-fA-F]{6}$/),Je=r.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),ye=r.union([Je,r.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),r.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),r.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ye=r.object({primary:be,background:be,text:be,radius:Dt,font:r.enum(["system","serif","rounded","mono"])}).strict(),J=r.union([r.enum(["primary","text","muted","background","surface"]),r.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),y=(e,t)=>r.number().int().min(e).max(t),Xe=r.union([r.enum(["fit","fill"]),y(1,1200)]),zt=r.object({top:y(0,200),right:y(0,200),bottom:y(0,200),left:y(0,200)}).strict(),Pt=r.object({top:y(-100,200),right:y(-100,200),bottom:y(-100,200),left:y(-100,200)}).strict(),et=r.object({x:y(0,100),y:y(0,100)}).strict(),wt=r.discriminatedUnion("type",[r.object({type:r.literal("color"),color:J}).strict(),r.object({type:r.literal("linear"),angle:y(0,360),stops:r.array(r.object({color:J,at:y(0,100)}).strict()).min(2).max(4)}).strict(),r.object({type:r.literal("image"),src:ye,fit:r.enum(["cover","contain"]),position:et.optional()}).strict()]),vt=r.discriminatedUnion("type",[r.object({type:r.literal("rect"),radius:r.union([y(0,200),r.object({topLeft:y(0,200),topRight:y(0,200),bottomRight:y(0,200),bottomLeft:y(0,200)}).strict()])}).strict(),r.object({type:r.literal("pill")}).strict()]),Ut=r.object({width:y(0,12),color:J,style:r.enum(["solid","dashed"])}).strict(),Vt=r.object({x:y(-40,40),y:y(-40,40),blur:y(0,80),spread:y(-20,40),color:J}).strict(),$t=r.object({font:r.enum(["system","serif","rounded","mono"]),size:y(8,96),weight:r.number().int().min(100).max(900).multipleOf(100),lineHeight:r.number().min(.8).max(3),letterSpacing:r.number().min(-5).max(20),color:J,align:r.enum(["start","center","end"]),italic:r.boolean(),decoration:r.enum(["none","underline","line-through"]),transform:r.enum(["none","uppercase"])}).strict().partial(),B=r.object({width:Xe,height:Xe,padding:zt,margin:Pt,gap:y(0,120),grow:r.union([r.boolean(),r.number().min(0).max(12)]),background:wt,opacity:r.number().min(0).max(1),clipContent:r.boolean(),shape:vt,border:Ut,shadow:Vt,text:$t}).strict().partial(),C={id:X,name:r.string().trim().min(1).max(60).optional(),hidden:r.boolean().optional(),style:B.optional(),fallback:S.optional()},Bt=r.object({...C,type:r.literal("text"),productField:r.enum(["name","price","trial","period"]).optional(),feature:r.object({id:r.uuid(),field:r.enum(["name","allowance"])}).strict().optional(),text:S,variant:r.enum(["title","heading","body","caption"])}).strict(),qt=r.object({...C,type:r.literal("image"),src:ye,localizedSrc:r.record(M,ye).optional(),alt:S,aspect:r.enum(["auto","1:1","4:3","16:9","3:1"]),fit:r.enum(["cover","contain"]),position:et.optional()}).strict(),Mt=r.object({...C,type:r.literal("button"),label:S,variant:r.enum(["primary","secondary","link"]),action:S,purpose:r.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Ft=r.object({...C,type:r.literal("divider")}).strict(),Zt=r.object({...C,type:r.literal("customer_data"),title:S,data:Ke}).strict(),Gt=r.object({...C,type:r.literal("spacer"),size:jt}).strict(),Ht=r.object({...C,type:r.literal("custom_html"),html:r.record(M,r.string().max(z.customHtml)),css:r.string().max(z.customCss)}).strict(),Kt=r.object({...C,type:r.literal("price"),fallback:S,parts:r.object({current:B.optional(),original:B.optional(),period:B.optional()}).strict().optional()}).strict(),Qt=r.object({...C,type:r.literal("coupon_code"),label:S,fallback:S}).strict(),Wt=r.object({...C,type:r.literal("countdown"),source:r.enum(["offer.ends_at","offer.expires_at","fixed"]),at:r.iso.datetime().optional(),granularity:r.enum(["day","hour","minute","second"]),expired:S,fallback:S}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Yt=r.object({...C,type:r.literal("plan_picker"),label:S,fallback:S,planIds:r.array(r.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:r.string().min(1).max(200).optional(),grouping:Ze.safeExtend({monthLabel:S,yearLabel:S,unavailableLabel:S}).optional(),states:r.object({selected:B.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ge(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Xt=r.discriminatedUnion("type",[r.object({type:r.literal("input"),label:S,keyboard:r.enum(["text","email","tel","url"]),maxLength:y(1,500)}).strict(),r.object({type:r.literal("multiselect"),label:S,min:y(0,50),max:y(1,50)}).strict(),r.object({type:r.literal("select"),label:S,defaultIndex:y(0,49),purpose:r.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:B.optional()}).strict(),r.object({type:r.literal("tabs"),label:S,defaultIndex:y(0,49),purpose:r.literal("tier").optional()}).strict(),r.object({type:r.literal("toggle"),label:S,defaultEnabled:r.boolean()}).strict(),r.object({type:r.literal("carousel"),label:S}).strict()]),D={...C,type:r.literal("stack"),direction:r.enum(["vertical","horizontal","overlay"]),align:r.enum(["start","center","end","stretch"]),justify:r.enum(["start","center","end","between"]),productSlot:r.object({index:y(0,19),period:r.enum(["month","year"]).optional(),requireBinding:r.boolean().optional()}).strict().optional(),interaction:Xt.optional(),states:r.object({selected:B.optional()}).strict().optional(),purpose:r.literal("benefits").optional(),purchaseAction:S.optional(),buttonVariant:r.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},tt=r.lazy(()=>r.object({...C,type:D.type,direction:D.direction,align:D.align,justify:D.justify,children:r.array(Jt).max(z.children),productSlot:D.productSlot,interaction:D.interaction,states:D.states,purpose:D.purpose,purchaseAction:D.purchaseAction,buttonVariant:D.buttonVariant,bind:D.bind}).strict()),Jt=r.lazy(()=>r.union([tt,Bt,qt,Mt,Ft,Gt,Ht,Kt,Qt,Wt,Yt,Zt])),er=r.union([r.string().max(500),r.number().finite(),r.boolean(),r.null()]),Y={id:S,event:S,properties:r.record(S,er).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},tr=r.discriminatedUnion("type",[r.object({...Y,type:r.literal("navigate"),close:r.literal(!1),pageId:X}).strict(),r.object({...Y,type:r.literal("event"),close:r.boolean()}).strict(),r.object({...Y,type:r.literal("close"),close:r.literal(!0)}).strict(),r.object({...Y,type:r.literal("open_url"),close:r.boolean(),url:Je}).strict(),r.object({...Y,type:r.literal("claim_offer"),close:r.boolean(),couponId:r.uuid()}).strict()]),rr=r.object({defaultLocale:M,locales:r.record(M,r.record(S,r.string().max(z.stringLength)))}).strict(),nr=r.enum(["popup","paywall","onboarding","page","banner"]),Gn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages",banner:"/workspace/banners"},ir=r.discriminatedUnion("type",[r.object({type:r.literal("modal"),size:r.enum(["sm","md","lg"])}).strict(),r.object({type:r.literal("sheet"),size:r.enum(["sm","md","lg"])}).strict(),r.object({type:r.literal("fullscreen")}).strict(),r.object({type:r.literal("inline")}).strict()]),Hn={sm:360,md:420,lg:560},or=r.object({kind:r.literal("screen"),schemaVersion:r.literal(Tt),name:r.string().trim().min(1).max(80),surface:nr,initialPageId:X.optional(),presentation:ir,theme:Ye,pages:r.array(r.object({id:X,name:r.string().trim().min(1).max(60),root:tt,theme:Ye.optional(),editorPosition:r.object({x:r.number().finite().min(-1e5).max(1e5),y:r.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:rr,actions:r.array(tr).max(z.actions)}).strict();function G(e,t){for(let n of e.pages)ee(n.root,t)}function Kn(e,t){return{...e,pages:e.pages.map((n,i)=>i===0?{...n,root:t}:n)}}var ar=or.superRefine((e,t)=>{let n=z;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(p=>p.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let p of e.actions)p.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(b=>b.id===p.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let i=p=>t.addIssue({code:"custom",message:p}),a=Object.keys(e.strings.locales);a.includes(e.strings.defaultLocale)||i("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),a.length>z.locales&&i(`\u6700\u591A ${z.locales} \u79CD\u8BED\u8A00`);let c=new Set;for(let p of e.actions)c.has(p.id)&&i(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${p.id}`),c.add(p.id);let l=new Set;for(let p of e.pages)["next","back"].includes(p.id)&&i(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${p.id}`),l.has(p.id)&&i(`\u9875\u9762 id \u91CD\u590D\uFF1A${p.id}`),l.add(p.id);let d=new Set,g=0,s=!1;G(e,(p,b)=>{if(g++,b>z.depth&&(s=!0),d.has(p.id)&&i(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${p.id}`),d.add(p.id),p.type==="button"&&!c.has(p.action)&&i(`\u6309\u94AE ${p.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${p.action}`),p.type==="custom_html")for(let h of Object.keys(p.html))a.includes(h)||i(`\u81EA\u5B9A\u4E49 HTML ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`);if(p.type==="image")for(let h of Object.keys(p.localizedSrc??{}))a.includes(h)||i(`\u56FE\u7247 ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`)}),g>n.nodes&&i(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),s&&i(`\u5C42\u7EA7\u6700\u591A ${z.depth} \u5C42`)});function ee(e,t,n=1,i=null){if(t(e,n,i)!==!1&&e.type==="stack")for(let a of e.children)ee(a,t,n+1,e)}function Se(e){let t=[],n=new Set;return G(e,i=>{let a=(c,l,d)=>{n.has(c)||(n.add(c),t.push({key:c,nodeId:i.id,nodeType:i.type,field:l,required:d}))};i.type==="stack"&&i.interaction&&a(i.interaction.label,"label",!0),i.fallback&&a(i.fallback,"text",!0),i.type==="text"&&a(i.text,"text",!0),i.type==="customer_data"&&a(i.title,"title",!0),(i.type==="plan_picker"||i.type==="coupon_code")&&a(i.label,"label",!0),i.type==="plan_picker"&&i.grouping&&(a(i.grouping.monthLabel,"label",!0),a(i.grouping.yearLabel,"label",!0),a(i.grouping.unavailableLabel,"text",!0)),i.type==="countdown"&&a(i.expired,"text",!0),i.type==="button"&&a(i.label,"label",!0),i.type==="image"&&(a(`image:${i.id}`,"src",!1),a(i.alt,"alt",!1)),i.type==="custom_html"&&a(`html:${i.id}`,"html",!0)}),t}function sr(e,t,n){if(t.field==="html"){let i;return G(e,a=>{a.id===t.nodeId&&a.type==="custom_html"&&(i=a.html[n])}),i}if(t.field==="src"){let i=he(e,t.nodeId);return i?.type==="image"?i.localizedSrc?.[n]??(n===e.strings.defaultLocale?i.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function rt(e){let t=Se(e).filter(i=>i.required);return Object.keys(e.strings.locales).sort((i,a)=>i===e.strings.defaultLocale?-1:a===e.strings.defaultLocale?1:0).map(i=>{let a=t.filter(c=>!sr(e,c,i)?.trim()).map(c=>c.key);return{locale:i,total:t.length,filled:t.length-a.length,missing:a,complete:a.length===0}})}function Qn(e){return nt(e,!0)}function Wn(e){return nt(e,!1)}function nt(e,t){let n=[],i=t&&e.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"));i&&(!e.actions.some(s=>s.type==="claim_offer")||e.actions.some(s=>s.type==="event"&&typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-")))&&n.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function a(s,p){let b=s.type==="stack"||s.type==="button"?s.bind?.coupon??p:p;if(i&&s.type==="text"&&Object.values(e.strings.locales).some(h=>h[s.text]?.includes("{{offer."))&&!b&&n.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),s.type==="button"){let h=e.actions.find(w=>w.id===s.action);h?.type==="claim_offer"&&b&&b!==h.couponId&&n.push(`\u9886\u53D6\u6309\u94AE ${s.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}s.type==="stack"&&s.children.forEach(h=>a(h,b))}e.pages.forEach(s=>a(s.root));let c=[],l=ar.safeParse(e);l.success||n.push(...l.error.issues.map(s=>s.message));for(let s of Object.values(e.strings.locales))for(let p of Object.values(s))for(let b of se(p))n.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${b}`);G(e,s=>{if(s.type==="customer_data"&&Object.values(e.strings.locales).some(b=>/\{\{|\}\}/.test(b[s.title]??""))&&n.push(`\u6570\u636E\u7EC4\u4EF6 ${s.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(s.type==="text"?[s.text]:s.type==="button"?[s.label]:[]).some(b=>Object.values(e.strings.locales).some(h=>h[b]?.includes("{{")))&&!s.fallback&&n.push(`\u7EC4\u4EF6 ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),s.fallback&&Object.values(e.strings.locales).some(b=>b[s.fallback]?.includes("{{"))&&n.push(`\u7EC4\u4EF6 ${s.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),s.type==="custom_html"){for(let b of Object.values(s.html))n.push(...ge(b).map(h=>`HTML ${s.id}\uFF1A${h}`));Object.values(s.html).some(b=>b.includes("{{"))&&!s.fallback&&n.push(`HTML ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(s.css)&&n.push(`HTML ${s.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(s.type==="stack"||s.type==="button")&&s.bind?.picker&&he(e,s.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(ce(e),s.bind.picker)&&n.push(`\u5BB9\u5668 ${s.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let s of Object.keys(ce(e)))he(e,s)||n.push(`Product selection scope ${s} must reference a UI node`);let d=rt(e);for(let s of d)s.complete||(s.locale===e.strings.defaultLocale?n.push(`\u9ED8\u8BA4\u8BED\u8A00 ${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):n.push(`${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));Se(e).length===0&&!e.pages.some(s=>cr(s.root))&&n.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let g=new Set;G(e,s=>{s.type==="button"&&g.add(s.action)});for(let s of e.actions)!g.has(s.id)&&!e.pages.some(p=>lr(p.root,s.id))&&c.push(`\u52A8\u4F5C ${s.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:n,warnings:c}}function cr(e){let t=!1;return ee(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function lr(e,t){let n=!1;return ee(e,i=>{if(i.type==="custom_html")for(let a of Object.values(i.html))a.includes(`data-grow-action="${t}"`)&&(n=!0)}),n}function ur(e){return rt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Yn(e,t){return Te(t,ur(e),e.strings.defaultLocale)}function Xn(e,t){let n=e.strings.locales[t]??{},i=e.strings.locales[e.strings.defaultLocale]??{},a={};for(let l of Se(e)){if(l.field==="html"||l.field==="src")continue;let d=n[l.key]?.trim()?n[l.key]:i[l.key];d!==void 0&&(a[l.key]=d)}let c=l=>{if(l.type==="stack")return{...l,children:l.children.map(c)};if(l.type==="custom_html"){let d=l.html[t]?.trim()?l.html[t]:l.html[e.strings.defaultLocale];return{...l,html:d===void 0?{}:{[t]:d}}}if(l.type==="image"){let{localizedSrc:d,...g}=l;return{...g,src:d?.[t]??d?.[e.strings.defaultLocale]??l.src}}return l};return{...e,pages:e.pages.map(l=>({...l,root:c(l.root)})),strings:{defaultLocale:t,locales:{[t]:a}}}}function pr(e,t){let n=null;return ee(e,i=>{if(n)return!1;i.id===t&&(n=i)}),n}function he(e,t){for(let n of e.pages){let i=pr(n.root,t);if(i)return i}return null}function Jn(e){let t=de(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function ei(e,t,n){let i={};if(!t||typeof t!="object"||Array.isArray(t))return i;let a=t;if(G(e,c=>{if(c.type==="plan_picker"){let d=a[c.id];typeof d=="string"&&(i[c.id]=n?.pickers[c.id]?.options.includes(d)?d:"");return}if(c.type!=="stack"||!c.interaction)return;let l=Object.hasOwn(a,c.id)?a[c.id]:void 0;["select","tabs"].includes(c.interaction.type)&&typeof l=="string"&&c.children.some(d=>d.id===l)&&(i[c.id]=l),c.interaction.type==="toggle"&&typeof l=="boolean"&&(i[c.id]=l)}),e.surface==="paywall"&&typeof a.__page=="string"&&e.pages.some(c=>c.id===a.__page)&&(i.__page=a.__page),n){let c={...i};for(let[l,d]of Object.entries(a))(typeof d=="string"||typeof d=="boolean")&&(c[l]=d);Object.assign(i,Me(e,c,n))}return i}import{z as I}from"zod";var oi=I.discriminatedUnion("kind",[I.object({kind:I.literal("ledger"),cursor:oe}).strict(),I.object({kind:I.literal("billing"),cursor:I.uuid()}).strict()]),mr=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),dr=I.record(I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),I.union([I.string().max(500),I.boolean(),I.array(I.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),fr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function xe(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>xe(n,t+1)):Object.entries(e).some(([n,i])=>["__proto__","constructor","prototype"].includes(n)||fr.test(n)||xe(i,t+1)))}var gr=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,br=I.record(mr,ue).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!xe(e)&&!gr.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function ai(e){let t=Object.create(null);for(let[n,i]of new URL(e).searchParams)I.string().max(500).parse(i),Object.hasOwn(t,n)||(t[n]=i);return br.parse(t),t}var it=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yr=I.array(I.object({variable:it,componentId:it,required:I.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),si=I.object({bindings:yr,answers:dr,values:I.record(I.string(),ue).optional()}).strict();export{te as a,Sr as b,xr as c,ot as d,at as e,Ee as f,_r as g,Ie as h,st as i,Ir as j,ct as k,Ae as l,lt as m,Er as n,Ar as o,Nr as p,pt as q,O as r,pe as s,kr as t,Cr as u,Lr as v,re as w,E as x,mt as y,V as z,L as A,ke as B,dt as C,ft as D,gt as E,Dr as F,M as G,de as H,Te as I,ht as J,wr as K,ne as L,$r as M,St as N,Q as O,De as P,ie as Q,Br as R,qr as S,ze as T,Gr as U,Pe as V,P as W,Jr as X,we as Y,oe as Z,en as _,Et as $,tn as aa,ve as ba,on as ca,an as da,sn as ea,Ue as fa,Ve as ga,yn as ha,Nt as ia,Rt as ja,$e as ka,hn as la,Ot as ma,fe as na,Be as oa,En as pa,ae as qa,se as ra,An as sa,Nn as ta,qe as ua,ce as va,Me as wa,Ze as xa,Ge as ya,kt as za,He as Aa,Ke as Ba,Lt as Ca,jn as Da,Dn as Ea,zn as Fa,ge as Ga,We as Ha,vn as Ia,Tt as Ja,z as Ka,X as La,S as Ma,jt as Na,Dt as Oa,ye as Pa,Ye as Qa,J as Ra,Xe as Sa,zt as Ta,Pt as Ua,et as Va,wt as Wa,vt as Xa,Ut as Ya,Vt as Za,$t as _a,B as $a,Bt as ab,qt as bb,Mt as cb,Ft as db,Zt as eb,Gt as fb,Ht as gb,Kt as hb,Qt as ib,Wt as jb,Yt as kb,Xt as lb,tt as mb,Jt as nb,tr as ob,rr as pb,nr as qb,Gn as rb,ir as sb,Hn as tb,G as ub,Kn as vb,ar as wb,ee as xb,Se as yb,sr as zb,rt as Ab,Qn as Bb,Wn as Cb,ur as Db,Yn as Eb,Xn as Fb,pr as Gb,he as Hb,Jn as Ib,ei as Jb,oi as Kb,dr as Lb,br as Mb,ai as Nb,yr as Ob,si as Pb};
|