@tinkerlandai/indiana-sdk 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -2
- package/README.md +8 -4
- package/README.zh-CN.md +7 -3
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-BsrSG955.d.ts} +334 -518
- package/dist/chunk-3SONNXFG.js +1 -0
- package/dist/chunk-467Z5ISI.js +11 -0
- package/dist/{chunk-QG4GM4RI.js → chunk-4AWSZWZD.js} +1 -1
- package/dist/{chunk-5TEZEOHX.js → chunk-6MO6Y24B.js} +1 -1
- package/dist/chunk-HD74AAFS.js +1 -0
- package/dist/chunk-J4RHVU3W.js +1 -0
- package/dist/chunk-KQCTDXVD.js +17 -0
- package/dist/chunk-NOFNOHUI.js +1 -0
- package/dist/chunk-QO4YQLZ4.js +1 -0
- package/dist/chunk-RRII2DMC.js +1 -0
- package/dist/chunk-WCFVNF5D.js +1 -0
- package/dist/chunk-YAFMBXIE.js +4 -0
- package/dist/{client-OYRHOMUQ.js → client-F6UPJMHR.js} +1 -1
- package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-Bvd956GL.d.ts} +333 -25
- package/dist/controls-XG46TKUU.js +2 -0
- package/dist/errors-DrdTlPwf.d.ts +57 -0
- package/dist/funnel-runtime-host-26QI2W3S.js +1 -0
- package/dist/{funnel-runtime-start-CVb2YonU.d.ts → funnel-runtime-start-ChVYbLzV.d.ts} +7604 -3787
- package/dist/iam.js +1 -1
- package/dist/index.d.ts +3635 -1485
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -3
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +13 -13
- package/dist/page.js +1 -1
- package/dist/paywall-WKOHBYW7.js +1 -0
- package/dist/popup.d.ts +9 -16
- package/dist/popup.js +12 -12
- package/dist/react-native.d.ts +327 -0
- package/dist/react-native.js +1 -0
- package/dist/server.d.ts +6 -5
- package/dist/server.js +1 -1
- package/dist/src-UHLPVD6E.js +1 -0
- package/dist/visual.js +1 -1
- package/package.json +10 -3
- package/dist/chunk-CB63JLGT.js +0 -1
- package/dist/chunk-D7YHFS6B.js +0 -4
- package/dist/chunk-FF3LWJ26.js +0 -11
- package/dist/chunk-FVUPV6YE.js +0 -1
- package/dist/chunk-ISUXYPYL.js +0 -1
- package/dist/chunk-RMJJOSVZ.js +0 -1
- package/dist/chunk-S2MSIA57.js +0 -17
- package/dist/chunk-VVSQKVE7.js +0 -1
- package/dist/chunk-YAMBRNJ2.js +0 -1
- package/dist/funnel-runtime-host-KPYLOYYN.js +0 -1
- package/dist/paywall-5WU6PX5C.js +0 -1
- package/dist/src-U7PBAUBN.js +0 -1
- package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-B4LkIr5q.d.ts} +4 -4
- package/dist/{screen-16d-xADb.d.ts → screen-iFngkxaL.d.ts} +185 -185
package/dist/chunk-FVUPV6YE.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{kb as T,lb as P,ob as S}from"./chunk-FF3LWJ26.js";import{a as e}from"./chunk-5TEZEOHX.js";import{D as _,G as C,J as k,v as O}from"./chunk-RMJJOSVZ.js";import{a as j}from"./chunk-S5TVMQRC.js";import{b as E}from"./chunk-ISUXYPYL.js";var L={name:"@tinkerlandai/indiana-sdk",version:"0.6.3",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"},"./iam":{types:"./dist/iam.d.ts",import:"./dist/iam.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","rrweb-snapshot":"2.1.7","@rrweb/types":"2.1.7"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var X=Symbol("IndianaNoContent");function Q(a,V){let v=a.webView??"hosted";if(!["hosted","embedded"].includes(v))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=a.scope?E.parse(a.scope):void 0,s=new URL(a.baseUrl??j);if(s.username||s.password||s.search||s.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let U=a.fetch??globalThis.fetch.bind(globalThis),u=a.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,g,c=0,l=null,m=new Set;function R(){c+=1,p=null,l=null;for(let i of m)i.abort();m.clear()}async function M(i,H={},N="POST",q={}){if(!p)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let y=c,n=new AbortController;m.add(n);let f=()=>y!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),I,K=new Promise((t,o)=>{I=()=>o(f()),n.signal.addEventListener("abort",I,{once:!0})}),x=setTimeout(()=>n.abort(),u),F=async()=>{let t=await U(`${s.href.replace(/\/$/,"")}/api/v1/${i}`,{method:N,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:S.current,[P]:L.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:N==="POST"?JSON.stringify(H):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...q.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw f();let o;try{o=t.status===204?X:await t.json()}catch{throw n.signal.aborted?f():new e(t.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",t.status,t.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw f();if(y!==c)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!t.ok){let r=C.safeParse(o),w=r.success&&(!O.safeParse(r.data.error.code).success||_(r.data.error.code,t.status)),A=w?r.data.error.code:"HTTP_ERROR",D=k(A,t.status,{retryAfter:t.headers.get("Retry-After"),recovery:w?r.data.error.recovery:void 0,reason:w?r.data.error.reason:void 0});throw new e(A,w?r.data.error.message:"Indiana request failed",t.status,t.headers.get("X-Request-Id")??(r.success?r.data.requestId:void 0),{...D,...r.success&&r.data.error.retryable===!1?{retryable:!1}:{},...D.retryAfterSeconds===void 0&&r.success&&r.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:r.data.error.retryAfterSeconds}:{}})}if(t.headers.get(T)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&o&&typeof o=="object"&&"scope"in o){let r=E.safeParse(o.scope);if(!r.success||r.data.projectId!==d.projectId||r.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let b=t.headers.get("X-Indiana-Web-View");if(b){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(b))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");g=b}let h=t.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new e("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,V?.(l))}return o};try{return await Promise.race([F(),K])}catch(t){throw y!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):t instanceof e?t:new e(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(x),n.signal.removeEventListener("abort",I),m.delete(n)}}return{subjectKey:()=>l,webViewUrl(){if(v!=="embedded"){if(!g)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(g,s).href}},identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");R(),p=i},reset:R,request:M}}export{Q as a};
|
package/dist/chunk-ISUXYPYL.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as g}from"./chunk-U6S6AZM6.js";import{l as u,n as y}from"./chunk-S2MSIA57.js";import{z as x}from"zod";var E=x.enum(["sandbox","live"]),O=x.object({projectId:x.string().min(1),environment:E}).strict();import{z as t}from"zod";var f=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([r,p])=>r<=p),$=t.strictObject({attribute:t.string().optional(),seed:t.string(),hashVersion:t.literal(2),ranges:t.array(f).max(100)}),H=t.strictObject({id:t.string().min(1).max(255),condition:y,gate:t.boolean().optional()}),C=t.strictObject({key:t.string().optional(),name:t.string().optional(),passthrough:t.boolean().optional()}),k={condition:y.optional(),parentConditions:t.array(H).max(100).optional(),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),hashAttribute:t.string().optional(),fallbackAttribute:t.string().optional(),hashVersion:t.literal(2).optional(),disableStickyBucketing:t.boolean().optional(),bucketVersion:t.number().int().nonnegative().optional(),minBucketVersion:t.number().int().nonnegative().optional(),filters:t.array($).max(100).optional(),ranges:t.array(f).max(20).optional(),meta:t.array(C).max(20).optional(),seed:t.string().optional(),name:t.string().optional(),phase:t.string().optional()},b=t.strictObject({...k,key:t.string().min(1).max(255),variations:t.tuple([u,u]).rest(u).refine(r=>r.length<=20),urlPatterns:t.array(t.strictObject({include:t.boolean(),type:t.enum(["regex","simple"]),pattern:t.string()})).max(100).optional(),force:t.number().int().nonnegative().optional(),active:t.boolean().optional(),persistQueryString:t.boolean().optional()}),U=t.strictObject({value:u,variationId:t.number().int(),key:t.string(),name:t.string().optional(),bucket:t.number().optional(),passthrough:t.boolean().optional(),inExperiment:t.boolean(),hashUsed:t.boolean().optional(),hashAttribute:t.string(),hashValue:t.string(),featureId:t.string().nullable(),stickyBucketUsed:t.boolean().optional()}),_=t.strictObject({...k,id:t.string().max(255).optional(),force:u.optional(),variations:t.array(u).min(2).max(20).optional(),key:t.string().optional(),range:f.optional(),tracks:t.array(t.strictObject({experiment:b,result:U})).max(100).optional()}),D=t.strictObject({defaultValue:u.optional(),rules:t.array(_).max(500).optional()}),v=t.record(t.string(),t.union([t.strictObject({type:t.literal("hashed"),attributeKey:t.string(),values:t.array(t.string().regex(/^[a-f0-9]{64}$/))}),t.strictObject({type:t.literal("list"),attributeKey:t.string(),values:t.array(t.union([t.string(),t.number()]))}),t.strictObject({type:t.literal("condition"),condition:y})])),J=t.strictObject({scope:O,generation:t.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}).nullable(),features:t.record(t.string(),D),savedGroups:v,experiments:t.record(t.uuid(),b)});import{z as n}from"zod";import{z as e}from"zod";import{z as i}from"zod";var M=i.strictObject({schemaVersion:i.literal(1),renderKey:i.string().min(1).max(256),routeTemplate:i.string().startsWith("/").max(2048),selectors:i.array(i.string().regex(/^[a-z][a-z0-9-]*\[data-indiana-id="(?:[^"\\\x00-\x1f]|\\["\\])*"\]$/).max(512)).max(512),present:i.array(i.number().int().min(0).max(511)).min(1).max(512),absent:i.array(i.number().int().min(0).max(511)).max(512)}).superRefine((r,p)=>{let o=[...r.present,...r.absent];(new Set(r.selectors).size!==r.selectors.length||new Set(o).size!==o.length||o.length!==r.selectors.length||o.some(s=>s>=r.selectors.length))&&p.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),w=i.strictObject({renderKey:i.string().min(1).max(256),routeKey:i.string().min(1).max(256),stateKey:i.string().min(1).max(256),documentKey:i.string().min(1).max(256),documentHash:i.string().regex(/^[a-f0-9]{64}$/),compositionKey:i.string().min(1).max(256),entryMode:i.enum(["hard","soft"]),match:i.strictObject({present:i.array(i.number().int().min(0).max(511)).max(512),absent:i.array(i.number().int().min(0).max(511)).max(512)})});import{z as m}from"zod";var N={"enterprise-internal-indiana-test":"indiana-admin-vercel@enterprise-internal-490516.iam.gserviceaccount.com","tinkerland-indiana-prod":"indiana-admin-vercel@tinkerland-indiana.iam.gserviceaccount.com"},S="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",B=m.string().regex(new RegExp(`^${S}/${S}/${S}/manifest\\.json$`)),X="content-length;content-type;host;x-goog-if-generation-match",A=m.strictObject({kind:m.literal("gcs-v4-put"),url:m.url(),bucket:m.enum(["enterprise-internal-indiana-test","tinkerland-indiana-prod"]),objectKey:B,byteLength:m.number().int().min(1).max(8388608),expiresAt:m.iso.datetime(),headers:m.strictObject({"Content-Type":m.literal("application/json"),"x-goog-if-generation-match":m.literal("0")})}).superRefine((r,p)=>{let o=new URL(r.url),s=o.searchParams,j=["X-Goog-Algorithm","X-Goog-Credential","X-Goog-Date","X-Goog-Expires","X-Goog-Signature","X-Goog-SignedHeaders"],l=s.get("X-Goog-Date")??"",R=/^\d{8}T\d{6}Z$/.test(l)?Date.parse(`${l.slice(0,4)}-${l.slice(4,6)}-${l.slice(6,8)}T${l.slice(9,11)}:${l.slice(11,13)}:${l.slice(13,15)}Z`):NaN,d=Number(s.get("X-Goog-Expires"));(o.origin!=="https://storage.googleapis.com"||o.username||o.password||o.hash||o.pathname!==`/${r.bucket}/app-manifests/${r.objectKey}`||[...s.keys()].length!==j.length||j.some(z=>s.getAll(z).length!==1)||s.get("X-Goog-Algorithm")!=="GOOG4-RSA-SHA256"||s.get("X-Goog-Credential")!==`${N[r.bucket]}/${l.slice(0,8)}/auto/storage/goog4_request`||s.get("X-Goog-SignedHeaders")!==X||!/^[a-f0-9]{512,1024}$/.test(s.get("X-Goog-Signature")??"")||!Number.isFinite(R)||!Number.isInteger(d)||d<1||d>900||R+d*1e3!==Date.parse(r.expiresAt))&&p.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var G=8388608;var a=e.string().min(1).max(256),c=e.string().regex(/^[a-f0-9]{64}$/),me=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:a,stateKey:a,documentKey:a,documentHash:c,elementKey:a.optional(),nodeId:a.optional(),contentHash:c.optional(),renderKey:a.optional(),observed:e.optional(g)}),P=e.strictObject({observed:e.optional(g),pageKey:a,documentKey:a,expectedDocumentHash:c,renderKey:a.optional(),nodeId:a,elementKey:a,expectedContentHash:c,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),V=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:a,stateKey:a,documentKey:a,documentHash:c,renderKey:a.optional(),observed:e.optional(g),patches:e.array(P.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),le=e.discriminatedUnion("action",[e.strictObject({action:e.literal("register"),requestId:e.uuid(),label:e.string().trim().min(1).max(100),sha256:c,bytes:e.number().int().min(1).max(G),transferBytes:e.number().int().min(1).max(G)}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("materialize"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),observed:e.optional(g),variationId:a,changesetId:e.uuid().nullable(),expectedRevision:c.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(P).min(1).max(200)})]),h=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),label:e.string(),sha256:c,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),ue=e.strictObject({rows:e.array(h).max(100),nextCursor:e.uuid().nullable(),currentId:e.uuid().nullable()}),I=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),pe=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:I,runtime:I,previews:I})}),ge=e.strictObject({asOf:e.iso.datetime({offset:!0}),reviewOnly:e.literal(!0),complete:e.boolean(),issues:e.strictObject({scanLimit:e.boolean(),invalidReferences:e.number().int().nonnegative(),missingVersions:e.number().int().nonnegative()}),totals:e.strictObject({versions:e.number().int().nonnegative(),protected:e.number().int().nonnegative(),reviewCandidates:e.number().int().nonnegative()}),rows:e.array(e.strictObject({versionId:e.uuid(),kind:e.enum(["source","runtime"]),state:e.enum(["uploading","ready","rejected"]),createdAt:e.iso.datetime({offset:!0}),reviewAfter:e.iso.datetime({offset:!0}),reasons:e.array(e.enum(["current","upload-capability","retention-grace","incomplete-inventory","retained-observation","gb","gb-observation","funnel-draft","funnel-draft-observation","funnel-version","funnel-version-observation"])).max(11)})).max(50),nextCursor:e.uuid().nullable()}),de=e.strictObject({version:h,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),ye=e.strictObject({version:h,upload:A.nullable()}),be=e.strictObject({version:h,readOnly:e.boolean(),download:e.strictObject({url:e.url(),origin:e.url(),expiresIn:e.number().int().positive()})}),he=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:a,path:e.string(),documentKey:a,documentHash:c,initialStateKey:a,initialRenderKey:a})),renders:e.array(w).max(1e3)}).loose().superRefine((r,p)=>{(!r.renders||r.routes.some(o=>!r.renders?.some(s=>s.renderKey===o.initialRenderKey&&s.routeKey===o.routeKey&&s.documentKey===o.documentKey&&s.stateKey===o.initialStateKey&&s.documentHash===o.documentHash&&s.entryMode==="hard")))&&p.addIssue({code:"custom",message:"Incomplete render catalog"})}),xe=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:a,key:a,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),fe=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var T=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(r=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(r)||/^(aria|data)-[a-z0-9_-]+$/.test(r)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),F=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(T).max(200).default([]),iam:V.optional(),renderGuard:M.optional()}),K=F.omit({variation:!0,description:!0,iam:!0}),L=b.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([K,K]).rest(K).refine(r=>r.length<=20)}),Re=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(L).max(100),savedGroups:v}),Oe="__indiana_visual_editor",ke=n.object({selector:n.string().max(2048),tag:n.string().max(64),text:n.string().max(1e3),href:n.string().max(2048),src:n.string().max(2048),alt:n.string().max(2048).optional(),matches:n.number().int().nonnegative(),html:n.string().max(5e4).optional(),inlineStyle:n.string().max(5e4).optional(),styles:n.record(n.string(),n.string().max(1e3)).optional()});export{E as a,O as b,b as c,U as d,_ as e,D as f,v as g,J as h,me as i,T as j,F as k,K as l,L as m,Re as n,Oe as o,ke as p};
|
package/dist/chunk-RMJJOSVZ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{l as ue}from"./chunk-S2MSIA57.js";import{z as ct}from"zod";var lt=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],k=ct.enum(lt);function pe(e){let t=k.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function Nr(e,t){let r=pe(t),i=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!i?.[1]||(i[2]?.length??0)>r)throw new Error("Amount has invalid currency precision");let a=BigInt(i[1])*BigInt(10**r)+BigInt((i[2]??"").padEnd(r,"0")||"0");if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(a)}function Rr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let r=pe(t),i=String(e).padStart(r+1,"0");return r?`${i.slice(0,-r)}.${i.slice(-r)}`:i}function kr(e,t,r="en",i={}){let a=k.parse(t.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as I}from"zod";var te=I.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),A=I.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),ut=I.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),me=A.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ee=I.string().min(1).max(64),V=I.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ne=I.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),z=I.record(Ee,I.union([I.string().max(120),I.number().finite(),I.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,String(r)]))),Re=I.record(Ee,I.union([I.string().max(120),I.number().finite(),I.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Z=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[r,i=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");let a=BigInt(r)*BigInt("1000000")+BigInt(i.padEnd(6,"0"));return t?-a:a},ke=I.array(I.object({upTo:me.nullable(),cost:A}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,r)=>{let i=e[r-1]?.upTo;return t.upTo!==null&&(r===0||i!=null&&Z(t.upTo)>Z(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),pt=I.object({key:Ne,match:Re,priority:I.number().int().default(0),cost:A.optional(),tiers:ke.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),mt=I.object({key:Ne,match:Re,factor:me.optional(),add:ut.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),dt=I.object({units:me.default("1"),cost:A,tiers:ke.optional(),dimensions:I.array(pt).max(12).optional(),multipliers:I.array(mt).max(4).optional()}).strict().superRefine((e,t)=>{let r=e.dimensions??[],i=e.multipliers??[];(new Set(r.map(l=>l.key)).size!==r.length||new Set(i.map(l=>l.key)).size!==i.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[l,d]of r.entries())for(let g of r.slice(l+1))Object.keys(d.match).length===Object.keys(g.match).length&&d.priority===g.priority&&!Object.keys(d.match).some(s=>g.match[s]!==void 0&&g.match[s]!==d.match[s])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let a=[e.cost,...(e.tiers??[]).map(l=>l.cost),...r.flatMap(l=>[...l.cost===void 0?[]:[l.cost],...(l.tiers??[]).map(d=>d.cost)])],c=Z(e.units);for(let l of a)for(let d=0;d<1<<i.length;d++){let g=i.filter((v,R)=>d&1<<R);if(g.some((v,R)=>g.slice(R+1).some(Ae=>Object.keys(v.match).some(le=>Ae.match[le]!==void 0&&Ae.match[le]!==v.match[le]))))continue;let s=Z(l),p=BigInt("1"),y=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=Z(R.factor??"1"),p*=BigInt("1000000"),y+=Z(R.add??"0"));let h=(s+y*p)*BigInt("1000000"),P=p*c;(h<BigInt("0")||h%P!==BigInt("0")||h/P>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),zr=dt.safeExtend({featureKey:V});import{z as ft}from"zod";var je=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,U=ft.string().max(16).regex(je,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function de(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:r,script:i,region:a}=new Intl.Locale(t),c=[r,i,a].filter(Boolean).join("-");return je.test(c)?c:null}catch{return null}}var gt=new Set(["TW","HK","MO"]);function Oe(e){let[t,r,i]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let a=r?.length===4?r:void 0,c=r?.length===4?i:r;return a?`zh-${a}`:c&>.has(c)?"zh-Hant":"zh-Hans"}function ze(e,t,r){let i=t.map(a=>({code:U.parse(a),normalized:a}));for(let a of e){let c=de(a);if(!c)continue;let l=i.find(p=>p.normalized===c);if(l)return l.code;let d=Oe(c),g=i.filter(p=>Oe(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return r}var yt=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function Tr(e){return yt.find(t=>t.code===e)?.label??e}import{z as E}from"zod";var re=E.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Pr=E.enum([...re.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),vr=E.enum([...re.options,"stale_revision"]),bt=E.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),ht=E.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Ce={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function $r(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}function xt(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(["TIMEOUT","NETWORK_ERROR","HTTP_ERROR","INVALID_RESPONSE","INVALID_SERVER_RESPONSE"].includes(e))return{retryable:!1,recovery:"recover_operation"};if(e==="NOT_IDENTIFIED"||e==="INVALID_TOKEN")return{retryable:!1,recovery:"authenticate"};if(["INVALID_URL","INVALID_TIMEOUT","SERVER_ONLY","AMBIGUOUS_AUTHENTICATION"].includes(e))return{retryable:!1,recovery:"fix_request"};if(e==="PROTOCOL_MISMATCH")return{retryable:!1,recovery:"upgrade_sdk"};if(e==="IDENTITY_CHANGED")return{retryable:!1,recovery:"reload_state"};if(e==="CAPABILITY_UNAVAILABLE")return{retryable:!1,recovery:"check_availability"};let r=re.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Ce[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Ur(e,t){let r=re.safeParse(e);if(r.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Ce[r.data].status===t;let i={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(i,e)&&(i[e]?.includes(t)??!1)}function St(e,t=Date.now()){if(e===null)return;let r=e.trim();if(/^\d+$/.test(r)){let a=Number(r);return Number.isSafeInteger(a)?a:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(r))return;let i=Date.parse(r);return Number.isFinite(i)?Math.max(0,Math.ceil((i-t)/1e3)):void 0}var Le=E.object({retryable:E.boolean(),recovery:bt,reason:ht.optional(),retryAfterSeconds:E.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),It=E.object({requestId:E.uuid().optional(),error:E.object({code:E.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:E.string(),...Le.partial().shape})}),Vr=E.object({error:It.shape.error.extend({requestId:E.uuid().optional()})}),Br=E.object({error:E.string(),code:E.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:E.uuid(),...Le.shape});function qr(e,t,r={}){let i=xt(e,t),a=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??i.recovery,c=i.retryable&&r.retryable!==!1&&a!=="recover_operation",l=c?St(r.retryAfter??null):void 0;return{...i,retryable:c,recovery:a,...l===void 0?{}:{retryAfterSeconds:l},...r.reason?{reason:r.reason}:{}}}import{z as u}from"zod";var B=A.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),K=u.string().min(1).max(120),ne=u.enum(["cap","overflow"]),O=(e,t)=>{let[r,i=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");return BigInt(r)*10n**BigInt(t)+BigInt(i.padEnd(t,"0"))},G=e=>{try{return e()}catch{return!1}},Hr=u.discriminatedUnion("operation",[u.object({operation:u.literal("quote"),overageBehavior:ne.optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:B,properties:z}).strict(),u.object({operation:u.literal("consume"),overageBehavior:ne.optional(),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:A,properties:z,idempotencyKey:K}).strict(),u.object({operation:u.literal("reserve"),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:B,properties:z,idempotencyKey:K,expiresInSeconds:u.number().int().min(1).max(86400)}).strict(),u.object({operation:u.literal("confirm"),operationId:u.uuid(),quantity:B,properties:z.optional(),idempotencyKey:K}).strict(),u.object({operation:u.literal("refund"),operationId:u.uuid(),quantity:B,idempotencyKey:K}).strict(),u.object({operation:u.literal("release"),operationId:u.uuid(),idempotencyKey:K}).strict()]),_t=u.object({internal_credit_feature_id:u.uuid().nullable(),internal_metered_feature_id:u.uuid(),dimension:u.string().min(1).max(64),counterKey:u.string().min(1).max(240),cycleStart:u.iso.datetime({offset:!0}),unitCost:A,units:B,amount:te,tier:u.number().int().min(1).max(12).nullable()}).strict(),Q=u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Te(e,t){let r=e.reduce((i,a)=>i+O(a.units,12),0n)-O(t,12);return e.some(i=>i.funding==="balance")?r>=-100n&&r<=100n:r===0n}var we=u.discriminatedUnion("funding",[u.strictObject({funding:u.literal("balance"),sourceId:u.uuid(),rolloverId:u.uuid().nullable(),units:Q.refine(e=>/[1-9]/.test(e)),amount:te}),u.strictObject({funding:u.literal("unbilled"),units:Q.refine(e=>/[1-9]/.test(e))}),u.object({funding:u.literal("prepaid"),sourceId:u.uuid(),units:B,amount:te,pricing:u.array(_t).min(1).max(12)}).strict().refine(e=>G(()=>e.pricing.reduce((t,r)=>t+O(r.units,6),0n)===O(e.units,6)&&e.pricing.reduce((t,r)=>t+O(r.amount,12),0n)===O(e.amount,12)&&e.pricing.every(t=>O(t.unitCost,6)*O(t.units,6)===O(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),u.object({funding:u.literal("postpaid"),invoiceLineId:u.uuid().nullable(),units:B,authorizationId:u.uuid()}).strict()]),ie=u.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Kr=u.object({allowed:u.boolean(),internal_feature_id:u.uuid(),quantity:A,requestedQuantity:A.optional(),overageBehavior:ne.optional(),reason:ie.nullable(),allocations:u.array(we).max(500)}).strict().refine(e=>G(()=>e.allowed?e.reason===null&&Te(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>G(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&O(e.requestedQuantity,6)>=O(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Gr=u.object({id:u.uuid(),internal_feature_id:u.uuid(),kind:u.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:u.uuid().nullable(),quantity:A,requestedQuantity:A.optional(),overageBehavior:ne.optional(),accepted:u.boolean(),reason:u.enum([...ie.options,"expired"]).nullable(),createdAt:u.iso.datetime({offset:!0}),reservationStatus:u.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:u.iso.datetime({offset:!0}).nullable(),allocations:u.array(we).max(500)}).strict().refine(e=>G(()=>e.accepted?e.reason===null&&Te(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>G(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&O(e.requestedQuantity,6)>=O(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as C}from"zod";var At=C.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Et=C.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),De=C.strictObject({internal_feature_id:C.uuid(),entityId:C.uuid().nullable()}),Xr=De.extend({quantity:A,expectedRevision:C.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:C.string().min(1).max(120),properties:z.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Pe=De.extend({operationId:C.uuid().nullable(),usage:A,capacity:At.nullable(),remaining:Et.nullable(),withinLimit:C.boolean(),revision:C.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:C.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let r=i=>{let a=i.startsWith("-"),[c,l=""]=(a?i.slice(1):i).split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(c)*10n**12n+BigInt(l.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||r(e.remaining)!==r(e.capacity)-r(e.usage)||e.withinLimit!==r(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});import{z as o}from"zod";var D=o.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),L=o.iso.datetime({offset:!0}),Nt=o.enum(["access","metered","credit"]),W={internal_feature_id:o.uuid(),key:V,name:o.string().min(1).max(120),kind:Nt},an=o.object({customerId:o.uuid(),snapshotAt:L,memberships:o.array(o.object({id:o.uuid(),productId:o.string().min(1).max(255),productVersionId:o.uuid(),billingProductVersionId:o.uuid(),version:o.number().int().positive(),key:o.string().min(1).max(64),name:o.string().min(1).max(120),groupId:o.string().max(255).nullable(),membershipType:o.enum(["main","addon"]),status:o.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:o.boolean(),accessEnabled:o.boolean(),renewalChange:o.object({productVersionId:o.uuid(),name:o.string().min(1).max(120),version:o.number().int().positive(),effectiveAt:L,benefitsAppliedAt:L.nullable(),timing:o.enum(["immediate","renewal"]),changeKind:o.enum(["plan","seats","quantity"]),feature:o.strictObject({internal_feature_id:o.uuid(),name:o.string().min(1).max(80),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).optional(),seat:o.object({key:o.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).strict().nullable(),status:o.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:o.object({phase:o.enum(["paid","trial"]),startsAt:L,endsAt:L.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:o.boolean(),balances:o.array(o.object({...W,usageType:o.enum(["consumable","non_consumable"]).nullable(),accessible:o.boolean(),unlimited:o.boolean(),available:D,held:D,debt:D,nextExpiresAt:L.nullable(),usage:Pe.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:o.boolean()}).strict(),ve=o.enum(["source","usage","transaction","invoice","debt","settlement"]),oe=o.object({at:L,id:o.uuid(),type:ve}).strict(),sn=o.object({type:ve.nullable(),resourceKey:V.optional(),kind:o.enum(["purchase","refund"]).optional(),topup:o.boolean().optional(),from:o.iso.date().nullable(),to:o.iso.date().nullable(),after:oe.nullable(),limit:o.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),M={id:o.uuid(),occurredAt:L},Rt=o.discriminatedUnion("type",[o.strictObject({...M,type:o.literal("invoice"),status:o.string().min(1).max(80),paid:D,refunded:D,currency:k,externalId:o.string().nullable()}),o.object({...M,...W,type:o.literal("source"),reason:o.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:D,unlimited:o.boolean(),status:o.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:L,expiresAt:L.nullable(),orderId:o.uuid().nullable(),parentSourceId:o.uuid().nullable()}).strict(),o.object({...M,type:o.literal("usage"),internal_feature_id:o.uuid(),name:o.string().min(1).max(120),kind:o.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:o.uuid().nullable(),quantity:A,accepted:o.boolean(),reason:o.enum([...ie.options,"expired"]).nullable(),properties:z,reservationStatus:o.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:L.nullable(),charges:o.array(o.discriminatedUnion("funding",[o.strictObject({funding:o.literal("balance"),sourceId:o.uuid(),rolloverId:o.uuid().nullable(),units:Q,amount:D}),o.strictObject({funding:o.literal("unbilled"),units:Q}),o.object({...W,funding:o.literal("prepaid"),amount:D}).strict(),o.object({funding:o.literal("postpaid"),invoiceId:o.uuid(),invoiceLineId:o.uuid(),authorizationId:o.uuid(),units:A,currency:k}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),o.object({...M,type:o.literal("transaction"),purpose:o.enum(["product","invoice"]),productVersionId:o.uuid().nullable(),productName:o.string().min(1).max(120).nullable(),productVersion:o.number().int().positive().nullable(),invoiceId:o.uuid().nullable(),orderId:o.uuid(),originalId:o.uuid().nullable(),kind:o.enum(["purchase","refund"]),amountMinor:o.number().int().nonnegative().max(2e8).nullable(),currency:k.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),o.object({...M,...W,type:o.literal("debt"),sourceId:o.uuid(),transactionId:o.uuid(),amount:D}).strict(),o.object({...M,...W,type:o.literal("settlement"),sourceId:o.uuid(),debtId:o.uuid(),kind:o.enum(["payment","usage_refund","payment_return"]),amount:D}).strict()]),cn=o.object({customerId:o.uuid(),rows:o.array(Rt).max(50),nextCursor:oe.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as F}from"zod";var $e=F.enum(["stripe","apple","google"]),pn=F.enum(["membership","credit_pack","lifetime"]),mn=F.enum(["active","grace","suspended","inactive","revoked"]),dn=F.strictObject({currency:F.string().regex(/^[A-Z]{3}$/),micros:F.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as kt}from"zod";var Ue=kt.object({provider:$e,currency:k}).strict();import{z as S}from"zod";var Ve=S.strictObject({internal_feature_id:S.uuid(),quantity:A.refine(e=>/[1-9]/.test(e)),properties:z,entityId:S.uuid().optional()}),An=S.strictObject({requirement:Ve,commerce:Ue.optional(),paywallId:S.uuid().optional()}),Ot=S.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),jt=S.strictObject({productId:S.string().min(1),productVersionId:S.string().min(1),name:S.string().min(1).max(120),action:S.enum(["purchase","upgrade","addon","topup"]),membershipId:S.string().min(1).nullable(),currency:k,amountMinor:S.string().regex(/^(0|[1-9]\d{0,8})$/),interval:S.enum(["free","week","month","year","one_time"]),intervalCount:S.number().int().min(1).max(156)}),Be=S.strictObject({internal_feature_id:S.string().min(1),name:S.string().min(1).max(120),kind:S.enum(["access","metered","credit"]),quantity:A,allowed:S.boolean(),reason:Ot.nullable(),preview:S.strictObject({scenario:S.enum(["feature_flag","usage_limit"]),candidates:S.array(jt).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(r=>r.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),En=S.strictObject({paywallId:S.uuid(),requirement:Ve});import{z as $}from"zod";var qe=$.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ze=$.strictObject({tiers:$.array($.strictObject({id:qe,name:$.string().trim().min(1).max(80)})).min(1).max(8),assignments:$.array($.strictObject({productVersionId:$.string().min(1).max(200),tierId:qe,period:$.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let r=e.tiers.map(i=>i.id);(new Set(r).size!==r.length||new Set(e.assignments.map(i=>i.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(i=>`${i.tierId}:${i.period}`)).size!==e.assignments.length||e.assignments.some(i=>!r.includes(i.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Me(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}function Fe(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function ae(e){let t={};function r(i){if(Fe(i)){let a=t[i.interaction.pickerId]??={ids:[],defaultId:null};for(let l of i.children){let d=l.type==="stack"?l.bind?.plan:void 0;d&&!a.ids.includes(d)&&a.ids.push(d)}let c=i.children[i.interaction.defaultIndex];!a.defaultId&&c?.type==="stack"&&(a.defaultId=c.bind?.plan??null)}i.type==="stack"&&i.children.forEach(r)}return e.pages.forEach(i=>r(i.root)),t}function He(e,t,r){let i={};function a(g){if(g.hidden)return;if(g.type==="plan_picker"){let y=r.pickers[g.id];i[g.id]={ids:y?.options??[],defaults:y?.selected?[y.selected]:[],remembered:[]};return}if(g.type!=="stack")return;let s=g.children.filter(y=>!y.hidden),p=g.interaction;if(Fe(g)){let y=i[g.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},h=r.pickers[g.interaction.pickerId]?.options??[];for(let v of s){let R=v.type==="stack"?v.bind?.plan:void 0;R&&h.includes(R)&&!y.ids.includes(R)&&y.ids.push(R),R&&v.id===t[g.id]&&y.remembered.push(R)}let P=g.children[g.interaction.defaultIndex];P?.type==="stack"&&!P.hidden&&P.bind?.plan&&y.defaults.push(P.bind.plan)}if(p?.type==="tabs"){let y=s.find(h=>h.id===t[g.id])??g.children[p.defaultIndex];y&&a(y)}else if(p?.type==="toggle"){let y=typeof t[g.id]=="boolean"?t[g.id]:p.defaultEnabled,h=g.children[y?0:1];h&&a(h)}else s.forEach(a)}let c=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,l=e.pages.find(g=>g.id===c);l&&a(l.root);let d={};for(let[g,s]of Object.entries(i)){let p=t[g],y=s.remembered[0]??(s.ids.includes(r.pickers[g]?.selected??"")?r.pickers[g]?.selected:s.defaults[0]);d[g]=typeof p=="string"?s.ids.includes(p)?p:"":y&&s.ids.includes(y)?y:""}for(let g of Object.keys(ae(e)))d[g]??="";return d}import{z as f}from"zod";var zt=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],fe=f.object({plan:f.string().min(1).max(200).optional(),coupon:f.uuid().optional(),promotionCode:f.uuid().optional(),picker:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ke=f.object({text:f.string().optional(),label:f.string().optional(),alt:f.string().optional(),html:f.string().max(32768).optional(),price:f.object({current:f.string(),original:f.string().nullable(),period:f.string()}).optional(),code:f.string().optional(),countdownAt:f.iso.datetime().optional(),planId:f.string().min(1).max(200).optional(),planVersionId:f.string().min(1).max(200).optional(),currency:k.optional(),couponId:f.uuid().optional(),offerId:f.uuid().optional(),unavailable:f.boolean().optional(),unavailableReason:f.string().optional(),missing:f.array(f.string()).optional()}).strict(),Ln=f.object({paywall:Be.optional(),nodes:f.record(f.string(),f.object({base:Ke,picker:f.string().optional(),byPlan:f.record(f.string(),Ke).optional()}).strict()),plans:f.record(f.string(),f.object({id:f.string().min(1).max(200),versionId:f.string().min(1).max(200),available:f.boolean(),name:f.string(),price:f.string(),period:f.string(),currency:k.optional()}).strict()),pickers:f.record(f.string(),f.object({options:f.array(f.string().min(1).max(200)).max(20),selected:f.string().min(1).max(200).nullable()}).strict()),diagnostics:f.array(f.object({nodeId:f.string(),message:f.string()}).strict())}).strict();function se(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function ce(e){let t=se(e).filter(i=>!zt.includes(i)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(i)),r=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(r.includes("{{")||r.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function Tn(e,t,r,i=!1){let a=se(e).filter(c=>!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(c)&&t[c]===void 0);return a.length&&!i?{value:r,missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(c,l)=>t[l.trim()]??c),missing:a}}function wn(e,t,r={}){let i=e?.nodes[t];if(!i)return;let a=i.picker?r[i.picker]??e?.pickers[i.picker]?.selected:void 0;return typeof a=="string"?i.byPlan?.[a]??i.base:i.base}import{z as m}from"zod";var Ct=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Ge=m.enum(Ct),Qe=m.object({source:Ge,layout:m.enum(["full","compact"]),resourceKey:V.optional(),pageSize:m.number().int().min(1).max(50),showSources:m.boolean(),allowPurchase:m.boolean(),outputs:m.object({billing_adjustment:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),N=m.string().max(2e3),We=m.object({id:m.string().max(100),label:N,detail:m.array(N).max(12),value:N.optional(),status:N.optional(),facts:m.array(m.object({label:N,value:N}).strict()).max(1e3),purchaseId:m.uuid().optional(),invoiceUrl:m.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:m.array(m.strictObject({action:m.literal("invoice_open"),label:N})).max(1).optional(),membershipActions:m.array(m.object({value:m.string().max(100),label:N}).strict()).max(3).optional()}).strict(),Lt=m.object({key:V,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:m.array(We).max(50),sourceCount:m.number().int().nonnegative(),sourcePage:m.number().int().positive(),hasNextSources:m.boolean(),hasPreviousSources:m.boolean()}).strict(),Tt=m.object({source:Ge,status:m.enum(["idle","loading","ready","error"]),stale:m.boolean(),preview:m.boolean(),errorCode:m.string().max(80).optional(),errorMessage:N.optional(),resources:m.array(Lt).max(500),rows:m.array(We).max(50),hasNext:m.boolean(),hasPrevious:m.boolean(),page:m.number().int().positive(),filter:m.string().max(40),updatedAt:m.iso.datetime().optional(),buyingId:m.uuid().optional(),membershipBusy:m.boolean().optional(),billingBusy:m.boolean().optional(),membershipReview:m.object({title:N,note:N,facts:m.array(m.object({label:N,value:N}).strict()).max(100)}).strict().optional(),membershipResult:N.optional()}).strict(),$n=m.object({nodes:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Tt)}).strict(),Un=m.object({nodeId:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:m.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:m.string().max(100).optional()}).strict();function Vn(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function ge(e){let t=ce(e).map(r=>`\u672A\u77E5\u53D8\u91CF\uFF1A${r}`);for(let r=0;r<e.length;r++){if(e[r]!=="<"||!/[A-Za-z!/?{]/.test(e[r+1]??""))continue;let i=r;if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4);r=a<0?e.length:a+2}else{let a="";for(r++;r<e.length;r++){let c=e[r];if(a)c===a&&(a="");else if(c==='"'||c==="'")a=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(i,r+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function Ye(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Zn(e,t,r,i=!1){let a=ge(e);if(a.length)throw new Error(a[0]);let c=[...new Set(se(e).filter(l=>!l.startsWith("variables.")&&t[l]===void 0))];return c.length&&!i?{value:Ye(r),missing:c}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(l,d)=>t[d.trim()]===void 0?l:Ye(t[d.trim()])),missing:c}}import{z as n}from"zod";var wt=4,w={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},X=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),x=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dt=n.enum(["none","xs","sm","md","lg","xl"]),Pt=n.enum(["none","sm","md","lg","full"]),ye=n.string().regex(/^#[0-9a-fA-F]{6}$/),et=n.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),be=n.union([et,n.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Xe=n.object({primary:ye,background:ye,text:ye,radius:Pt,font:n.enum(["system","serif","rounded","mono"])}).strict(),J=n.union([n.enum(["primary","text","muted","background","surface"]),n.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),b=(e,t)=>n.number().int().min(e).max(t),Je=n.union([n.enum(["fit","fill"]),b(1,1200)]),vt=n.object({top:b(0,200),right:b(0,200),bottom:b(0,200),left:b(0,200)}).strict(),$t=n.object({top:b(-100,200),right:b(-100,200),bottom:b(-100,200),left:b(-100,200)}).strict(),tt=n.object({x:b(0,100),y:b(0,100)}).strict(),Ut=n.discriminatedUnion("type",[n.object({type:n.literal("color"),color:J}).strict(),n.object({type:n.literal("linear"),angle:b(0,360),stops:n.array(n.object({color:J,at:b(0,100)}).strict()).min(2).max(4)}).strict(),n.object({type:n.literal("image"),src:be,fit:n.enum(["cover","contain"]),position:tt.optional()}).strict()]),Vt=n.discriminatedUnion("type",[n.object({type:n.literal("rect"),radius:n.union([b(0,200),n.object({topLeft:b(0,200),topRight:b(0,200),bottomRight:b(0,200),bottomLeft:b(0,200)}).strict()])}).strict(),n.object({type:n.literal("pill")}).strict()]),Bt=n.object({width:b(0,12),color:J,style:n.enum(["solid","dashed"])}).strict(),qt=n.object({x:b(-40,40),y:b(-40,40),blur:b(0,80),spread:b(-20,40),color:J}).strict(),Zt=n.object({font:n.enum(["system","serif","rounded","mono"]),size:b(8,96),weight:n.number().int().min(100).max(900).multipleOf(100),lineHeight:n.number().min(.8).max(3),letterSpacing:n.number().min(-5).max(20),color:J,align:n.enum(["start","center","end"]),italic:n.boolean(),decoration:n.enum(["none","underline","line-through"]),transform:n.enum(["none","uppercase"])}).strict().partial(),q=n.object({width:Je,height:Je,padding:vt,margin:$t,gap:b(0,120),grow:n.union([n.boolean(),n.number().min(0).max(12)]),background:Ut,opacity:n.number().min(0).max(1),clipContent:n.boolean(),shape:Vt,border:Bt,shadow:qt,text:Zt}).strict().partial(),j={id:X,name:n.string().trim().min(1).max(60).optional(),hidden:n.boolean().optional(),style:q.optional(),fallback:x.optional()},Mt=n.object({...j,type:n.literal("text"),productField:n.enum(["name","price","trial","period"]).optional(),feature:n.object({id:n.uuid(),field:n.enum(["name","allowance"])}).strict().optional(),text:x,variant:n.enum(["title","heading","body","caption"])}).strict(),Ft=n.object({...j,type:n.literal("image"),src:be,localizedSrc:n.record(U,be).optional(),alt:x,aspect:n.enum(["auto","1:1","4:3","16:9","3:1"]),fit:n.enum(["cover","contain"]),position:tt.optional()}).strict(),Ht=n.object({...j,type:n.literal("button"),label:x,variant:n.enum(["primary","secondary","link"]),action:x,purpose:n.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Kt=n.object({...j,type:n.literal("divider")}).strict(),Gt=n.object({...j,type:n.literal("customer_data"),title:x,data:Qe}).strict(),Qt=n.object({...j,type:n.literal("spacer"),size:Dt}).strict(),Wt=n.object({...j,type:n.literal("custom_html"),html:n.record(U,n.string().max(w.customHtml)),css:n.string().max(w.customCss)}).strict(),Yt=n.object({...j,type:n.literal("price"),fallback:x,parts:n.object({current:q.optional(),original:q.optional(),period:q.optional()}).strict().optional()}).strict(),Xt=n.object({...j,type:n.literal("coupon_code"),label:x,fallback:x}).strict(),Jt=n.object({...j,type:n.literal("countdown"),source:n.enum(["offer.ends_at","offer.expires_at","fixed"]),at:n.iso.datetime().optional(),granularity:n.enum(["day","hour","minute","second"]),expired:x,fallback:x}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),er=n.object({...j,type:n.literal("plan_picker"),label:x,fallback:x,planIds:n.array(n.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:n.string().min(1).max(200).optional(),grouping:Ze.safeExtend({monthLabel:x,yearLabel:x,unavailableLabel:x}).optional(),states:n.object({selected:q.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Me(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),tr=n.discriminatedUnion("type",[n.object({type:n.literal("input"),label:x,keyboard:n.enum(["text","email","tel","url"]),maxLength:b(1,500)}).strict(),n.object({type:n.literal("multiselect"),label:x,min:b(0,50),max:b(1,50)}).strict(),n.object({type:n.literal("select"),label:x,defaultIndex:b(0,49),purpose:n.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:q.optional()}).strict(),n.object({type:n.literal("tabs"),label:x,defaultIndex:b(0,49),purpose:n.literal("tier").optional()}).strict(),n.object({type:n.literal("toggle"),label:x,defaultEnabled:n.boolean()}).strict(),n.object({type:n.literal("carousel"),label:x}).strict()]),T={...j,type:n.literal("stack"),direction:n.enum(["vertical","horizontal","overlay"]),align:n.enum(["start","center","end","stretch"]),justify:n.enum(["start","center","end","between"]),productSlot:n.object({index:b(0,19),period:n.enum(["month","year"]).optional(),requireBinding:n.boolean().optional()}).strict().optional(),interaction:tr.optional(),states:n.object({selected:q.optional()}).strict().optional(),purpose:n.literal("benefits").optional(),purchaseAction:x.optional(),buttonVariant:n.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},rt=n.lazy(()=>n.object({...j,type:T.type,direction:T.direction,align:T.align,justify:T.justify,children:n.array(rr).max(w.children),productSlot:T.productSlot,interaction:T.interaction,states:T.states,purpose:T.purpose,purchaseAction:T.purchaseAction,buttonVariant:T.buttonVariant,bind:T.bind}).strict()),rr=n.lazy(()=>n.union([rt,Mt,Ft,Ht,Kt,Qt,Wt,Yt,Xt,Jt,er,Gt])),nr=n.union([n.string().max(500),n.number().finite(),n.boolean(),n.null()]),Y={id:x,event:x,properties:n.record(x,nr).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ir=n.discriminatedUnion("type",[n.object({...Y,type:n.literal("navigate"),close:n.literal(!1),pageId:X}).strict(),n.object({...Y,type:n.literal("event"),close:n.boolean()}).strict(),n.object({...Y,type:n.literal("close"),close:n.literal(!0)}).strict(),n.object({...Y,type:n.literal("open_url"),close:n.boolean(),url:et}).strict(),n.object({...Y,type:n.literal("claim_offer"),close:n.boolean(),couponId:n.uuid()}).strict()]),or=n.object({defaultLocale:U,locales:n.record(U,n.record(x,n.string().max(w.stringLength)))}).strict(),ar=n.enum(["popup","paywall","onboarding","page"]),Xn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},sr=n.discriminatedUnion("type",[n.object({type:n.literal("modal"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("sheet"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("fullscreen")}).strict()]),Jn={sm:360,md:420,lg:560},cr=n.object({kind:n.literal("screen"),schemaVersion:n.literal(wt),name:n.string().trim().min(1).max(80),surface:ar,initialPageId:X.optional(),presentation:sr,theme:Xe,pages:n.array(n.object({id:X,name:n.string().trim().min(1).max(60),root:rt,theme:Xe.optional(),editorPosition:n.object({x:n.number().finite().min(-1e5).max(1e5),y:n.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(w.pages),strings:or,actions:n.array(ir).max(w.actions)}).strict();function H(e,t){for(let r of e.pages)ee(r.root,t)}function ei(e,t){return{...e,pages:e.pages.map((r,i)=>i===0?{...r,root:t}:r)}}var lr=cr.superRefine((e,t)=>{let r=w;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(p=>p.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let p of e.actions)p.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(y=>y.id===p.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>r.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${r.pages} \u4E2A`}),e.actions.length>r.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${r.actions} \u4E2A`});let i=p=>t.addIssue({code:"custom",message:p}),a=Object.keys(e.strings.locales);a.includes(e.strings.defaultLocale)||i("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),a.length>w.locales&&i(`\u6700\u591A ${w.locales} \u79CD\u8BED\u8A00`);let c=new Set;for(let p of e.actions)c.has(p.id)&&i(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${p.id}`),c.add(p.id);let l=new Set;for(let p of e.pages)["next","back"].includes(p.id)&&i(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${p.id}`),l.has(p.id)&&i(`\u9875\u9762 id \u91CD\u590D\uFF1A${p.id}`),l.add(p.id);let d=new Set,g=0,s=!1;H(e,(p,y)=>{if(g++,y>w.depth&&(s=!0),d.has(p.id)&&i(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${p.id}`),d.add(p.id),p.type==="button"&&!c.has(p.action)&&i(`\u6309\u94AE ${p.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${p.action}`),p.type==="custom_html")for(let h of Object.keys(p.html))a.includes(h)||i(`\u81EA\u5B9A\u4E49 HTML ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`);if(p.type==="image")for(let h of Object.keys(p.localizedSrc??{}))a.includes(h)||i(`\u56FE\u7247 ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`)}),g>r.nodes&&i(`\u7EC4\u4EF6\u6700\u591A ${r.nodes} \u4E2A`),s&&i(`\u5C42\u7EA7\u6700\u591A ${w.depth} \u5C42`)});function ee(e,t,r=1,i=null){if(t(e,r,i)!==!1&&e.type==="stack")for(let a of e.children)ee(a,t,r+1,e)}function xe(e){let t=[],r=new Set;return H(e,i=>{let a=(c,l,d)=>{r.has(c)||(r.add(c),t.push({key:c,nodeId:i.id,nodeType:i.type,field:l,required:d}))};i.type==="stack"&&i.interaction&&a(i.interaction.label,"label",!0),i.fallback&&a(i.fallback,"text",!0),i.type==="text"&&a(i.text,"text",!0),i.type==="customer_data"&&a(i.title,"title",!0),(i.type==="plan_picker"||i.type==="coupon_code")&&a(i.label,"label",!0),i.type==="plan_picker"&&i.grouping&&(a(i.grouping.monthLabel,"label",!0),a(i.grouping.yearLabel,"label",!0),a(i.grouping.unavailableLabel,"text",!0)),i.type==="countdown"&&a(i.expired,"text",!0),i.type==="button"&&a(i.label,"label",!0),i.type==="image"&&(a(`image:${i.id}`,"src",!1),a(i.alt,"alt",!1)),i.type==="custom_html"&&a(`html:${i.id}`,"html",!0)}),t}function ur(e,t,r){if(t.field==="html"){let i;return H(e,a=>{a.id===t.nodeId&&a.type==="custom_html"&&(i=a.html[r])}),i}if(t.field==="src"){let i=he(e,t.nodeId);return i?.type==="image"?i.localizedSrc?.[r]??(r===e.strings.defaultLocale?i.src:void 0):void 0}return e.strings.locales[r]?.[t.key]}function nt(e){let t=xe(e).filter(i=>i.required);return Object.keys(e.strings.locales).sort((i,a)=>i===e.strings.defaultLocale?-1:a===e.strings.defaultLocale?1:0).map(i=>{let a=t.filter(c=>!ur(e,c,i)?.trim()).map(c=>c.key);return{locale:i,total:t.length,filled:t.length-a.length,missing:a,complete:a.length===0}})}function ti(e){return it(e,!0)}function ri(e){return it(e,!1)}function it(e,t){let r=[],i=t&&e.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"));i&&(!e.actions.some(s=>s.type==="claim_offer")||e.actions.some(s=>s.type==="event"&&typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-")))&&r.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function a(s,p){let y=s.type==="stack"||s.type==="button"?s.bind?.coupon??p:p;if(i&&s.type==="text"&&Object.values(e.strings.locales).some(h=>h[s.text]?.includes("{{offer."))&&!y&&r.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),s.type==="button"){let h=e.actions.find(P=>P.id===s.action);h?.type==="claim_offer"&&y&&y!==h.couponId&&r.push(`\u9886\u53D6\u6309\u94AE ${s.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}s.type==="stack"&&s.children.forEach(h=>a(h,y))}e.pages.forEach(s=>a(s.root));let c=[],l=lr.safeParse(e);l.success||r.push(...l.error.issues.map(s=>s.message));for(let s of Object.values(e.strings.locales))for(let p of Object.values(s))for(let y of ce(p))r.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${y}`);H(e,s=>{if(s.type==="customer_data"&&Object.values(e.strings.locales).some(y=>/\{\{|\}\}/.test(y[s.title]??""))&&r.push(`\u6570\u636E\u7EC4\u4EF6 ${s.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(s.type==="text"?[s.text]:s.type==="button"?[s.label]:[]).some(y=>Object.values(e.strings.locales).some(h=>h[y]?.includes("{{")))&&!s.fallback&&r.push(`\u7EC4\u4EF6 ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),s.fallback&&Object.values(e.strings.locales).some(y=>y[s.fallback]?.includes("{{"))&&r.push(`\u7EC4\u4EF6 ${s.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),s.type==="custom_html"){for(let y of Object.values(s.html))r.push(...ge(y).map(h=>`HTML ${s.id}\uFF1A${h}`));Object.values(s.html).some(y=>y.includes("{{"))&&!s.fallback&&r.push(`HTML ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(s.css)&&r.push(`HTML ${s.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(s.type==="stack"||s.type==="button")&&s.bind?.picker&&he(e,s.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(ae(e),s.bind.picker)&&r.push(`\u5BB9\u5668 ${s.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let s of Object.keys(ae(e)))he(e,s)||r.push(`Product selection scope ${s} must reference a UI node`);let d=nt(e);for(let s of d)s.complete||(s.locale===e.strings.defaultLocale?r.push(`\u9ED8\u8BA4\u8BED\u8A00 ${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):r.push(`${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));xe(e).length===0&&!e.pages.some(s=>pr(s.root))&&r.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let g=new Set;H(e,s=>{s.type==="button"&&g.add(s.action)});for(let s of e.actions)!g.has(s.id)&&!e.pages.some(p=>mr(p.root,s.id))&&c.push(`\u52A8\u4F5C ${s.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:r,warnings:c}}function pr(e){let t=!1;return ee(e,r=>{if(r.hidden)return!1;r.type==="image"&&(t=!0)}),t}function mr(e,t){let r=!1;return ee(e,i=>{if(i.type==="custom_html")for(let a of Object.values(i.html))a.includes(`data-grow-action="${t}"`)&&(r=!0)}),r}function dr(e){return nt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function ni(e,t){return ze(t,dr(e),e.strings.defaultLocale)}function ii(e,t){let r=e.strings.locales[t]??{},i=e.strings.locales[e.strings.defaultLocale]??{},a={};for(let l of xe(e)){if(l.field==="html"||l.field==="src")continue;let d=r[l.key]?.trim()?r[l.key]:i[l.key];d!==void 0&&(a[l.key]=d)}let c=l=>{if(l.type==="stack")return{...l,children:l.children.map(c)};if(l.type==="custom_html"){let d=l.html[t]?.trim()?l.html[t]:l.html[e.strings.defaultLocale];return{...l,html:d===void 0?{}:{[t]:d}}}if(l.type==="image"){let{localizedSrc:d,...g}=l;return{...g,src:d?.[t]??d?.[e.strings.defaultLocale]??l.src}}return l};return{...e,pages:e.pages.map(l=>({...l,root:c(l.root)})),strings:{defaultLocale:t,locales:{[t]:a}}}}function fr(e,t){let r=null;return ee(e,i=>{if(r)return!1;i.id===t&&(r=i)}),r}function he(e,t){for(let r of e.pages){let i=fr(r.root,t);if(i)return i}return null}function oi(e){let t=de(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function ai(e,t,r){let i={};if(!t||typeof t!="object"||Array.isArray(t))return i;let a=t;if(H(e,c=>{if(c.type==="plan_picker"){let d=a[c.id];typeof d=="string"&&(i[c.id]=r?.pickers[c.id]?.options.includes(d)?d:"");return}if(c.type!=="stack"||!c.interaction)return;let l=Object.hasOwn(a,c.id)?a[c.id]:void 0;["select","tabs"].includes(c.interaction.type)&&typeof l=="string"&&c.children.some(d=>d.id===l)&&(i[c.id]=l),c.interaction.type==="toggle"&&typeof l=="boolean"&&(i[c.id]=l)}),e.surface==="paywall"&&typeof a.__page=="string"&&e.pages.some(c=>c.id===a.__page)&&(i.__page=a.__page),r){let c={...i};for(let[l,d]of Object.entries(a))(typeof d=="string"||typeof d=="boolean")&&(c[l]=d);Object.assign(i,He(e,c,r))}return i}import{z as Se}from"zod";var gr="[a-f0-9]{64}",ot="[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",yr="[a-zA-Z][a-zA-Z0-9_.-]{0,63}",br="[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?",Ie=new RegExp(`^/web-view/screens/(${gr})/(?:funnel/(${ot})/(${yr})|paywall/(${ot}))/(${br})$`),at=Se.string().max(256).regex(Ie,"Invalid screen render address"),ui=Se.union([at,Se.string().max(512).regex(new RegExp(`^(?:https://[a-z0-9.-]+(?::[0-9]{1,5})?|http://(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?)${Ie.source.slice(1)}`),"Invalid screen render URL")]);function pi(e){let t=e.kind==="funnel"?`/web-view/screens/${e.tag}/funnel/${e.versionId}/${e.screenId}/${e.locale}`:`/web-view/screens/${e.tag}/paywall/${e.versionId}/${e.locale}`;return at.parse(t)}function mi(e){let t=Ie.exec(e);if(!t)return null;let[,r,i,a,c,l]=t;return!r||!l||!U.safeParse(l).success?null:i&&a?{kind:"funnel",tag:r,versionId:i,screenId:a,locale:l}:c?{kind:"paywall",tag:r,versionId:c,locale:l}:null}var di={funnel:e=>`screen-render:funnel:${e}`,funnelVersion:e=>`screen-render:funnel-version:${e}`,paywall:e=>`screen-render:paywall:${e}`,paywallVersion:e=>`screen-render:paywall-version:${e}`};import{z as _}from"zod";var hi=_.discriminatedUnion("kind",[_.object({kind:_.literal("ledger"),cursor:oe}).strict(),_.object({kind:_.literal("billing"),cursor:_.uuid()}).strict()]),hr=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xr=_.record(_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_.union([_.string().max(500),_.boolean(),_.array(_.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),Sr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function _e(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(r=>_e(r,t+1)):Object.entries(e).some(([r,i])=>["__proto__","constructor","prototype"].includes(r)||Sr.test(r)||_e(i,t+1)))}var Ir=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,_r=_.record(hr,ue).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!_e(e)&&!Ir.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function xi(e){let t=Object.create(null);for(let[r,i]of new URL(e).searchParams)_.string().max(500).parse(i),Object.hasOwn(t,r)||(t[r]=i);return _r.parse(t),t}var st=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ar=_.array(_.object({variable:st,componentId:st,required:_.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),Si=_.object({bindings:Ar,answers:xr,values:_.record(_.string(),ue).optional()}).strict();export{lt as a,k as b,pe as c,Nr as d,Rr as e,kr as f,te as g,A as h,ut as i,V as j,z as k,ke as l,pt as m,mt as n,dt as o,zr as p,U as q,de as r,ze as s,yt as t,Tr as u,re as v,Pr as w,vr as x,bt as y,ht as z,Ce as A,$r as B,xt as C,Ur as D,St as E,Le as F,It as G,Vr as H,Br as I,qr as J,ne as K,Hr as L,_t as M,Q as N,we as O,ie as P,Kr as Q,Gr as R,De as S,Xr as T,Pe as U,D as V,an as W,ve as X,oe as Y,sn as Z,Rt as _,cn as $,$e as aa,pn as ba,mn as ca,dn as da,Ue as ea,Ve as fa,An as ga,Ot as ha,jt as ia,Be as ja,En as ka,Ze as la,Me as ma,Fe as na,ae as oa,He as pa,zt as qa,fe as ra,Ke as sa,Ln as ta,se as ua,ce as va,Tn as wa,wn as xa,Ct as ya,Ge as za,Qe as Aa,Tt as Ba,$n as Ca,Un as Da,Vn as Ea,ge as Fa,Ye as Ga,Zn as Ha,wt as Ia,w as Ja,X as Ka,x as La,Dt as Ma,Pt as Na,be as Oa,Xe as Pa,J as Qa,Je as Ra,vt as Sa,$t as Ta,tt as Ua,Ut as Va,Vt as Wa,Bt as Xa,qt as Ya,Zt as Za,q as _a,Mt as $a,Ft as ab,Ht as bb,Kt as cb,Gt as db,Qt as eb,Wt as fb,Yt as gb,Xt as hb,Jt as ib,er as jb,tr as kb,rt as lb,rr as mb,ir as nb,or as ob,ar as pb,Xn as qb,sr as rb,Jn as sb,H as tb,ei as ub,lr as vb,ee as wb,xe as xb,ur as yb,nt as zb,ti as Ab,ri as Bb,dr as Cb,ni as Db,ii as Eb,fr as Fb,he as Gb,oi as Hb,ai as Ib,Ie as Jb,at as Kb,ui as Lb,pi as Mb,mi as Nb,di as Ob,hi as Pb,xr as Qb,_r as Rb,xi as Sb,Ar as Tb,Si as Ub};
|
package/dist/chunk-S2MSIA57.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
function J(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function j(e,t,n){return n===2?J(J(e+t)+"")%1e4/1e4:null}function be(e){return e<=0?[]:new Array(e).fill(1/e)}function D(e,t){return e>=t[0]&&e<t[1]}function W(e,t){for(let[n,r]of t.entries())if(D(e,r))return n;return-1}function z(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=be(e);n=n||r,n.length!==e&&(n=r);let s=n.reduce((u,c)=>c+u,0);(s<.99||s>1.01)&&(n=r);let i=0,o=t;return n.map(u=>{let c=i;return i+=u,[c,c+o*u]})}function Q(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let i=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return i!==void 0&&i>=0&&i<n?i:null}function X(e){try{return e()}catch{return!1}}function V(e){return typeof e=="string"?e:JSON.stringify(e)}function k(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function ge(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Y(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let s of t){let i=Ze(e,s.type,s.pattern);if(s.include===!1){if(i)return!1}else n=!0,i&&(r=!0)}return r||!n}function Xe(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function Ye(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((s,i)=>{r.push([e.searchParams.get(i)||"",s,!1])}),!r.some(s=>!Xe(s[0],s[1],s[2]))}catch{return!1}}function Ze(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let s=ge(n);return s?s.test(r.href)||s.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Ye(r,n);return!1}catch{return!1}}function Z(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function H(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function xe(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);H(e.savedGroups??{})}var et=e=>e/2**32|0,tt=e=>e>>>0;function ye(e,t,n,r){let s=et(n),i=tt(n);e.setUint32(t,r?i:s,r),e.setUint32(t+4,r?s:i,r)}function me(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ee=e=>e?`"${e}" `:"";function nt(e,t=""){if(typeof e!="number")throw new TypeError(ee(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ee(t)+"expected integer >= 0, got "+e);return e}function G(e,t,n=""){if(me(e)&&(t===void 0||e.length===t))return e;t!==void 0&&nt(t,"length");let r=me(e),s=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,o=ee(n)+"expected Uint8Array"+s+", got "+i;throw r?new RangeError(o):new TypeError(o)}var rt=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},ke=(e,t)=>{rt(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function te(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Se(e,t){G(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function ne(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function I(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function A(e,t){return e<<32-t|e>>>t}var st=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ot=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function we(e){if(G(e),st)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ot[e[n]];return t}function it(e,t,n="opts"){return ke(e,"defaults"),t!==void 0&&ke(t,n),Object.assign(Object.create(null),e,t)}function Ae(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=it({},t,"info");let n=(s,i)=>e(i).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}var ve=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ee(e,t,n){return e&t^~e&n}function Fe(e,t,n){return e&t^e&n^t&n}var P=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,s){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(t),this.view=I(this.buffer)}update(t){te(this),G(t);let{view:n,buffer:r,blockLen:s}=this,i=t.length,o=!1;for(let u=0;u<i;){let c=Math.min(s-this.pos,i-u);if(c===s){let l=I(t);for(;s<=i-u;u+=s)this.process(l,u);o=!0;continue}r.set(u===0&&c===i?t:t.subarray(u,u+c),this.pos),this.pos+=c,u+=c,this.pos===s&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){te(this),Se(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:s,isLE:i}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>s-o&&(this.process(r,0),n.fill(0)),ye(r,s-8,this.length*8,i),this.process(r,0),this.roundClean();let u=t===n?r:I(t),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let f=0;f<l;f++)u.setUint32(4*f,d[f],i)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return t.destroyed=i,t.finished=s,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},$e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var at=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),R=new Uint32Array(64),re=class extends P{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:s,E:i,F:o,G:u,H:c}=this;return[t,n,r,s,i,o,u,c]}set(t,n,r,s,i,o,u,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=u|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let f=0;f<16;f++,n+=4)R[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let b=R[f-15],y=R[f-2],S=A(b,7)^A(b,18)^b>>>3,w=A(y,17)^A(y,19)^y>>>10;R[f]=w+R[f-7]+S+R[f-16]|0}let{A:r,B:s,C:i,D:o,E:u,F:c,G:l,H:d}=this;for(let f=0;f<64;f++){let b=A(u,6)^A(u,11)^A(u,25),y=d+b+Ee(u,c,l)+at[f]+R[f]|0,w=(A(r,2)^A(r,13)^A(r,22))+Fe(r,s,i)|0;d=l,l=c,c=u,u=o+y|0,o=i,i=s,s=r,r=y+w|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,s,i,o,u,c,l,d)}roundClean(){ne(R)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ne(this.buffer)}},se=class extends re{constructor(){super(32,$e)}};var Oe=Ae(()=>new se,ve(1));var Re=new Map,oe=32,Be=new WeakMap,Ce=new WeakMap;function ut(e){return we(Oe(new TextEncoder().encode(String(e))))}var N=e=>Array.isArray(e)?e.map(N):typeof e=="string"||typeof e=="number"?ut(e):null,K=e=>typeof e=="string"?e.toLowerCase():e;function Ue(e){let t=Be.get(e);return t||(t=new Set(e),Be.set(e,t)),t}function ct(e){let t=Ce.get(e);return t||(t=new Set(e.map(K)),Ce.set(e,t)),t}function Le(e){H(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=oe&&Ue(n)}return e}function v(e,t,n,r){n=n||{},r||H(n),r=r||new Set;for(let[s,i]of Object.entries(t))switch(s){case"$or":if(!De(e,i,n,r))return!1;break;case"$nor":if(De(e,i,n,r))return!1;break;case"$and":if(!pt(e,i,n,r))return!1;break;case"$not":if(v(e,i,n,r))return!1;break;case"$savedGroup":if(!ft(e,i,n,r))return!1;break;default:if(!U(i,_e(e,s),n,!1,r))return!1}return!0}function ft(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:s,attributeKey:i}=t;if(typeof s!="string"||r.has(s)||i!==void 0&&typeof i!="string")return!1;let o=n[s];if(!o||Array.isArray(o)||typeof o!="object")return!1;let u=new Set(r).add(s);if(o.type==="list"||o.type==="hashed"){let c=i??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let l=_e(e,c);return T(o.type==="hashed"?N(l):l,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:v(e,o.condition,n,u):!1}function _e(e,t){let n=t.split("."),r=e;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return null;return r}function Ve(e,t=!1){let n=`${e}${t?"/i":""}`,r=Re.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Re.set(n,r)),r}function U(e,t,n,r=!1,s=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!He(e))return JSON.stringify(t)===JSON.stringify(e);let i=e;for(let o in i)if(!ht(o,t,i[o],n,s))return!1;return!0}function He(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function lt(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function dt(e,t,n,r){if(!Array.isArray(e))return!1;let s=He(t)?i=>U(t,i,n,!1,r):i=>v(i,t,n,r);for(let i=0;i<e.length;i++)if((e[i]??null)!==null&&s(e[i]))return!0;return!1}function T(e,t,n=!1){if(n){let s;if(t.length>=oe){let i=ct(t);s=o=>{let u=K(o);return!(typeof u=="number"&&Number.isNaN(u))&&i.has(u)}}else s=i=>t.some(o=>K(i)===K(o));return Array.isArray(e)?e.some(i=>s(i)):s(e)}let r=t.length>=oe?(s=>i=>s.has(i))(Ue(t)):s=>t.includes(s);return Array.isArray(e)?e.some(s=>r(s)):r(e)}function Te(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function je(e,t,n,r=!1,s=new Set){if(!Array.isArray(e))return!1;for(let i=0;i<t.length;i++){let o=!1;for(let u=0;u<e.length;u++)if(U(t[i],e[u],n,r,s)){o=!0;break}if(!o)return!1}return!0}function ht(e,t,n,r,s=new Set){let i=t,o=n;switch(e){case"$veq":return k(t)===k(n);case"$vne":return k(t)!==k(n);case"$vgt":return k(t)>k(n);case"$vgte":return k(t)>=k(n);case"$vlt":return k(t)<k(n);case"$vlte":return k(t)<=k(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return i<o;case"$lte":return i<=o;case"$gt":return i>o;case"$gte":return i>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?T(t,n):!1;case"$ini":return Array.isArray(n)?T(t,n,!0):!1;case"$inGroup":{let u=r[n],c=Te(u);return c===null?!1:T(u?.type==="hashed"?N(t):t,c)}case"$notInGroup":{let u=r[n],c=Te(u);return c===null?!1:!T(u?.type==="hashed"?N(t):t,c)}case"$nin":return Array.isArray(n)?!T(t,n):!1;case"$nini":return Array.isArray(n)?!T(t,n,!0):!1;case"$not":return!U(n,t,r,!1,s);case"$size":return Array.isArray(t)?U(n,t.length,r,!1,s):!1;case"$elemMatch":return dt(t,n,r,s);case"$all":return Array.isArray(n)?je(t,n,r,!1,s):!1;case"$alli":return Array.isArray(n)?je(t,n,r,!0,s):!1;case"$regex":try{return Ve(n).test(t)}catch{return!1}case"$regexi":try{return Ve(n,!0).test(t)}catch{return!1}case"$type":return lt(t)===n;default:return!1}}function De(e,t,n,r){if(!t.length)return!0;for(let s of t)if(v(e,s,n,r))return!0;return!1}function pt(e,t,n,r){for(let s of t)if(!v(e,s,n,r))return!1;return!0}function ie(e){return xe(e),{context:e,stack:{evaluatedFeatures:new Set}}}function ae(e){return{...e.attributes,...e.attributeOverrides}}function $(e,t,n){let r=t||"id",s="",i=ae(e);return i[r]&&(s=i[r]),!s&&n&&(i[n]&&(s=i[n]),s&&(r=n)),{hashAttribute:r,hashValue:s}}function h(e,t,n){e.context.log?.(t,n)}function L(e,t){return t=t||0,`${e}__${t}`}function M(e,t){return`${e}||${t}`}function bt(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:s,hashValue:i}=$(e,t),o=M(s,V(i)),{hashAttribute:u,hashValue:c}=$(e,n),l=c?M(u,V(c)):null,d={};return l&&r[l]&&Object.assign(d,r[l].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function ue({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:s,expMinBucketVersion:i,expMeta:o}){n=n||0,i=i||0,r=r||"id",o=o||[];let u=L(t,n),c=bt(e,r,s);if(i>0)for(let f=0;f<i;f++){let b=L(t,f);if(c[b]!==void 0)return{variation:-1,versionIsBlocked:!0}}let l=c[u];if(l===void 0)return{variation:-1};let d=o.findIndex(f=>f.key===l);return d<0?{variation:-1}:{variation:d}}function ce(e,t,n,r){let s=M(t,n),i=e.stickyBucketAssignmentDocs,o=i&&i[s]?i[s].assignments||{}:{},u={...o,...r},c=JSON.stringify(o)!==JSON.stringify(u);return{key:s,doc:{attributeName:t,attributeValue:n,assignments:u},changed:c}}function gt(e){let t=new Set;return Object.values(e).forEach(n=>{if(n.rules)for(let r of n.rules)r.variations&&(t.add(r.hashAttribute||"id"),r.fallbackAttribute&&t.add(r.fallbackAttribute))}),Array.from(t)}function xt(e,t=e.features||{}){let n={};return gt(t).forEach(r=>{let{hashValue:s}=$(e,r);n[r]=V(s)}),n}function x(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function yt(e){return x({...e,parentConditions:e.parentConditions?.map(t=>x(t)),filters:e.filters?.map(t=>x(t)),meta:e.meta?.map(t=>x(t))})}function Ge(e){return x({...e,parentConditions:e.parentConditions?.map(t=>x(t)),filters:e.filters?.map(t=>x(t)),meta:e.meta?.map(t=>x(t)),tracks:e.tracks?.map(t=>({experiment:yt(t.experiment),result:x(t.result)}))})}function Ie(e,t){let n=ie(t),r=Ne(e,null,n);return t.onExperimentEval?.(e,r),r}function Pe(e,t){return le(e,ie(t))}function mt(e){return e.forcedVariations||{}}function Ke(e,t,n){let{context:r}=e;if(r.trackedExperiments){let s=Je(t,n);if(r.trackedExperiments.has(s))return;r.trackedExperiments.add(s)}fe(()=>r.onExperimentViewed?.(t,n))}function kt(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let s=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===s)return;r.trackedFeatureUsage[t]=s}fe(()=>r.onFeatureUsage?.(t,n))}function fe(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function le(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return h(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),B(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let i of r?.rules??[])Z(i);let s=n.forcedFeatureValues;if(s&&s.has(e))return h(t,"Global override",{id:e,value:s.get(e)}),B(t,e,s.get(e),"override");if(!r)return h(t,"Unknown feature",{id:e}),B(t,e,null,"unknownFeature");if(r.rules){let i=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let l of o.parentConditions){t.stack.evaluatedFeatures=new Set(i);let d=le(l.id,t);if(d.source==="cyclicPrerequisite")return B(t,e,null,"cyclicPrerequisite");let f={value:d.value};if(!v(f,l.condition||{},n.savedGroups||{})){if(l.gate)return h(t,"Feature blocked by prerequisite",{id:e,rule:o}),B(t,e,null,"prerequisite");h(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&qe(o.filters,t)){h(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Me(o.condition,t)){h(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!St(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){h(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return h(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(l=>{Ke(t,l.experiment,l.result)}),B(t,e,o.force,"force",o.id)}if(!o.variations){h(t,"Skip invalid rule",{id:e,rule:o});continue}let u={variations:o.variations,key:o.key||e};"coverage"in o&&(u.coverage=o.coverage),o.weights&&(u.weights=o.weights),o.hashAttribute&&(u.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(u.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(u.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(u.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(u.minBucketVersion=o.minBucketVersion),o.meta&&(u.meta=o.meta),o.ranges&&(u.ranges=o.ranges),o.name&&(u.name=o.name),o.phase&&(u.phase=o.phase),o.seed&&(u.seed=o.seed),o.hashVersion&&(u.hashVersion=o.hashVersion),o.filters&&(u.filters=o.filters),o.condition&&(u.condition=o.condition);let c=Ne(u,e,t);if(n.onExperimentEval?.(u,c),c.inExperiment&&!c.passthrough)return B(t,e,c.value,"experiment",o.id,u,c)}}return h(t,"Use default value",{id:e,value:r.defaultValue}),B(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ne(e,t,n){let{context:r}=n;Z(e);let s=e.key,i=e.variations.length;if(i<2)return h(n,"Invalid experiment",{id:s}),g(n,e,-1,!1,t);if(r.enabled===!1)return h(n,"Context disabled",{id:s}),g(n,e,-1,!1,t);if(e.urlPatterns&&!Y(r.url||"",e.urlPatterns))return h(n,"Skip because of url targeting",{id:s}),g(n,e,-1,!1,t);let o=Q(s,r.url||"",i);if(o!==null)return h(n,"Force via querystring",{id:s,variation:o}),g(n,e,o,!1,t);let c=mt(r)[s];if(c!==void 0)return h(n,"Force via dev tools",{id:s,variation:c}),g(n,e,c,!1,t);if(e.active===!1)return h(n,"Skip because inactive",{id:s}),g(n,e,-1,!1,t);let{hashAttribute:l,hashValue:d}=$(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return h(n,"Skip because missing hashAttribute",{id:s}),g(n,e,-1,!1,t);let f=-1,b=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:m,versionIsBlocked:E}=ue(x({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));b=m>=0,f=m,y=!!E}if(!b){if(e.filters&&qe(e.filters,n))return h(n,"Skip because of filters",{id:s}),g(n,e,-1,!1,t);if(e.include&&!X(e.include))return h(n,"Skip because of include function",{id:s}),g(n,e,-1,!1,t);if(e.condition&&!Me(e.condition,n))return h(n,"Skip because of condition exp",{id:s}),g(n,e,-1,!1,t);if(e.parentConditions){let m=new Set(n.stack.evaluatedFeatures);for(let E of e.parentConditions){n.stack.evaluatedFeatures=new Set(m);let F=le(E.id,n);if(F.source==="cyclicPrerequisite")return g(n,e,-1,!1,t);let C={value:F.value};if(!v(C,E.condition||{},r.savedGroups||{}))return h(n,"Skip because prerequisite evaluation fails",{id:s}),g(n,e,-1,!1,t)}}}let S=j(e.seed||s,d,e.hashVersion??2);if(S===null)return h(n,"Skip because of invalid hash version",{id:s}),g(n,e,-1,!1,t);if(!b){let m=e.ranges||z(i,e.coverage===void 0?1:e.coverage,e.weights);f=W(S,m)}if(y)return h(n,"Skip because sticky bucket version is blocked",{id:s}),g(n,e,-1,!1,t,void 0,!0);if(f<0)return h(n,"Skip because of coverage",{id:s}),g(n,e,-1,!1,t);if("force"in e)return h(n,"Force variation",{id:s,variation:e.force}),g(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return h(n,"Skip because QA mode",{id:s}),g(n,e,-1,!1,t);let w=g(n,e,f,!0,t,S,b);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:m,key:E,doc:F}=ce(r,l,V(d),{[L(e.key,e.bucketVersion)]:w.key});if(m){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[E]=F;let C=r.saveStickyBucketAssignmentDoc;fe(()=>C(F))}}return Ke(n,e,w),h(n,"In experiment",{id:s,variation:w.variationId}),w}function B(e,t,n,r,s,i,o){let u={value:n,on:!!n,off:!n,source:r,ruleId:s||""};return i&&(u.experiment=i),o&&(u.experimentResult=o),r!=="override"&&kt(e,t,u),u}function Me(e,t){return v(ae(t.context),e,t.context.savedGroups||{})}function qe(e,t){return e.some(n=>{let{hashValue:r}=$(t.context,n.attribute);if(!r)return!0;let s=j(n.seed,r,n.hashVersion||2);return s===null?!0:!n.ranges.some(i=>D(s,i))})}function St(e,t,n,r,s,i,o){if(!s&&i===void 0)return!0;if(!s&&i===0)return!1;let{hashValue:u}=$(e.context,n,r);if(!u)return!1;let c=j(t,u,o??2);return c===null?!1:s?D(c,s):i!==void 0?c<=i:!0}function g(e,t,n,r,s,i,o){let u=!0;(n<0||n>=t.variations.length)&&(n=0,u=!1);let{hashAttribute:c,hashValue:l}=$(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},f=t.variations[0];for(let[y,S]of t.variations.entries())if(y===n){f=S;break}let b={key:d.key||""+n,featureId:s,inExperiment:u,hashUsed:r,variationId:n,value:f,hashAttribute:c,hashValue:l,stickyBucketUsed:!!o};return d.name&&(b.name=d.name),i!==void 0&&(b.bucket=i),d.passthrough&&(b.passthrough=d.passthrough),b}function Je(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
-
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
-
|
|
4
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
-
furnished to do so, subject to the following conditions:
|
|
6
|
-
|
|
7
|
-
The above copyright notice and this permission notice shall be included in all
|
|
8
|
-
copies or substantial portions of the Software.
|
|
9
|
-
|
|
10
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
-
SOFTWARE.
|
|
17
|
-
*/import{z as a}from"zod";var _=a.json().superRefine((e,t)=>{let n=0;function r(s,i){if(++n>1e4||i>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof s=="string"&&(s.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(s))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(s))s.forEach(o=>r(o,i+1));else if(s&&typeof s=="object")for(let[o,u]of Object.entries(s))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(u,i+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),he=a.record(a.string().min(1).max(128),_).superRefine((e,t)=>{(!_.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),wt=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),q=he.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[s,i]of Object.entries(r)){if(s==="$savedGroup"&&!a.strictObject({id:a.uuid(),attributeKey:a.string().min(1).max(128).optional()}).safeParse(i).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!s.startsWith("$")&&s.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),s.startsWith("$")&&!wt.has(s)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${s}`}),["$regex","$regexi"].includes(s)&&typeof i=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(i)||[...i.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||s==="$regexi"&&/[^\x00-\x7f]/.test(i.replace(/\\u([0-9a-f]{4})/gi,(o,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(i)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(i)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),At=a.discriminatedUnion("type",[a.strictObject({type:a.literal("condition"),condition:q}),a.strictObject({type:a.literal("list"),attributeKey:a.string().min(1).max(128),values:a.array(a.union([a.string(),a.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function vt(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[s,i]of Object.entries(r))s==="$savedGroup"&&i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.id=="string"?t.add(i.id):["$inGroup","$notInGroup"].includes(s)&&typeof i=="string"?t.add(i):["$eq","$ne","$in","$nin","$ini","$nini"].includes(s)||n(i)}return n(e),[...t]}var Et=a.record(a.uuid(),At).superRefine((e,t)=>{let n=new Set,r=new Set;function s(i){if(n.has(i)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(i))return;let o=e[i];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(i),o.type==="condition"&&vt(o.condition).forEach(s),n.delete(i),r.add(i)}Object.keys(e).forEach(s)}),pe=a.tuple([a.number().min(0).max(1),a.number().min(0).max(1)]).refine(([e,t])=>e<=t),We=a.strictObject({attribute:a.string().optional(),seed:a.string().min(1),hashVersion:a.literal(2),ranges:a.array(pe).min(1).max(100)}),Ft=a.strictObject({id:a.string().min(1).max(128),condition:q,gate:a.boolean().optional()}),de={id:a.string().max(128).optional(),condition:q.optional(),parentConditions:a.array(Ft).max(50).optional(),filters:a.array(We).max(20).optional()},$t=a.union([a.strictObject({...de}),a.strictObject({...de,force:_,coverage:a.number().min(0).max(1).optional(),range:pe.optional(),seed:a.string().min(1).optional(),hashAttribute:a.string().optional(),hashVersion:a.literal(2).optional()}),a.strictObject({...de,type:a.literal("experiment-ref"),experimentId:a.uuid(),values:a.record(a.string().min(1),_),meta:a.record(a.string().min(1),a.strictObject({passthrough:a.boolean()})).optional()})]),Ot=a.strictObject({defaultValue:_,rules:a.array($t).max(100)}),vn=a.record(a.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ot).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function s(i){if(n.has(i)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${i}`});return}if(r.has(i))return;let o=e[i];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${i}`});return}n.add(i);for(let u of o.rules)for(let c of u.parentConditions??[])s(c.id);n.delete(i),r.add(i)}Object.keys(e).forEach(s)}),Rt=a.strictObject({name:a.string().max(80),reason:a.string().max(500),dateStarted:a.iso.datetime({offset:!0}),dateEnded:a.iso.datetime({offset:!0}).nullable(),coverage:a.number().min(0).max(1),variationWeights:a.array(a.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:q,savedGroups:a.array(a.strictObject({match:a.enum(["any","all","none"]),ids:a.array(a.uuid()).min(1)})).max(50),namespace:a.strictObject({id:a.uuid(),ranges:a.array(pe).min(1)}).nullable(),seed:a.string().min(1).max(128)}),Bt=a.strictObject({key:a.string().min(1).max(128),name:a.string().min(1).max(80),hypothesis:a.string().max(2e3),status:a.enum(["draft","running","stopped"]),hashAttribute:a.string().min(1).max(128),fallbackAttribute:a.string().max(128).nullable(),hashVersion:a.literal(2),disableStickyBucketing:a.boolean(),bucketVersion:a.number().int().min(0).max(1e3),minBucketVersion:a.number().int().min(0).max(1e3),variations:a.array(a.strictObject({id:a.string().min(1),key:a.string().min(1),name:a.string().max(80),description:a.string().max(500)})).min(2).max(20),phases:a.array(Rt).min(1).max(100),releasedVariationId:a.string().nullable(),excludeFromPayload:a.boolean(),statusSchedule:a.strictObject({startAt:a.iso.datetime({offset:!0}).nullable(),stopAt:a.iso.datetime({offset:!0}).nullable(),stopAfter:a.strictObject({value:a.number().int().positive().max(36500),unit:a.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let s=e.phases[r-1];return!s?.dateEnded||Date.parse(n.dateStarted)<Date.parse(s.dateStarted)||Date.parse(s.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,s],i,o)=>r>=s||o.some(([u,c],l)=>l!==i&&r<c&&u<s)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function En(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,{defaultValue:s.defaultValue,rules:s.rules.flatMap(i=>{if(!("experimentId"in i))return[Ge({...i,hashVersion:2})];let o=t[i.experimentId];if(!o)throw new Error(`Missing experiment: ${i.experimentId}`);let u=o.phases.at(-1);if(!u)throw new Error("Experiment requires an active phase");let c=o.statusSchedule?.startAt?Date.parse(o.statusSchedule.startAt):null,l=ze(o),d=o.status!=="stopped"&&(o.status==="running"||c!==null&&n>=c)&&(c===null||n>=c)&&(l===null||n<l),{type:f,experimentId:b,values:y,meta:S,...w}=i,m=x({...w,parentConditions:w.parentConditions?.map(p=>x(p)),filters:w.filters?.map(p=>x(p))});if(o.variations.some(p=>!Object.hasOwn(y,p.key))||Object.keys(y).length!==o.variations.length||Object.keys(S??{}).some(p=>!o.variations.some(O=>O.key===p)))throw new Error("Every variation needs a Feature value");let E=p=>{let O=y[p];if(O===void 0)throw new Error("Every variation needs a Feature value");return O},F={$and:[u.condition,...m.condition?[m.condition]:[],...u.savedGroups.map(p=>{let O=p.ids.map(Qe=>({$savedGroup:{id:Qe}}));return p.match==="all"?{$and:O}:p.match==="none"?{$nor:O}:{$or:O}})]},C=o.variations.find(p=>p.id===o.releasedVariationId);return C&&!o.excludeFromPayload?S?.[C.key]?.passthrough?[{...m,condition:F}]:[{...m,condition:F,force:E(C.key)}]:[{...m,condition:F,key:o.key,variations:o.variations.map(p=>E(p.key)),meta:o.variations.map(p=>({key:p.key,name:p.name,...x(S?.[p.key]??{})})),weights:u.variationWeights,coverage:d?u.coverage:0,seed:u.seed,hashVersion:2,hashAttribute:o.hashAttribute,...o.fallbackAttribute===null?{}:{fallbackAttribute:o.fallbackAttribute},disableStickyBucketing:!d||o.disableStickyBucketing,bucketVersion:o.bucketVersion,minBucketVersion:o.minBucketVersion,filters:[...m.filters??[],...(o.filters??[]).map(p=>x(p))]}]})}]))}function ze(e){if(e.statusSchedule?.stopAt)return Date.parse(e.statusSchedule.stopAt);let t=e.statusSchedule?.stopAfter;if(!t||e.status==="draft"&&!e.statusSchedule?.startAt)return null;let n=e.statusSchedule?.startAt??e.phases.at(-1)?.dateStarted;if(!n)throw new Error("Experiment requires an active phase");return Date.parse(n)+t.value*(t.unit==="days"?864e5:36e5)}function Fn(e,t=Date.now()){let n=Object.values(e).filter(r=>r.status!=="stopped"&&!(r.releasedVariationId&&!r.excludeFromPayload)).flatMap(r=>[r.statusSchedule?.startAt?Date.parse(r.statusSchedule.startAt):null,ze(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var Ct=Bt.safeExtend({filters:a.array(We).optional()}),Vt=a.strictObject({experiments:a.record(a.uuid(),Ct),savedGroups:Et}),Tt=a.strictObject({attributeName:a.string(),attributeValue:a.string(),assignments:a.record(a.string(),a.string())}),$n=a.strictObject({snapshot:Vt,attributes:he,results:he,stickyBucketAssignmentDocs:a.record(a.string(),Tt)}),On=a.strictObject({variantKey:a.string().nullable(),bucketVersion:a.number().int().min(0),source:a.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:a.number().min(0).max(1).optional(),stickyBucketUsed:a.boolean().optional(),hashUsed:a.boolean().optional()});export{Q as a,V as b,Y as c,we as d,Oe as e,Le as f,v as g,xt as h,Ie as i,Pe as j,Je as k,_ as l,he as m,q as n,At as o,vt as p,Et as q,$t as r,Ot as s,vn as t,Rt as u,Bt as v,En as w,ze as x,Fn as y,Ct as z,Vt as A,Tt as B,$n as C,On as D};
|
package/dist/chunk-VVSQKVE7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as k,b as L,c as O}from"./chunk-4K25DELJ.js";function N(r){let e=r.document,o=/^zh\b/i.test(e.documentElement.lang),t=e.createElement("div"),v=t.attachShadow({mode:"open"}),h=e.createElement("style");t.setAttribute("data-indiana-private",""),t.setAttribute("data-indiana-capture-controls",""),t.setAttribute("aria-live","off");let b=typeof t.showPopover=="function";b&&t.setAttribute("popover","manual"),t.hidden=!0,r.nonce&&(h.nonce=r.nonce),h.textContent=":host{all:initial!important;position:fixed!important;margin:0!important;inset:auto!important;right:12px!important;bottom:12px!important;z-index:2147483647!important;display:block!important;width:340px!important;max-width:calc(100vw - 24px)!important;color:#17202d!important;font:13px/1.4 system-ui,sans-serif!important;color-scheme:light!important}:host([hidden]){display:none!important}*{box-sizing:border-box}.panel{background:white;border:1px solid #98a4b4;border-radius:2px;padding:12px;box-shadow:0 2px 10px #17202d20}.top,.actions{display:flex;align-items:center;gap:8px}.top{justify-content:space-between}strong{font-weight:600}small{font-size:12px;font-variant-numeric:tabular-nums}.message{margin:6px 0;color:#465467;overflow-wrap:anywhere}.actions{justify-content:flex-end}button{font:inherit;min-height:40px;border:1px solid #98a4b4;border-radius:2px;padding:6px 12px;background:white;color:#17202d;cursor:pointer}button:focus-visible{outline:2px solid #155eef;outline-offset:2px}button:disabled{cursor:default;color:#5b6778;background:#f2f4f7}button.primary:enabled{background:#155eef;border-color:#155eef;color:white}@media(forced-colors:active){.panel,button{border:1px solid CanvasText}button:focus-visible{outline:2px solid Highlight}}";let l=e.createElement("section"),u=e.createElement("div"),f=e.createElement("strong"),I=e.createElement("small"),g=e.createElement("p"),R=e.createElement("div"),d=e.createElement("button"),A=e.createElement("button");if(l.className="panel",u.className="top",R.className="actions",l.setAttribute("aria-label",o?"Indiana \u9875\u9762\u91C7\u96C6":"Indiana page capture"),l.setAttribute("role","region"),f.textContent=o?"Indiana \u9875\u9762\u91C7\u96C6":"Indiana page capture",g.className="message",g.setAttribute("role","status"),d.type=A.type="button",d.className="primary",d.textContent=o?"\u91CD\u8BD5\u91C7\u96C6":"Retry capture",u.append(f,I),R.append(d,A),l.append(u,g,R),v.append(h,l),(e.body??e.documentElement).append(t),!h.sheet)throw t.remove(),Object.assign(Error("Authoring controls blocked by style policy"),{code:"AUTHORING_CONTROLS_BLOCKED"});t.hidden=!1;let a={state:"connecting",snapshots:0},E=!1,w,p;function y(c=e.activeElement){if(E||c===t||c&&t.contains(c))return;let i,m=c;for(let S=0;m&&S<80;S++,m=m.parentElement)if(m.matches('dialog[open],[role="dialog"],[role="alertdialog"],[role="menu"],[role="listbox"]')&&m.getAttribute("aria-hidden")!=="true"){i=m;break}w=i;let x=i??e.body??e.documentElement;if(t.parentElement!==x&&x.append(t),t.removeAttribute("aria-hidden"),b)try{t.showPopover()}catch{}}let C=c=>{c.target instanceof e.defaultView.Element&&y(c.target)},_=c=>{c.target===w&&y(e.body)};e.addEventListener("focusin",C,!0),e.addEventListener("close",_,!0);let n={connecting:["\u6B63\u5728\u8FDE\u63A5\u91C7\u96C6\u670D\u52A1\u2026","Connecting to capture service\u2026"],authorized:["\u91C7\u96C6\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u52A0\u8F7D\u2026","Capture authorized; loading\u2026"],idle:["\u9875\u9762\u7A33\u5B9A\u540E\u81EA\u52A8\u91C7\u96C6\uFF0C\u8F93\u5165\u6587\u672C\u4F1A\u906E\u853D\u3002","Stable page states are captured automatically. Input text is masked."],capturing:["\u6B63\u5728\u91C7\u96C6\u9875\u9762\u7ED3\u6784\u2026","Capturing page structure\u2026"],uploading:["\u6B63\u5728\u4FDD\u5B58\u8131\u654F\u5FEB\u7167\u2026","Saving a masked snapshot\u2026"],waiting:["\u4E0A\u4F20\u5904\u7406\u4E2D\uFF0C\u540E\u7EED\u53D8\u5316\u5DF2\u5408\u5E76\u7B49\u5F85\u3002","Upload in progress; later changes are coalesced."],paused:["\u91C7\u96C6\u5DF2\u6682\u505C\u3002\u68C0\u67E5\u9875\u9762\u6216\u8FDE\u63A5\u540E\uFF0C\u53EF\u624B\u52A8\u91CD\u8BD5\u3002","Capture paused. Check the page or connection, then retry."],stopped:["\u91C7\u96C6\u5DF2\u505C\u6B62\u3002\u5237\u65B0\u9875\u9762\u540E\u6062\u590D\u666E\u901A\u8BBF\u95EE\u3002","Capture stopped. Reload the page to resume ordinary delivery."]};function s(){if(E)return;if(t.isConnected||w&&!w.isConnected&&y(),!t.isConnected){E=!0,clearInterval(p),e.removeEventListener("focusin",C,!0),e.removeEventListener("close",_,!0),r.stop();return}let c=Number.isInteger(a.snapshots)?Math.min(10,Math.max(0,a.snapshots)):0,i=a.expiresAt&&Number.isFinite(a.expiresAt)?Math.max(0,Math.ceil((a.expiresAt-Date.now())/1e3)):null;I.textContent=(o?`\u5DF2\u4FDD\u5B58 ${c} \u4EFD`:`${c} saved`)+(i===null?"":` \xB7 ${Math.floor(i/60)}:${String(i%60).padStart(2,"0")}`);let m=n[a.state]??n.paused;a.state==="paused"&&/(?:429|QUOTA)/.test(a.reason??"")&&(m=["\u5DF2\u8FBE\u5230\u91C7\u96C6\u914D\u989D\uFF0C\u8BF7\u8FD4\u56DE\u63A7\u5236\u53F0\u67E5\u770B\u3002","Capture quota reached. Check the Console before retrying."]),a.state==="paused"&&a.reason==="OFFLINE"&&(m=["\u7F51\u7EDC\u5DF2\u65AD\u5F00\u3002\u6062\u590D\u8FDE\u63A5\u540E\uFF0C\u8BF7\u624B\u52A8\u91CD\u8BD5\u3002","You are offline. Reconnect, then retry explicitly."]),a.state==="paused"&&/(?:SLICE|ENCODING|NODE|BYTE|TEXT|ATTRIBUTE|CSS|DEADLINE)/.test(a.reason??"")&&(m=["\u9875\u9762\u8D85\u51FA\u91C7\u96C6\u9884\u7B97\u3002\u7F29\u5C0F\u9875\u9762\u72B6\u6001\u540E\u518D\u8BD5\u3002","This page exceeds the capture budget. Reduce the page state before retrying."]),a.state==="stopped"&&a.reason==="QUOTA"&&(m=["\u672C\u6B21\u6388\u6743\u6B21\u6570\u5DF2\u7528\u5B8C\u3002\u8BF7\u8FD4\u56DE\u63A7\u5236\u53F0\u91CD\u65B0\u6388\u6743\u3002","This grant is exhausted. Request another grant from the Console."]),a.state==="stopped"&&/EXPIRED|REVOKED/.test(a.reason??"")&&(m=["\u91C7\u96C6\u6388\u6743\u5DF2\u5931\u6548\u3002\u8BF7\u8FD4\u56DE\u63A7\u5236\u53F0\u91CD\u65B0\u6388\u6743\u3002","Capture authority has expired or changed. Return to the Console."]),a.state==="stopped"&&a.reason==="CAPTURE_UPGRADE_REQUIRED"&&(m=["\u91C7\u96C6\u7248\u672C\u4E0D\u5339\u914D\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u6216\u66F4\u65B0 SDK \u540E\u91CD\u65B0\u6388\u6743\u3002","Capture versions differ. Reload or update the SDK, then request another grant."]),g.textContent!==m[o?0:1]&&(g.textContent=m[o?0:1]),d.disabled=a.state!=="paused"||i===0,A.textContent=a.state==="stopped"?o?"\u5173\u95ED":"Close":o?"\u505C\u6B62\u91C7\u96C6":"Stop capture"}for(let c of["click","pointerdown","pointerup","keydown","keyup"])v.addEventListener(c,i=>i.stopPropagation());return d.onclick=()=>{d.disabled||r.retry()},A.onclick=()=>{a.state==="stopped"?r.close():r.stop()},y(),s(),{update(c){E||(a=c,p&&clearInterval(p),p=void 0,a.state!=="stopped"&&a.expiresAt&&Number.isFinite(a.expiresAt)&&(p=setInterval(s,1e3)),s())},destroy(){E||(E=!0,clearInterval(p),e.removeEventListener("focusin",C,!0),e.removeEventListener("close",_,!0),t.remove())},get active(){return!E&&t.isConnected}}}function U(r){let e=r.document??document,o=e.defaultView;if(!o)return{destroy(){},checkpoint(n){},retry(){}};let t="indiana:iam:authoring:v2:"+new URL(r.baseUrl).origin+":"+r.environmentId;function v(n){if(n.length>12e3||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n))return!1;try{let s=JSON.parse(o.atob(n.split(".")[0].replaceAll("-","+").replaceAll("_","/")));return k(o.location.origin)&&typeof s=="object"&&s!==null&&"version"in s&&"environmentId"in s&&"origin"in s&&s.version===2&&s.environmentId===r.environmentId&&s.origin===o.location.origin}catch{return!1}}let h=!1,b=!1,l=0,u=!1,f="",I,g,R=0,d,A=()=>{try{o.sessionStorage.removeItem(t)}catch{}},a=n=>{if(b!==n){b=n;try{r.onAuthoringChange?.(n)}catch{}}},E=n=>{R=n.snapshots,g?.update(n);try{r.onStatus?.(n)}catch{}e.dispatchEvent(new o.CustomEvent("indiana:iam:status",{detail:n}))};function w(){h||(l++,I?.abort(),d?.destroy("USER_STOPPED"),d=void 0,u=!1,A(),f="",a(!1),e.removeEventListener("indiana:iam:checkpoint",p),E({state:"stopped",reason:"USER_STOPPED",snapshots:R}))}let p=n=>{let s=n instanceof o.CustomEvent?n.detail:void 0,c=s&&typeof s=="object"&&"label"in s?s.label:void 0;if(typeof c=="string"&&/^[\p{L}\p{N} _.-]{1,64}$/u.test(c))try{d?d.checkpoint(c):f&&!u&&C(f)}catch{}};function y(){let n=new URLSearchParams(o.location.hash.slice(1)),s=n.get("indiana-capture");if(!s)return null;v(s)&&a(!0),n.delete("indiana-capture");let c=new URL(o.location.href);return c.hash=n.toString(),o.history.replaceState(o.history.state,"",c),/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(s)&&s.length<=12e3?s:null}function C(n){if(h||!v(n))return;let s=++l;I?.abort(),I=new AbortController;let c=I.signal;d?.destroy("REPLACED"),d=void 0,f=n,u=!0,a(!0),e.addEventListener("indiana:iam:checkpoint",p);try{o.sessionStorage.setItem(t,n)}catch{}(async()=>{if(r.controls!==!1&&!g?.active&&(g?.destroy(),g=N({document:e,nonce:r.nonce,retry(){d?d.retry():f&&!u&&C(f)},stop:w,close(){g?.destroy(),g=void 0}})),g?.update({state:"connecting",snapshots:0}),!o.navigator.onLine)throw Object.assign(Error("Capture offline"),{code:"OFFLINE"});if(await r.prepare?.(),h||s!==l)return;let i=await fetch(new URL("/api/app-manifest-captures",r.baseUrl),{method:"POST",credentials:"omit",redirect:"error",cache:"no-store",headers:{Authorization:"Bearer "+n,[L]:O,"Content-Type":"application/json"},body:JSON.stringify({action:"authorize"}),signal:AbortSignal.any([c,AbortSignal.timeout(3e4)])});if(i.status!==204||i.headers.get(L)!==O)throw i.body?.cancel().catch(()=>{}),Object.assign(new Error("Capture authorization refused"),{code:i.ok?i.status===204?"CAPTURE_VERSION_MISMATCH":"SERVICE_RESPONSE_INVALID":"AUTH_OR_SERVICE_"+i.status});if(h||s!==l)return;E({state:"authorized",snapshots:0});let{startCapture:m}=await import("./client-OYRHOMUQ.js");if(h||s!==l)return;let x=await m({environmentId:r.environmentId,grant:n,baseUrl:r.baseUrl,document:e,signal:c,onStatus(S){h||s!==l||(S.state==="stopped"&&(A(),f="",a(!1),e.removeEventListener("indiana:iam:checkpoint",p)),E(S))}});if(h||s!==l){x.destroy("REPLACED");return}d=x,e.addEventListener("indiana:iam:checkpoint",p)})().catch(i=>{if(!h&&s===l){let m=i instanceof Error&&["TypeError","TimeoutError"].includes(i.name)||i&&typeof i=="object"&&"code"in i&&/^(?:AUTH_OR_SERVICE_(?:408|429|5\d\d)|SERVICE_RESPONSE_INVALID|OFFLINE)$/.test(String(i.code));m||(A(),f="",a(!1),e.removeEventListener("indiana:iam:checkpoint",p));let x=i&&typeof i=="object"&&"code"in i?String(i.code):"",S={state:m?"paused":"stopped",reason:["CAPTURE_VERSION_MISMATCH","AUTH_OR_SERVICE_426"].includes(x)?"CAPTURE_UPGRADE_REQUIRED":x==="OFFLINE"?"OFFLINE":i&&typeof i=="object"&&"code"in i&&i.code==="AUTHORING_CONTROLS_BLOCKED"?"AUTHORING_CONTROLS_BLOCKED":m?"SERVICE_UNAVAILABLE":"AUTH_OR_SERVICE_UNAVAILABLE",snapshots:0};E(S)}}).finally(()=>{s===l&&(u=!1)})}let _=()=>{let n=y();n&&C(n)};o.addEventListener("hashchange",_);try{let n=y()??o.sessionStorage.getItem(t);n&&C(n)}catch{}return{destroy(){h=!0,l++,I?.abort(),d?.destroy(),g?.destroy(),g=void 0,o.removeEventListener("hashchange",_),e.removeEventListener("indiana:iam:checkpoint",p),A(),f="",a(!1)},checkpoint(n){d?d.checkpoint(n):f&&!u&&C(f)},retry(){d?d.retry():f&&!u&&C(f)}}}async function D(r,e,o){let t=new URL(r,e.baseURI),v=e.defaultView?.location.origin,h=/^\/\.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(t.pathname)?.[1];if(!h||t.origin!==v||t.search||t.hash||t.username||t.password)throw Error("Invalid IAM release URL");let b=AbortSignal.any([o,AbortSignal.timeout(2e3)]),l=await fetch(t,{credentials:"omit",redirect:"error",cache:"force-cache",signal:b}),u=l.headers.get("content-length");if(!l.ok||!/^application\/json(?:;|$)/i.test(l.headers.get("content-type")??"")||u!==null&&(!/^\d+$/.test(u)||Number(u)>512))throw l.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let f=l.body?.getReader();if(!f)throw Error("IAM release is unavailable");let I=[],g=0,R=()=>{},d=new Promise((y,C)=>{R=()=>C(Error("IAM release timeout")),b.addEventListener("abort",R,{once:!0}),b.aborted&&R()}),A=!1;try{for(;;){let y=await Promise.race([f.read(),d]);if(y.done){A=!0;break}if(g+=y.value.length,g>512)throw Error("IAM release budget");I.push(y.value)}}finally{b.removeEventListener("abort",R),A||f.cancel().catch(()=>{}),f.releaseLock()}let a=new Uint8Array(g),E=0;for(let y of I)a.set(y,E),E+=y.length;let w=new TextDecoder("utf-8",{fatal:!0}).decode(a),p=JSON.parse(w);if(w.trim()!==JSON.stringify(p))throw Error("Noncanonical IAM release descriptor");if(!p||typeof p!="object"||Array.isArray(p)||Object.keys(p).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(p,"format")!=="indiana-app-manifest-release"||Reflect.get(p,"schemaVersion")!==2||Reflect.get(p,"releaseId")!==h||!/^[a-f0-9]{64}$/.test(String(Reflect.get(p,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(p,"manifestDigest")}var T=new WeakMap;function F(r,e=document){if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Invalid IAM manifest digest");let o=T.get(e);o||(o=new Map,T.set(e,o));let t="data-indiana-release",v=e.documentElement,h=()=>new Set((v.getAttribute(t)??"").split(/\s+/).filter(Boolean)),b=o.get(r);if(!b){let u=h();b={count:0,owned:!u.has(r)},o.set(r,b),u.add(r),v.setAttribute(t,[...u].join(" "))}b.count++;let l=!1;return{attributes:{indianaAppManifestRelease:r},destroy(){if(!l&&(l=!0,b.count--,!b.count&&(o.delete(r),b.owned))){let u=h();u.delete(r),u.size?v.setAttribute(t,[...u].join(" ")):v.removeAttribute(t)}}}}async function $(r){return(await import("./client-OYRHOMUQ.js")).startCapture(r)}export{U as a,D as b,F as c,$ as d};
|
package/dist/chunk-YAMBRNJ2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as we}from"./chunk-FVUPV6YE.js";import{$k as Ke,Bf as Ue,Ei as Ee,Ek as H,Fi as ke,Fk as je,Gd as Le,Jk as Pe,Kk as M,Lk as Je,Mk as Be,Nk as ze,Oi as Se,Ok as He,Pi as qe,Rh as be,Vf as ce,al as $e,bl as Qe,cl as Ye,hk as Ge,ui as te,xf as Ve,yf as Me}from"./chunk-FF3LWJ26.js";import{a as d}from"./chunk-5TEZEOHX.js";import{a as Ae}from"./chunk-S5TVMQRC.js";import{b as _e,h as ge}from"./chunk-ISUXYPYL.js";import{f as De,j as xe,m as Ne}from"./chunk-S2MSIA57.js";function yn(e){let n=null,i=null,t=0,m=0,y=new Set,o=null,u=null,r=new Set,s=()=>{for(let I of r)try{I()}catch{}},g={attributes:Ne.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(I,P)=>{!y.has(I)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(I,structuredClone(P))}:void 0,onExperimentViewed:e.onExperimentViewed?(I,P)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(I),structuredClone(P)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?I=>e.saveStickyBucketAssignmentDoc(structuredClone(I)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function v(I,P=new Set){return y.has(I)?!o||!o.features[I]||["unknownFeature","cyclicPrerequisite"].includes(o.features[I].source):P.has(I)?!1:(P.add(I),(n?.features[I]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(D=>D.experiment.parentConditions??[])].some(D=>v(D.id,P))))}let A=I=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,g.features=n.features),y.has(I)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?w():structuredClone(o.features[I]??w()):v(I)?w():structuredClone(xe(I,g))};async function E(){if(!n||!y.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let I=m;if(u?.revision===I)return u.loading;let P=t,F=n,D=[...y],T=(async()=>{let _=Ue.parse(await e.evaluateRemote({attributes:structuredClone(g.attributes),features:D}));if(!(P!==t||I!==m||F!==n)){if(e.assertUsable?.(F.generation),_.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(D.some(U=>!Object.hasOwn(_.features,U))||Object.keys(_.features).some(U=>!y.has(U)))throw new Error("Invalid remote Feature results");o=structuredClone(_),g.features={...F.features,...Object.fromEntries(Object.entries(o.features).map(([U,j])=>[U,{defaultValue:j.value}]))},s()}})();u={revision:I,loading:T};try{await T}finally{u?.loading===T&&(u=null)}}function S(){E().catch(I=>{try{e.onError?.(I)}catch{}})}async function V(){if(i)return i;let I=t,P=(async()=>{let F=await e.load(),D="remoteFeatures"in F?Ve.parse(F):null,T=D??ge.parse(F);if(T.scope.projectId!==e.scope.projectId||T.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(I!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===T.generation){let{evaluatedAt:U,expiresAt:j,...oe}=n,{evaluatedAt:X,expiresAt:ee,...l}=T;if(M(oe)!==M(l))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=T.evaluatedAt,n.expiresAt=T.expiresAt,s(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&S(),structuredClone(n)}let _=new Set(D?.remoteFeatures??[]);if([..._].some(U=>Object.hasOwn(T.features,U)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in T&&!n.analyticsConfig.experimentViewsEnabled&&D?.analyticsConfig.experimentViewsEnabled&&g.trackedExperiments?.clear(),n=structuredClone(T),y=_,o=null,u=null,m++,g.features=n.features,g.savedGroups=De(n.savedGroups),g.trackedFeatureUsage={},s(),S(),structuredClone(n)})();i=P;try{return await P}finally{i===P&&(i=null)}}return{init:V,refresh:V,refreshRemote:E,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(I){return r.add(I),()=>{r.delete(I)}},setAttributes(I){g.attributes=Ne.parse(I),m++,o=null,u=null,g.features=n?.features??{},g.trackedFeatureUsage={},s(),S()},evalFeature:A,isOn(I){return A(I).on},isOff(I){return A(I).off},getFeatureValue(I,P){let F=A(I).value;return structuredClone(F===null?P:F)},reset(){t++,m++,i=null,u=null,n=null,o=null,y.clear(),g.features={},g.savedGroups={},g.stickyBucketAssignmentDocs={},g.attributes={},g.trackedFeatureUsage={},g.trackedExperiments?.clear(),s()}}}function Ze(e){let n,i,t=()=>new d("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),m=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw t();let u=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Ae).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",u));return"indiana.funnel.commands.v1."+Array.from(r,s=>s.toString(16).padStart(2,"0")).join("")});m.catch(()=>{});async function y(u){try{let r=await m;return await i.request(r,{mode:"exclusive"},()=>u(r))}catch(r){throw r instanceof d?r:t()}}function o(u){let r=n.getItem(u);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let s=JSON.parse(r);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw t();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>y(o),write:(u,r)=>y(s=>{if(o(s).revision!==u)return null;if(!Number.isSafeInteger(u+1))throw t();return n.setItem(s,JSON.stringify({revision:u+1,entry:r})),u+1})}}function Rn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ye(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((m,y)=>ye(m,n[y]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),t=Object.entries(n);return i.length===t.length&&i.every(([m,y])=>Object.hasOwn(n,m)&&ye(y,Reflect.get(n,m)))}var de=(e,n)=>new d(e,n);function Fn(e){return Ke(e,de)}function ln(e,n,i){return Qe(e,n,i,de)}async function We(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new d("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new d("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:m,remoteFeatures:y,...o}=t.growth,u=Se({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:ge.parse(o)});if(e.scope.environmentId!==i.environmentId)throw new d("SCOPE_MISMATCH","Evaluation environment changed");let r=ln(u,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:t.manifest.generation,result:r}}async function Xe(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new d("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new d("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new d("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:m,remoteFeatures:y,...o}=t.growth,u=Se({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:ge.parse(o)}),r=cn(u,t.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...r,generation:t.manifest.generation,policyRevision:i.policyRevision}}function cn(e,n,i){return Ye(e,n,i,de)}import{z as Q}from"zod";var en=te.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),nn=Q.strictObject({schemaVersion:Q.literal(1),scope:_e,runId:Q.uuid(),funnelId:Q.uuid(),versionId:Q.uuid(),command:en.optional(),closeCommand:en.refine(e=>e.operation==="close").optional(),purchase:Q.strictObject({receiptId:Q.uuid(),operationId:Q.uuid(),generation:Q.number().int().nonnegative()}).optional(),closed:Q.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),J=()=>new d("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function tn(e){let n=0,i=null,t=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),m=Promise.resolve();async function y(){let r=await e.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new d("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:nn.parse(r.entry)}}function o(r){let s=m.then(r);return m=s.catch(()=>{}),s}async function u(r){for(let s=0;s<4;s++){let g=await y();if(g.entry&&i!==null&&t(g.entry)!==i)throw J();let w=r(g.entry,g.revision);if(Fe(g.entry,w)){n=g.revision;return}let v=await e.write(g.revision,w);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw J();n=v;return}}throw J()}return{bind(r){let s=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(i!==null&&i!==s)throw J();i=s},async load(){let r=await y();return n=r.revision,i=r.entry?t(r.entry):null,r.entry},retain(r){let s=nn.parse(r),g=s.command;return!g||i!==null&&t(s)!==i?Promise.reject(J()):(i??=t(s),o(()=>u((w,v)=>{if(w&&!Fe(t(w),t(s)))throw J();if(!w){if(v!==n&&g.operation!=="close")throw J();return s}if(!w.command)return{...w,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===g.requestId||w.closeCommand&&!Fe(w.closeCommand,g))throw J();return{...w,closeCommand:g,closed:!0}}if(!Fe(w.command,g))throw J();return w})))},observePurchase(r,s,g){return o(()=>u((w,v)=>{if(!w&&v!==n||w&&t(w)!==t({...r,schemaVersion:1}))throw J();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw J();return g?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...r,...w,purchase:s}}))},settle(r){return o(()=>u(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===r?s.closeCommand?{...s,command:s.closeCommand,closeCommand:void 0}:s.purchase?{...s,command:void 0}:null:s.closeCommand&&"requestId"in s.closeCommand&&s.closeCommand.requestId===r?{...s,closeCommand:void 0}:s:null))}}}function fe(e){let{customerToken:n,...i}=e;return i}var dn=e=>!(e instanceof d)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new d("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new d("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=we({...e,...e.serverKey?{fetch:(l,c)=>{let N=new Headers(c?.headers);return N.set(ke,e.serverKey),(e.fetch??globalThis.fetch)(l,{...c,headers:N})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,t=null,m=0,y=0,o=null,u=null,r=!1,s=null,g=!1,w=null,v=new Set,A=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Ze(e):void 0),E=A&&tn(A),S,V=null,I=!1,P=E?E.load().then(l=>{if(I)throw new d("IDENTITY_CHANGED","Controller was reset during command restoration");if(V=l,!l)return;if(e.scope&&(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment))throw new d("SCOPE_MISMATCH","Pending command belongs to another scope");if(S=l.purchase,r=l.closed===!0,!l.command)return;let c=te.parse(l.command);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");o=c,l.closeCommand&&(u=l.closeCommand,r=!0),c.operation==="close"&&(r=!0),g=!0}):Promise.resolve();P.catch(()=>{});async function F(l,c,N){E&&await P;let k=m,Y=t,a=Ee.parse(await n.request("funnels",te.parse(l)));if(l.operation==="review"&&!a.review)throw new d("INVALID_RESPONSE","Historical projection is missing");if(k!==m)throw new d("IDENTITY_CHANGED","Run identity changed during the request");if(a.runToken&&a.runToken!==e.runToken)throw new d("INVALID_RESPONSE","Run credential changed");let B=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(B&&a.settlement?.requestId!==B)throw new d("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(V&&(a.run.id!==V.runId||a.run.source.id!==V.funnelId||a.run.source.versionId!==V.versionId))throw new d("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(t&&(a.run.id!==t.id||a.run.source.type!==t.source.type||a.run.source.id!==t.source.id||a.run.source.versionId!==t.source.versionId||a.run.locale!==t.locale||!ye(a.run.parameters,t.parameters)))throw new d("INVALID_RESPONSE","Run version changed");if(e.funnelId&&a.run.source.id!==e.funnelId)throw new d("INVALID_RESPONSE","Run belongs to another Funnel");E?.bind({scope:a.scope,runId:a.run.id,funnelId:a.run.source.id,versionId:a.run.source.versionId}),A&&!e.scope&&(e.scope=a.scope);let K=a.run.paywall,z=K??a.purchase,me=z?.operation,pe=a.settlement&&(!K||K.purchaseRequestId===a.settlement.requestId)&&(!S||S.operationId===a.settlement.operationId)?a.settlement:void 0,ie=me?.operationId??z?.quote?.operationId??pe?.operationId,ae=z?.receiptId??pe?.receiptId,Ie=K?.selectionGeneration??S?.generation??0;if(E&&ie&&ae&&l.operation!=="review"&&(!t||a.run.revision>=t.revision)&&(N===void 0||N>=y)&&(!S||Ie>=S.generation)){let $={receiptId:ae,operationId:ie,generation:Ie},Ce=me?.status==="complete"||z?.canReselect===!0;await E.observePurchase({scope:a.scope,runId:a.run.id,funnelId:a.run.source.id,versionId:a.run.source.versionId},$,Ce),Ce?S?.operationId===$.operationId&&(S=void 0):S=$}if(!a.run.stopped&&["running","waiting"].includes(a.run.status)&&l.operation==="get"&&l.settlementRequestId)return a;let se=c?.(a),he=typeof se=="boolean"?se:se?await se:!1;if(["running","waiting"].includes(a.run.status)||(r=!0),l.operation==="review"&&t&&t!==Y&&a.run.revision<=t.revision||t&&a.run.revision===t.revision&&N!==void 0&&N<y||(l.operation==="review"&&!a.run.stopped&&["running","waiting"].includes(a.run.status)&&t&&a.run.nodeId===t.nodeId&&a.run.visit===t.visit&&a.run.revision===t.revision&&(a.run.screen=t.screen,(t.paywall?.quote?.operationId===a.review?.activeOperationId||!t.paywall?.quote&&a.review?.activeOperationId===null)&&(a.run.paywall=t.paywall)),t?.paywall&&a.run.paywall&&t.paywall.receiptId===a.run.paywall.receiptId&&(a.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))return a;if(!t||a.run.revision>=t.revision)t=a.run;else if(!he)return a;if(t)for(let $ of v)try{$(structuredClone(t))}catch{}return a}async function D(l=o){if(E&&await P,!l)throw new d("INVALID_REQUEST","No command is pending");let c=l,N=m;if(E){if(!t||!e.scope)throw new d("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await E.retain({schemaVersion:1,scope:e.scope,runId:t.id,funnelId:t.source.id,versionId:t.source.versionId,command:fe(c)})}if(N!==m||o!==c&&u!==c)throw new d("IDENTITY_CHANGED","Run changed before command dispatch");let k={...c,...i?{customerToken:i}:{}},Y=g;g=!0;try{return await F(k,a=>{if(!a.settlement)throw new d("INVALID_RESPONSE","Exact command settlement is missing");if(a.settlement.requestId!==c.requestId)throw new d("INVALID_RESPONSE","Command settlement identity changed");if(N===m&&(o===c||u===c)&&a.run.pendingRequest?.requestId!==c.requestId&&a.settlement.state==="settled"&&(!r||c.operation==="close"||a.settlement?.state==="settled"&&!["running","waiting"].includes(a.run.status))){let B=()=>N!==m||o!==c&&u!==c?!1:(o===c&&(o=null),u===c&&(u=null),g=o!==null,V=null,!0);return E?E.settle(c.requestId).then(B):B()}return!1})}catch(a){throw N===m&&o===c&&!Y&&!dn(a)&&(E&&await E.settle(c.requestId),N===m&&o===c&&(o=null,g=!1,V=null)),a}}function T(l){let c=te.parse(l);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new d("INVALID_REQUEST","Mutation required");if(t?.recoveryRestricted&&c.operation!=="close"&&c.operation!=="resume"&&o?.requestId!==c.requestId)throw new d("PRECONDITION_FAILED","Original Run requires restricted recovery");if(r&&c.operation!=="close"){if(o?.requestId===c.requestId)return ee.settle(c.requestId);throw new d("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(c.operation==="close"&&o?.operation!=="close"){if(r=!0,u&&JSON.stringify(fe(u))!==JSON.stringify(fe(c)))throw new d("COMMAND_PENDING","Retry the original Close");if(u??=c,s)return s;let k=D(u);return s=k,k.then(()=>{s===k&&(s=null)},()=>{s===k&&(s=null)}),k}if(o){if(JSON.stringify(fe(o))!==JSON.stringify(fe(c)))throw new d("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else o=c,g=!1;let N=D();return w=N,N.then(()=>{w===N&&(w=null)},()=>{w===N&&(w=null)}),N}let _=null,U=new WeakMap;function j(l){let c=U.get(l);if(c)return c;let N=X(l);return U.set(l,N),N}let oe=!1;async function X(l){let c=await l;if(c.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(c.run.instruction?.type??""))return c;if(_)return _;oe=!0;let N=m,k=(async()=>{for(let Y=0;Y<32&&["evaluate","evaluate_segment"].includes(c.run.instruction?.type??"");Y++){if(o||r)return c;let a=c.run,B=c.run.instruction;if(B?.type==="evaluate_segment"){let z=await Xe(e.configuration,a);if(N!==m)throw new d("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o||r)return c;if(t&&(t.revision!==a.revision||t.visit!==a.visit||t.nodeId!==a.nodeId))return F({operation:"get",...i?{customerToken:i}:{}});c=await T({operation:"commit_segment",requestId:be(a.id,a.visit,`segment:${a.revision}`),nodeId:a.nodeId,visit:a.visit,revision:a.revision,...z});continue}if(B?.type!=="evaluate")return c;let K=await We(e.configuration,a);if(N!==m)throw new d("IDENTITY_CHANGED","Run identity changed during evaluation");if(o||r)return c;if(t&&(t.revision!==a.revision||t.visit!==a.visit||t.nodeId!==a.nodeId))return F({operation:"get",...i?{customerToken:i}:{}});c=await T({operation:"evaluate",requestId:be(a.id,a.visit,"evaluation"),nodeId:a.nodeId,visit:a.visit,revision:a.revision,receiptId:B.receiptId,policyRevision:B.policyRevision,...K})}return c})();_=k;try{return await k}finally{_===k&&(_=null)}}let ee={get configuration(){return oe?e.configuration:void 0},get configurationReady(){return!0},get view(){return t?structuredClone(t):null},get pendingCommand(){let l=u??o;return l?structuredClone(fe(l)):null},get pendingCommands(){return[o,u].filter(l=>l!==null).map(l=>structuredClone(fe(l)))},get pendingPurchase(){return S?structuredClone(S):null},async settle(l){let c=await F({operation:"get",settlementRequestId:l,...i?{customerToken:i}:{}});if(c.settlement?.requestId!==l)throw new d("INVALID_RESPONSE","Exact command settlement is missing");return c.settlement.state==="settled"&&(E&&await E.settle(l),o?.requestId===l&&(o=null,g=!1),u?.requestId===l&&(u=null)),c},get webViewUrl(){return n.webViewUrl()},review(l){return F({operation:"review",...l?{receiptId:l}:{},...i?{customerToken:i}:{}},void 0,++y)},async get(l,c){E&&await P,c??=S&&{receiptId:S.receiptId,operationId:S.operationId};let N=++y;return j(F({operation:"get",...l?{data:l}:{},...c?{purchase:c}:{},...i?{customerToken:i}:{}},void 0,N))},resume(l=t?.pendingRequest?.requestId){return l?r?ee.settle(l):o?.requestId===l?j(T(o)):j(T({operation:"resume",requestId:l})):Promise.reject(new d("INVALID_REQUEST","No interrupted command is available"))},submit(l){return j(T(l))},retry(){return s||(u?D(u):r&&o?ee.settle(o.requestId):w?j(w):o?j(T(o)):Promise.reject(new d("INVALID_REQUEST","No command is pending")))},identify(l){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(l))throw new d("INVALID_TOKEN","Customer credential required");m++,i=l,n.identify(e.runToken)},subscribe(l){return v.add(l),()=>v.delete(l)},reset(){I=!0,m++,i=void 0,t=null,o=null,u=null,s=null,g=!1,w=null,n.reset(),v.clear()}};return ee}async function Zn(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new d("INVALID_TOKEN","A verified Customer credential is required");let i=we(e);i.identify(n.customerToken);let t=ce.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),m=null,y=null,o=null,u=null,r=null;async function s(){let v=ce.resolvePaywall,A=v.response.parse(await i.request(v.path,v.request.parse({...t,selector:m?{type:"version",versionId:m.id}:t.selector})));if(n.paywallVersionId?A.paywall.id!==n.paywallVersionId:A.paywall.paywallId!==n.paywallId)throw new d("INVALID_RESPONSE","The requested Paywall changed");if(m&&(A.paywall.id!==m.id||A.paywall.paywallId!==m.paywallId||A.paywall.offering.id!==m.offering.id))throw new d("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return m=A.paywall,structuredClone(m)}async function g(v){if(!y)throw new d("INVALID_REQUEST","A quoted purchase is required");let A=v==="read"?ce.readSubscriptionOperation:ce.attach,E=A.response.parse(await i.request(A.path,A.request.parse({operationId:y.operationId,...v==="read"?{}:{intent:v}})));if(E.operation.operationId!==y.operationId||E.operation.currency!==t.commerce.currency)throw new d("INVALID_RESPONSE","The purchase operation changed");return o?.status==="complete"&&E.operation.status!=="complete"||o&&o.status!=="pending"&&E.operation.status==="pending"||(o=E.operation),structuredClone(o)}let w={get view(){return m?structuredClone(m):null},get quote(){return y?structuredClone(y):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return i.webViewUrl()},refresh:s,async preview(v){if(!m)throw new d("INVALID_REQUEST","Load the Paywall first");let A=m.document.buttons[v.actionId];if(A?.type!=="checkout")throw new d("INVALID_REQUEST","Choose an authored purchase action");let E=Le(A.product,v.selection,m.capabilities);if(!E)throw new d("PRODUCT_UNAVAILABLE","Choose an available Product");let S=ce.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:v.requestId,plans:[{productVersionId:E}],provider:t.commerce.provider,currency:t.commerce.currency,...v.offerId?{offerId:v.offerId}:{},...v.nativeOffer?{nativeOffer:v.nativeOffer}:{}}),V=JSON.stringify(S);if(u&&u!==V&&(!o||o.status==="pending"))throw new d("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(u===V){if(r)return r;if(y)return structuredClone(y)}u=V;let I=(async()=>{let P=ce.previewAttach,F=P.response.parse(await i.request(P.path,S));if(F.quote.currency!==t.commerce.currency||F.quote.provider!==t.commerce.provider||F.quote.lines.length!==1||F.quote.lines[0].productVersionId!==E)throw new d("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return y=F.quote,o=null,structuredClone(y)})();r=I;try{return await I}finally{r===I&&(r=null)}},confirm:()=>g("confirm"),cancel:()=>g("cancel"),read:()=>g("read"),destroy(){i.reset(),m=null,y=null,o=null,u=null}};return await s(),w}import{z as gn}from"zod";import{z as ve}from"zod";var fn=ve.record(ve.string().regex(/^[a-f0-9]{64}$/),ve.strictObject({at:ve.number(),text:ve.string()})),on=2*1048576,mn=100;function pn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function an(e,n){let i=n===void 0?pn():n,t=Promise.resolve();async function m(o){if(!i)return null;let u;try{return await Promise.race([Promise.resolve().then(()=>i.getItem(o)),new Promise(r=>{u=setTimeout(()=>r(null),mn)})])}catch{return null}finally{clearTimeout(u)}}async function y(){try{let o=await m(`${e}:artifacts`);if(o&&o.length<=on)return fn.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return m(e)},writeManifest(o){Promise.resolve().then(()=>i?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let u=(await y())[o];return u&&Date.now()>=u.at&&Date.now()-u.at<=H.retentionMs?u.text:void 0},writeArtifact(o,u){i&&(t=t.catch(()=>{}).then(async()=>{let r=await y(),s=Date.now();r[o]={at:s,text:u};let g={},w=2,v=0;for(let[A,E]of Object.entries(r).sort(([,S],[,V])=>V.at-S.at)){if(E.at>s||s-E.at>H.retentionMs)continue;let S=new TextEncoder().encode(JSON.stringify({[A]:E})).byteLength;w+S>on||v>=128||(g[A]=E,w+=S,v++)}await i.setItem(`${e}:artifacts`,JSON.stringify(g))}).catch(()=>{}))}}}var R=(e,n)=>new d(e,n),re=()=>performance.now(),sn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function st(e){let n=je.parse(e.scope),i=new URL(e.origin??Ae);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw R("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([i.origin,...(e.assetOrigins??[]).map(p=>{let f=new URL(p);if(f.protocol!=="https:"||f.username||f.password||f.search||f.hash||f.pathname!=="/")throw R("INVALID_URL","Invalid configuration asset origin");return f.origin})]),m=e.fetch??globalThis.fetch.bind(globalThis),y=`/api/v1/configuration/${n.environmentId}`,o=`indiana:configuration:1:${i.origin}:${M(n)}`,u=an(o,e.storage),r,s=0,g=0,w=!1,v=!1,A=0,E=0,S,V,I,P,F=0,D=new Set,T=new Set,_=new Map,U=new Map,j=0,oe=!1;function X(){for(let p of D)try{p()}catch{}}function ee(p){try{e.onError?.(p)}catch{}}let l=()=>!v&&!w&&!!r&&re()<s&&Date.now()<g;function c(){if(!l())throw R("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function N(p,f){let C=new TextEncoder().encode(f).byteLength;if(!_.has(p)){for(;_.size&&(_.size>=128||j+C>H.maxCacheBytes);){let h=_.entries().next().value;j-=new TextEncoder().encode(h[1]).byteLength,_.delete(h[0])}_.set(p,f),j+=C}}async function k(p,f,C){if(Number(p.headers.get("content-length"))>f)throw R("INVALID_RESPONSE","Configuration exceeds its byte limit");let h=p.body?.getReader();if(!h)throw R("INVALID_RESPONSE","Configuration body is missing");let b=[],L=0;try{for(;;){C.throwIfAborted();let x=await h.read();if(x.done)break;if(L+=x.value.length,L>f)throw R("INVALID_RESPONSE","Configuration exceeds its byte limit");b.push(x.value)}}finally{await h.cancel().catch(()=>{})}C.throwIfAborted();let O=new Uint8Array(L),G=0;for(let x of b)O.set(x,G),G+=x.length;return new TextDecoder("utf-8",{fatal:!0}).decode(O)}function Y(p){let f=new URL(p,i);if(!t.has(f.origin)||f.username||f.password||f.hash||f.search)throw R("INVALID_URL","Configuration artifact origin is not trusted");return f.href}async function a(p,f,C=!1){let h=await m(Y(p),{method:"GET",credentials:"omit",redirect:"error",cache:C?"default":"no-cache",signal:f,headers:{}});if(h.status===429){let b=h.headers.get("retry-after")??"";F=/^\d+$/.test(b)?Number(b)*1e3:Math.max(0,Date.parse(b)-Date.now())||15e3}if(!h.ok&&h.status!==304)throw R(`CONFIGURATION_HTTP_${h.status}`,"Configuration synchronization failed");return h}function B(p,f,C){let h=Date.parse(p.headers.get("x-indiana-config-validated-at")??""),b=Date.parse(p.headers.get("x-indiana-config-valid-until")??""),L=Date.parse(p.headers.get("date")??""),O=p.headers.get("age"),G=O!==null&&/^\d+(\.\d+)?$/.test(O)?Number(O)*1e3:NaN;if(![h,b,L,G].every(Number.isFinite)||b<=h||b-h>H.maxControlAgeMs||h>L+1e3)throw R("INVALID_RESPONSE","Configuration freshness evidence is invalid");let q=Math.min(b-h,C.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(G,L-h,0)-(re()-f);if(q<=0)throw R("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return re()+q}function K(){if(clearTimeout(I),clearTimeout(P),v||!D.size)return;l()&&(P=setTimeout(()=>{l()?K():X()},Math.max(1,s-re())),sn(P));let p=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);I=setTimeout(()=>{z().catch(ee)},Math.max(F,p*(.8+Math.random()*.2))),sn(I)}async function z(){if(v)throw R("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(S)return S;let p=A,f=new AbortController;V=f;let C=(async()=>{if(!oe){oe=!0;try{let Re=await u.readManifest();if(Re&&!r){let W=Pe.parse(JSON.parse(Re));M(W.scope)===M(n)&&(r=W)}}catch{}}f.signal.throwIfAborted();let O=r,G=re(),x=await a(y,f.signal);x.status===304&&(!O||!x.headers.has("x-indiana-config-validated-at")||!x.headers.has("x-indiana-config-valid-until")||!x.headers.has("age"))&&(x=await a(y,f.signal));let q=x.status===304?O:Pe.parse(JSON.parse(await k(x,H.maxManifestBytes,f.signal))),{generation:Z,...ne}=q,ue=x.headers.get("etag");if(M(q.scope)!==M(n)||Be(ne)!==Z||ue!==`"${Z}"`&&ue!==`W/"${Z}"`)throw R("INVALID_RESPONSE","Configuration scope or content identity changed");if(O&&(q.revision<O.revision||q.revision===O.revision&&q.generation!==O.generation))throw R("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Re,W]of Object.entries(O?.funnels??{})){let le=q.funnels[Re];if(le&&(le.controlRevision<W.controlRevision||le.evaluationRevision<W.evaluationRevision||le.controlRevision===W.controlRevision&&le.state!==W.state||le.evaluationRevision===W.evaluationRevision&&le.evaluationMode!==W.evaluationMode))throw R("INVALID_RESPONSE","Funnel control revision changed identity")}let Te=B(x,G,q.policy);if(f.signal.throwIfAborted(),p!==A)throw R("CONFIGURATION_DISPOSED","Configuration scope changed");return r=q,s=Te,g=Date.now()+Math.max(0,Te-re()),w=!1,E=0,F=0,u.writeManifest(M(q)),X(),structuredClone(q)})(),h=setTimeout(()=>f.abort(R("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),b=new Promise((O,G)=>f.signal.addEventListener("abort",()=>G(f.signal.reason),{once:!0})),L=Promise.race([C,b]).catch(O=>{throw E++,(O instanceof gn.ZodError||O instanceof SyntaxError||O instanceof d&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(O.code))&&(s=0,w=!0,X()),O}).finally(()=>{clearTimeout(h),S===L&&(S=void 0),K()});return S=L,L}async function me(p){let f=p.sha256,C=Z=>new TextEncoder().encode(Z).byteLength===p.byteLength&&Je(Z)===f;Y(p.url);let h=_.get(f);if(h&&C(h))return _.delete(f),_.set(f,h),h;if(U.has(f))return U.get(f);let b=new AbortController;T.add(b);let L=A,O=(async()=>{try{let ue=await u.readArtifact(f);if(ue&&C(ue))return N(f,ue),ue}catch{}b.signal.throwIfAborted();let Z=await a(p.url,b.signal,!0),ne=await k(Z,p.byteLength,b.signal);if(!C(ne))throw R("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(v||L!==A)throw R("CONFIGURATION_DISPOSED","Configuration scope changed");return N(f,ne),u.writeArtifact(f,ne),ne})(),G=setTimeout(()=>b.abort(R("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),x=new Promise((Z,ne)=>b.signal.addEventListener("abort",()=>ne(b.signal.reason),{once:!0})),q=Promise.race([O,x]).finally(()=>{clearTimeout(G),T.delete(b),U.delete(f)});return U.set(f,q),q}async function pe(){return l()||await z(),c(),r}async function ie(p){let f,C=new Promise((h,b)=>{f=setTimeout(()=>b(R("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([p(),C])}finally{clearTimeout(f)}}function ae(p,f){if(c(),r?.generation!==p.generation)throw R("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(f&&r.funnels[f]?.state!=="active")throw R("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ie(p){let f=p.gb.features;if(!f)throw R("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let C=p.artifacts[f];if(C.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let h=Me.parse(JSON.parse(await me(C)));if(M(h.scope)!==M({projectId:n.projectId,environment:n.environment})||h.generation!==C.generation||h.remoteFeatures.some(b=>Object.hasOwn(h.features,b)))throw R("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(p),{...h,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-re())).toISOString()}}async function se(p,f){let C=await pe();ae(C,p);let h=C.funnels[p];if(h.evaluationMode!=="local")throw R("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let b=f??h.currentVersionId,L=h.versions[b];if(!L)throw R("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(C.artifacts[L.artifact].formatVersion!==3)throw R("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[O,G]=await Promise.all([me(C.artifacts[L.artifact]).then(x=>He(JSON.parse(x))),h.evaluationMode==="local"?Ie(C):void 0]);if(G&&M(ze(O,G))!==M(L.dependencies))throw R("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(C,p),{document:O,growth:G,versionId:b,control:structuredClone(h),manifest:structuredClone(C)}}function he(){w=!0,X(),z().catch(ee)}let $=()=>{(typeof document>"u"||document.visibilityState==="visible")&&he()};function Ce(p){if(v)throw R("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return D.add(p),D.size===1&&(typeof window<"u"&&(window.addEventListener("online",he),window.addEventListener("focus",$),document.addEventListener("visibilitychange",$)),K()),()=>{D.delete(p),D.size||(clearTimeout(I),clearTimeout(P),Oe())}}function Oe(){typeof window<"u"&&(window.removeEventListener("online",he),window.removeEventListener("focus",$),document.removeEventListener("visibilitychange",$))}return{scope:Object.freeze({...n}),refresh:z,subscribe:Ce,assertFresh:c,assertFeatures(p){c();let f=r.gb.features;if(!f)throw R("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(p!==void 0&&r.artifacts[f].generation!==p)throw R("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return l()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return l()?Math.max(0,s-re()):0},async features(){return ie(async()=>Ie(await pe()))},pageExperiments:()=>ie(async()=>{let p=await pe(),f=p.gb.pageExperiments;if(!f)throw R("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let C=p.artifacts[f];if(C.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let h=Ge.parse(JSON.parse(await me(C)));if(h.environmentId!==n.environmentId||h.generation!==C.generation)throw R("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(p),h}),funnel:(p,f)=>ie(()=>se(p,f)),async localFunnel(p,f){let C=await ie(()=>se(p,f));if(!C.growth)throw R("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:h,remoteFeatures:b,...L}=C.growth;return qe({scope:{projectId:n.projectId,environment:n.environment},funnelId:p,versionId:C.versionId,evaluationMode:"local",evaluationRevision:C.control.evaluationRevision,document:C.document,payload:L})},assertFunnel(p,f,C){c();let h=r.funnels[p];if(!h||h.state!=="active")throw R("FUNNEL_STOPPED","Funnel is paused or unavailable");if(h.evaluationMode!=="local")throw R("EVALUATION_MODE","This Funnel now executes at Indiana");if(f!==void 0&&h.controlRevision!==f)throw R("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(C!==void 0&&!h.versions[C])throw R("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!v){v=!0,A++,s=0,V?.abort(R("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(I),clearTimeout(P),Oe(),X(),D.clear();for(let p of T)p.abort(R("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));_.clear(),j=0}}}}function dt(e,n,i){return $e(e,n,i,de)}function un(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new d("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new d("INVALID_TOKEN","A customer credential or server API key is required");let i=we({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(t){let m=te.safeParse({...t,operation:"start"});if(!m.success||m.data.operation!=="start"||(n?m.data.customer!==void 0:m.data.customer===void 0))throw new d("INVALID_REQUEST","Invalid current Funnel start");let y=m.data,o=Ee.safeParse(await i.request("funnels",y));if(!o.success||!o.data.runToken)throw new d("INVALID_RESPONSE","Funnel start credentials are missing");let u=o.data;if(u.run.source.id!==y.funnelId||u.run.locale!==(y.locale??"en")||!ye(u.run.parameters,y.parameters??{})||(y.customer?!u.customerId||y.customer.type==="id"&&u.customerId!==y.customer.value:u.customerId!==void 0))throw new d("INVALID_RESPONSE","Funnel start contract changed");return{...u,runToken:u.runToken}}}}async function Ct(e){e={...e};let n=e.configuration;if(!n)throw new d("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(i)!==M(e.scope))throw new d("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new d("EVALUATION_MODE","This Funnel uses Remote evaluation");let m=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(m?!e.customerId:e.customerId!==void 0)throw new d("INVALID_REQUEST","Only Server-Key starts name their Customer");let y=un({...e,scope:i,apiKey:e.credential}),o=u=>{let r=rn({...e,scope:i,runToken:u,...m?{serverKey:e.credential}:{}});return m||r.identify(e.credential),r};return{async start(u){let r=await y.start({...u,funnelId:e.funnelId,...m?{customer:{type:"id",value:e.customerId}}:{}}),s=o(r.runToken),g=await s.get();return{...r,...g,controller:s}},async restore(u){let r=o(u),s=await r.get();if(s.run.source.id!==e.funnelId)throw r.reset(),new d("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:u,controller:r}}}}export{yn as a,Rn as b,ye as c,Fn as d,ln as e,cn as f,Ze as g,rn as h,Zn as i,st as j,dt as k,un as l,Ct as m};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as ne}from"./chunk-6X42DWOM.js";import"./chunk-FVUPV6YE.js";import{Gd as ve,ui as me}from"./chunk-FF3LWJ26.js";import{a as w}from"./chunk-5TEZEOHX.js";import{Gb as Ce}from"./chunk-RMJJOSVZ.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S2MSIA57.js";function be(E){let F=E.view;if(!F?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let n=F.paywall.receiptId,Z=F.nodeId,te=F.visit,m=F.paywall.resolution,R=F.paywall.quote,g=F.paywall.operation,S=!1,V=new AbortController,v=F.paywall.purchaseRequestId,k=0,U=F.paywall.selectionGeneration??0,L=F.paywall.canReselect===!0,T=null,j=new Map,$=new Map;function D(t){if(t.purchase&&t.purchase.receiptId!==n)throw new w("INVALID_RESPONSE","Purchase receipt changed");let i=t.run.paywall;return t.purchase??(i?.receiptId===n?i:null)}function b(){if(S)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function O(t,i,s){if(b(),i!==k||s!==void 0&&R?.operationId!==s)return!1;let h=U,a=t.run.paywall;if(a?.receiptId===n){if((a.selectionGeneration??0)<U)return!1;if(U=a.selectionGeneration??0,L=a.canReselect===!0,a.resolution.id!==m.id||a.resolution.offering.id!==m.offering.id)throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let c=D(t),l=U>h,P=l?c?.quote??null:c?.quote??R,N=c?.operation??(P?.operationId===R?.operationId?g:null);if(P&&N&&P.operationId!==N.operationId)throw new w("INVALID_RESPONSE","Purchase operation changed");return a?.receiptId===n&&(m=a.resolution),(l||P?.operationId!==R?.operationId)&&(k++,a?.receiptId===n&&(v=a.purchaseRequestId)),R=P,(g?.operationId!==N?.operationId||g?.status==="pending"||N?.status==="complete")&&(g=N),!0}function z(t,i,s){return new Promise((h,a)=>{let c=!1,l=()=>{clearTimeout(ie),V.signal.removeEventListener("abort",M)},P=ee=>{c||(c=!0,l(),h(ee))},N=ee=>{c||(c=!0,l(),a(ee))},M=()=>N(new w("IDENTITY_CHANGED","Paywall presentation has closed")),ie=setTimeout(()=>N(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,i-Date.now()));V.signal.addEventListener("abort",M,{once:!0}),V.signal.aborted&&M(),t.then(P,N)})}function x(t){return new Promise(i=>{let s=()=>{clearTimeout(h),V.signal.removeEventListener("abort",s),i()},h=setTimeout(s,t);V.signal.addEventListener("abort",s,{once:!0}),V.signal.aborted&&s()})}async function W(t,i,s){b();let h=j.get(t);if(!h){let l=E.pendingCommands?.find(P=>P.requestId===t)??E.pendingCommand;if(l?.operation==="submit"&&l.requestId===t&&l.nodeId===Z&&l.visit===te){i.type==="paywall_quote"&&l.input.type==="paywall_quote"&&l.input.predecessor&&!i.predecessor&&(i={...i,predecessor:l.input.predecessor});let P=me.parse(l),N=me.parse({...l,input:i});if(N.operation!=="submit"||P.operation!=="submit"||JSON.stringify(N.input)!==JSON.stringify(P.input))throw new w("CONFLICT","A restored purchase request cannot change its input");i=N.input,h=P,j.set(t,h)}}if(h){if(JSON.stringify(h.input)!==JSON.stringify(i))throw new w("CONFLICT","A purchase request cannot change its input")}else{let l=E.view;if(!l||l.nodeId!==Z||l.visit!==te||l.paywall?.receiptId!==n)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");h={operation:"submit",requestId:t,nodeId:Z,visit:te,revision:l.revision,input:i},j.set(t,h)}let a=Date.now()+3e4,c=await z(E.submit(h),a,t);for(;c.run.pendingRequest?.requestId===t&&Date.now()<a&&!S&&(await x(Math.min(1e3,a-Date.now())),!(S||Date.now()>=a));)c=await z(E.resume(t),a,t);if(S)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(c.run.pendingRequest?.requestId===t)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!O(c,s,i.type==="paywall_confirm"||i.type==="paywall_cancel"?i.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed")}async function K(t){if(!R)throw new w("INVALID_REQUEST","A quoted purchase is required");let i=`${t}:${R.operationId}`,s=$.get(i);if(!s){let h=t==="confirm"?"paywall_confirm":"paywall_cancel",a=E.pendingCommands?.find(c=>c.operation==="submit"&&c.input.type===h&&"operationId"in c.input&&c.input.operationId===R.operationId)??E.pendingCommand;s=a?.operation==="submit"&&a.input.type===h&&"operationId"in a.input&&a.input.operationId===R.operationId?a.requestId:crypto.randomUUID(),$.set(i,s)}if(await W(s,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:R.operationId},k),!g)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(g)}return{get view(){return structuredClone(m)},get quote(){return R?structuredClone(R):null},get operation(){return g?structuredClone(g):null},get webViewUrl(){return E.webViewUrl},get canReselect(){return L},async refresh(){b();let t=k;return O(await E.get(),t),structuredClone(m)},preview(t){if(v&&v!==t.requestId&&(T||!L))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));if(v===t.requestId&&T)return T;let i=m.document.buttons[t.actionId],s=i?.type==="checkout"?ve(i.product,t.selection,m.capabilities):null;if(!s)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let h=v!==t.requestId&&U>0?{operationId:R?.operationId??null,generation:U}:void 0;if(h&&(!L||U<=0))return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));v!==t.requestId&&k++;let a=k;v=t.requestId;let c=(async()=>{if(await W(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:s,...h?{predecessor:h}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},a),!R)throw new w("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(R)})();return T=c,c.then(()=>{T===c&&(T=null)},l=>{T===c&&(T=null),v===t.requestId&&E.pendingCommand?.requestId!==t.requestId&&l instanceof w&&l.status!==void 0&&l.status<500&&![401,425].includes(l.status)&&(v=null)}),c},confirm:()=>K("confirm"),cancel:()=>K("cancel"),async read(){if(b(),!R)throw new w("INVALID_REQUEST","A quoted purchase is required");let t=R.operationId,i=k,s=E.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===t)??E.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===t&&await E.settle?.(s.requestId);let h=await E.get(void 0,{receiptId:n,operationId:t});b();let a=D(h);if(a?.quote&&a.quote.operationId!==t||a?.operation&&a.operation.operationId!==t)throw new w("INVALID_RESPONSE","Purchase operation changed");let c=O(h,i,t)?g:a?.operation;if(!c)throw new w("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(c)},destroy(){S=!0,V.abort(),j.clear(),$.clear()}}}async function Fe(E,F){let n=F,{mountScreenPreview:Z}=await import("./popup.js"),{showPaywall:te}=await import("./paywall-5WU6PX5C.js"),m=E.ownerDocument,R=m.activeElement,g=m.createElement("section"),S=m.createElement("div"),V=m.createElement("div"),v=m.createElement("div"),k=m.createElement("button");v.hidden=!0,k.type="button";let U=m.createElement("p"),L=m.createElement("p"),T=m.createElement("button"),j=m.createElement("button"),$=m.createElement("button"),D=m.createElement("dialog");g.dataset.indianaFunnel="",g.setAttribute("aria-busy","false"),g.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",V.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",U.setAttribute("role","status"),L.setAttribute("role","alert"),L.hidden=!0,T.type=j.type=$.type="button",V.append(T,U,L,$,k,j),g.append(S,v,V),E.append(g);let b=null,O=null,z=null,x="",W="",K="",t="",i=!1,s=0,h=!1,a="",c=null,l=Promise.resolve(),P=null,N=null,M={},ie=new Map,ee=new Set,se=new Set,ae=new Set,oe=null,H={},C=!1,he,G=0,q=null,re="",le=new Map,ye=e=>e?`${e.id}:${e.nodeId}:${e.visit}:${e.revision}:${e.paywall?.quote?.operationId??""}`:"",J=(e,o=null)=>{i||(N=o,L.textContent=e instanceof Error?e.message:"Request failed",L.hidden=!1,$.hidden=n.client.pendingCommand===null,ne(n.onError,e))};function B(){let e=n.client.view;if(!e)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}async function Y(e,o=!1){if(!(s&&!o||i||(C||n.client.view?.recoveryRestricted)&&!o)){s++,g.setAttribute("aria-busy","true"),L.hidden=!0,N=null;try{if(!o&&oe){let r=n.client.view;await oe;let y=n.client.view;if(!r||!y||y.id!==r.id||y.nodeId!==r.nodeId||y.visit!==r.visit||y.stopped||!["running","waiting"].includes(y.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(i)return;let d=await e();i||await X(n.client.view??d.run)}catch(d){J(d,n.client.pendingCommand?.requestId??null)}finally{s=Math.max(0,s-1),g.setAttribute("aria-busy",String(s>0)),i||($.hidden=n.client.pendingCommand===null,T.disabled=s>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function ge(e){if(C||ee.has(e)||se.has(e)||i)return;se.add(e);let o=async()=>{if(C||i||x!==e){se.delete(e);return}if(s||n.client.pendingCommand){setTimeout(()=>{o()},250);return}let d=(async()=>{let y=n.client.view,p=B(),A=p.requestId,u=!1;try{await n.client.submit({operation:"shown",...p})}catch(I){if(!(I instanceof w)||I.code!=="CONFLICT"||I.status!==409||n.client.pendingCommand)throw I;await n.client.get();let f=n.client.view;if(i||C||x!==e||!f||!y||f.id!==y.id||f.source.versionId!==y.source.versionId||f.nodeId!==p.nodeId||f.visit!==p.visit||f.revision<=p.revision||f.stopped||!f.screen||!["running","waiting"].includes(f.status)||n.client.pendingCommand)throw I;let _=B();A=_.requestId,await n.client.submit({operation:"shown",..._})}for(;!i&&x===e&&n.client.pendingCommand?.requestId===A;){if(!n.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(A),u=!0,n.client.pendingCommand?.requestId===A&&await new Promise(I=>setTimeout(I,1500))}i||x!==e||(u&&await n.client.get(),!(i||x!==e)&&ee.add(e))})();oe=d;let r=()=>{oe===d&&(oe=null),se.delete(e)};d.then(r,y=>{r(),s||J(y)})};o()}function ue(){c&&clearTimeout(c),!(i||!z||!["running","waiting"].includes(z.status)&&!n.client.pendingCommand)&&(c=setTimeout(()=>{c=null,Ie().finally(ue)},z.pendingRequest||n.client.pendingCommand?1500:5e3))}async function Ie(){if(!(i||h||s)){if(C){await ce(he);return}h=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let o=n.client.view,d=M,r=await n.client.get(o?.screen&&Object.keys(d).length?{nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:d}:void 0);!i&&d===M&&await X(n.client.view??r.run)}catch(e){J(e)}finally{h=!1}}}async function Ee(e){let o=n.client.view,d=o?.screen,r=d?.customerData.nodes[e.nodeId];if(i||s||!o||!d||!r)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let _=b?.document,Q=_?Ce(_,e.nodeId):null,we=Q?.type==="customer_data"?Q.data.outputs?.[e.action]:void 0;we&&d.outputs.includes(we)?await Y(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:we,answers:H,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,o);return}let p=e.action.startsWith("sources_")?r.resources.find(_=>_.key===e.value):null;if(e.action.startsWith("sources_")&&!p)throw new w("INVALID_REQUEST","Choose a current resource");let A=`${o.visit}:${e.nodeId}:${p?.key??""}`,u=ie.get(A)??[null],f=M[e.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(e.action==="filter"){let _=e.value;if(!_||!(r.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(_))throw new w("INVALID_REQUEST","Unknown data filter");f={page:1,after:null,filter:_},u.splice(0,u.length,null)}else if(e.action==="next"||e.action==="sources_next"){let _=p?.sources.at(-1),Q=p?_?{kind:"ledger",cursor:{at:_.detail[0],id:_.id,type:"source"}}:null:d.dataCursors[e.nodeId];if(!Q||!p&&!r.hasNext)return;u[f.page]=Q,f={...f,page:f.page+1,after:Q}}else if(e.action==="previous"||e.action==="sources_previous"){if(f.page<=1)return;f={...f,page:f.page-1,after:u[f.page-2]??null}}ie.set(A,u),M={...M,[e.nodeId]:f},await Y(()=>n.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:M}))}function Re(e){let o=e.screen?.presentation;if(!o||o.type==="inline"){D.open&&D.close(),g.parentElement!==E&&E.append(g);return}g.parentElement!==D&&(D.append(g),E.append(D));let d={sm:420,md:640,lg:900};D.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in o?d[o.size]+"px":"100vw"}`,D.setAttribute("aria-label",b?.document?.name??e.screen?.content.document.name??"Funnel"),D.open||D.showModal()}async function De(e){if(i)return;z=e,N&&n.client.pendingCommand?.requestId!==N&&(L.hidden=!0,N=null);let o=e.locale.startsWith("zh");if(k.textContent=o?"\u56DE\u770B":"History",k.hidden=!n.client.review,T.textContent=C?o?"\u8FD4\u56DE\u5F53\u524D":"Return to current":o?"\u8FD4\u56DE":"Back",j.textContent=o?"\u5173\u95ED":"Close",$.textContent=o?"\u91CD\u8BD5":"Retry",T.disabled=!C&&(s>0||!!n.client.pendingCommand||!e.canBack),$.hidden=n.client.pendingCommand===null,U.textContent=e.pendingRequest?o?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?o?"\u7B49\u5F85\u4E2D":"Waiting":"",a!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(a=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,ne(n.onState,structuredClone(e))),e.stopped||n.client.configurationReady===!1){C=!1,G++,q?.destroy(),q=null,v.replaceChildren(),v.hidden=!0,S.hidden=!1,b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",W="",t="",D.open&&D.close(),g.hidden=!0,ue();return}if(g.hidden=!1,C){ue();return}if(e.recoveryRestricted){b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",U.textContent=o?"\u539F\u8BB0\u5F55\u9700\u8981\u6838\u5BF9\uFF0C\u53EF\u53EA\u8BFB\u56DE\u770B":"Original records require reconciliation; read-only history is available";return}let d=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(d!==x&&(b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x=d,W="",t="",H={...e.answers},M={},ie.clear()),Re(e),e.screen){let y=e.screen.content;b||(b=Z(S,{mode:"live",rendererUrl:n.client.webViewUrl,title:y.document.name,onAction(u,I={},f={}){if(C)return;H={...H,...f};let _=Object.fromEntries((e.screen?.inputs??[]).filter(({variable:Q})=>Object.hasOwn(H,Q)).map(({variable:Q})=>[Q,H[Q]]));Y(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:u,answers:_,selection:I}}))},onAnswers:u=>{C||(H={...H,...u})},onCustomerDataIntent:u=>{C||Ee(u).catch(J)},onEscape:()=>{C||de()},onError:u=>J(new Error(u)),onRendered:()=>ge(d)}));let p={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:H,values:e.screen.values}},A=JSON.stringify([y,e.locale,p.parameters,e.screen.inputs,e.screen.values]);if(A!==W)b.update(y.document,e.locale,p),W=A,K=JSON.stringify(p.capabilities),t=JSON.stringify(p.customerData);else{let u=JSON.stringify(p.capabilities);u!==K&&(b.updateCapabilities(p.capabilities),K=u),JSON.stringify(p.customerData)!==t&&(b.updateCustomerData(p.customerData),t=JSON.stringify(p.customerData))}await b.ready}else if(e.paywall&&!O){let y=await te(S,{canInteract:()=>!C&&!i&&!n.client.view?.recoveryRestricted,start:async()=>be(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p,openIn:"same_window"}):m.defaultView?.location.assign(p),onAction:async p=>{if(C)return;let A=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:p,answers:{}}});await X(n.client.view??A.run)},onError:J,onDismiss:()=>{!C&&!i&&n.client.view?.visit===e.visit&&de()}});i?y.host?.destroy():(O=y.host,O?.setSuspended(C)),ge(d)}let r=e.instruction;if(r&&(r.type==="open_url"||r.type==="event")&&!ae.has(r.receiptId)){let y=m.createElement("button");y.type="button",y.textContent=r.type==="open_url"?`${o?"\u524D\u5F80":"Continue to"} ${new URL(r.url).host}`:o?"\u7EE7\u7EED":"Continue",y.onclick=()=>{let p=B(),A=r.type==="open_url"&&!n.onOpenUrl&&r.openIn==="new_window"?Pe(r.url):null;Y(async()=>{let u="success";if(r.type==="open_url")if(n.onOpenUrl)try{u=await n.onOpenUrl({receiptId:r.receiptId,url:r.url,openIn:r.openIn})===!1?"failed":"opened"}catch(f){ne(n.onError,f),u="failed"}else u=r.openIn==="new_window"&&!A?"failed":"opened";if(r.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(r.event)}if(i||n.client.view?.nodeId!==p.nodeId||n.client.view.visit!==p.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let I=await n.client.submit({operation:"submit",...p,input:{type:"client_action",receiptId:r.receiptId,outcome:u}});return ae.add(r.receiptId),r.type==="open_url"&&!n.onOpenUrl&&r.openIn==="same_window"&&m.defaultView?.location.assign(r.url),I})},S.replaceChildren(y)}!e.pendingRequest&&e.status==="completed"&&!ae.has(`complete:${e.id}`)&&(ae.add(`complete:${e.id}`),ne(n.onComplete,structuredClone(e))),ue()}function Pe(e){let o=m.defaultView?.open(e,"_blank")??null;return o&&(o.opener=null),o}function X(e){return l=l.catch(()=>{}).then(()=>De(e)),l}async function ce(e){if(i||!n.client.review)return;C||(re=ye(n.client.view),le.set(re,structuredClone(H))),C=!0,he=e,S.hidden=!0,O?.setSuspended(!0),v.hidden=!1;let o=++G;try{let d=await n.client.review(e);if(i||o!==G||!C)return;if(!d.review)throw new w("INVALID_RESPONSE","Historical projection is missing");q?.destroy(),q=null,v.replaceChildren();let r=d.run.locale.startsWith("zh"),y=m.createElement("p");y.textContent=r?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",v.append(y);for(let[u,I]of d.review.pages.entries()){let f=m.createElement("button");f.type="button",f.textContent=r?`\u7B2C ${u+1} \u9875`:`Page ${u+1}`,f.onclick=()=>{ce(I.receiptId)},v.append(f)}if(d.review.page){let u=d.review.page,I=m.createElement("div");if(I.inert=!0,v.append(I),q=Z(I,{mode:"live",rendererUrl:n.client.webViewUrl,title:u.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{fe()}}),q.update(u.document,d.run.locale,{serverInput:{bindings:u.inputs,answers:u.answers,values:u.values}}),await q.ready,i||o!==G||!C)return}let p=r?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},A=r?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let u of[...d.review.coupons.map((I,f)=>`${r?"\u4F18\u60E0\u5238":"Coupon"} ${f+1}: ${p[I.status]}`),...d.review.purchases.map((I,f)=>`${r?"\u8D2D\u4E70":"Purchase"} ${f+1}: ${A[I.status]}`)]){let I=m.createElement("p");I.textContent=u,v.append(I)}n.client.view&&await X(n.client.view)}catch(d){if(o!==G||i)return;q?.destroy(),q=null,v.replaceChildren(),J(d)}}async function fe(){if(!C||i||!n.client.review)return;let e=++G;try{if(await n.client.review(),i||e!==G)return;C=!1,G++,q?.destroy(),q=null,v.replaceChildren(),v.hidden=!0,S.hidden=!1;let o=n.client.view;ye(o)!==re?(le.set(re,structuredClone(H)),x="",W=""):(le.delete(re),O?.setSuspended(!1)),o&&await X(o)}catch(o){if(e!==G||i)return;q?.destroy(),q=null,v.replaceChildren(),J(o)}}let Ne=n.client.subscribe(e=>{n.client.configurationReady===!1&&(g.hidden=!0,b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",W="",t="",D.open&&D.close()),X(e).catch(J)}),Oe=n.client.subscribeError?.(J);function de(){return P||(i?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(pe(),Promise.resolve()):(P=Y(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&pe()}).finally(()=>{P=null}),P))}function pe(){i||(i=!0,c&&clearTimeout(c),Ne(),Oe?.(),b?.destroy(),G++,q?.destroy(),O?.destroy(),D.close(),D.remove(),g.remove(),R instanceof HTMLElement&&R.isConnected&&R.focus(),ne(n.onDismiss,z?structuredClone(z):null))}T.onclick=()=>{if(C){fe();return}Y(()=>n.client.submit({operation:"back",...B()}))},k.onclick=()=>{ce()},j.onclick=()=>{de()},$.onclick=()=>{Y(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),de()});try{let e=await n.client.get();await X(n.client.view??e.run)}catch(e){throw pe(),e}return{destroy:pe,refresh:Ie,review:ce,exitReview:fe,get unappliedDrafts(){return new Map([...le].map(([e,o])=>[e,structuredClone(o)]))}}}export{Fe as showFunnelRun};
|
package/dist/paywall-5WU6PX5C.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as z}from"./chunk-6X42DWOM.js";import"./chunk-FVUPV6YE.js";import{Gd as q,bk as j}from"./chunk-FF3LWJ26.js";import{a as w}from"./chunk-5TEZEOHX.js";import{f as $,ja as N}from"./chunk-RMJJOSVZ.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S2MSIA57.js";async function W(b,n,h){if(n.status!=="complete")throw new w("INVALID_RESPONSE","A verified completed purchase is required");if(await h.onComplete?.(n),!b||!h.check)return;let t=N.parse(await h.check());if(t.internal_feature_id!==b.internal_feature_id||t.quantity!==b.quantity)throw new w("INVALID_RESPONSE","The access requirement changed");t.allowed&&await h.onAccessGranted?.(t)}async function ie(b,n){let h=n.check?N.parse(await n.check()):null;if(h?.allowed)return await n.onAccessGranted?.(h),{check:h,host:null};let t=await n.start(),y=t.view;if(!y)throw new w("INVALID_RESPONSE","Paywall presentation is missing");let{mountScreenPreview:J}=await import("./popup.js"),a=b.ownerDocument,S=new AbortController,v=a.createElement("section"),Q=a.createElement("div"),O=a.createElement("div"),P=a.createElement("p"),c=a.createElement("button"),L=a.createElement("button"),u=a.createElement("dialog"),_=a.activeElement,p=y.document.screen.strings.defaultLocale.startsWith("zh");v.dataset.indianaPaywall="",v.setAttribute("aria-label",y.document.name),v.style.cssText="width:100%;box-sizing:border-box;background:#fff;color:#172033;font:14px/1.5 system-ui,sans-serif",O.style.cssText="display:flex;gap:12px;padding:12px 20px;align-items:center;flex-wrap:wrap",P.setAttribute("role","status"),L.textContent=p?"\u5173\u95ED":"Close",c.textContent=p?"\u91CD\u8BD5":"Retry",c.hidden=!0,O.append(P,c,L),v.append(Q,O);let D=y.document.presentation,A,d=!1,T=!1,f=null,G=!1,m=()=>!G&&n.canInteract?.()!==!1,M=!1,r=null,I=null,U=e=>{P.textContent=e instanceof Error?e.message:p?"\u8BF7\u6C42\u5931\u8D25":"Request failed",z(n.onError,e),c.hidden=r===null};async function k(e){if(!(T||d||!m())){T=!0,c.hidden=!0,P.textContent="";try{await e()}catch(s){d||U(s)}finally{T=!1}}}async function K(e){await W(h,e,n)}async function E(e){if(d)return;if(!m()){r=async()=>E(await t.read()),c.hidden=!1;return}if(P.textContent=e.status,e.status==="complete"){r=null,await K(e);return}if(e.status!=="pending"){if(t.canReselect===!1){P.textContent=p?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",c.textContent=p?"\u67E5\u8BE2\u7ED3\u679C":"Check result",r=async()=>E(await t.read()),c.hidden=!1;return}c.textContent=p?"\u91CD\u8BD5":"Retry",r=null,f=null;return}let s=Date.now()+6e5,l=2e3;for(;!d&&Date.now()<s;){if(await new Promise(C=>{let R=()=>{clearTimeout(x),C()},x=setTimeout(()=>{S.signal.removeEventListener("abort",R),C()},l);S.signal.addEventListener("abort",R,{once:!0})}),d)return;if(!m()){r=async()=>E(await t.read()),c.hidden=!1;return}let i=await t.read();if(i.status!=="pending"){await E(i);return}l=Math.min(l*1.5,3e4)}r=async()=>E(await t.read()),c.hidden=!1}async function V(){I?.remove(),I=null,r=V;let e=await t.confirm();if(!m()){r=V,c.hidden=!1;return}if(e.status==="pending"){if(e.checkoutUrl)n.onCheckoutUrl?await n.onCheckoutUrl(e.checkoutUrl):a.defaultView?.location.assign(e.checkoutUrl);else if(e.execution||e.nativePurchase){if(!n.onPurchase)throw new w("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await n.onPurchase({operation:e,signal:S.signal})}}r=async()=>E(await t.read()),await E(e)}function X(e){I?.remove();let s=a.createElement("div"),l=a.createElement("button"),i=a.createElement("button"),C=a.createElement("p");C.textContent=e.lines.map(o=>o.productName).join(", ")+" \xB7 "+$(e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),e.currency),l.textContent=p?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",i.textContent=p?"\u53D6\u6D88":"Cancel",l.onclick=()=>{k(V)};let R=async()=>{let o=await t.cancel();d||(s.remove(),I=null,await E(o))};i.onclick=()=>{r=R,k(R)};let x=a.createElement("div");for(let o of e.lines){let B=a.createElement("p");if(B.textContent=`${o.productName} \xB7 ${$(o.catalogAmountMinor,e.currency)}${j(o.interval,p?"zh-CN":"en",o.intervalCount??1)}`,x.append(B),o.trial){let F=a.createElement("p");F.textContent=p?`\u8BD5\u7528 ${o.trial.days} \u5929\uFF1B${o.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${o.trial.days}; ${o.trial.cardRequired?"a payment method is required":"no payment method is required"}`,x.append(F)}}if(!e.charge){let o=a.createElement("p");o.textContent=p?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",x.append(o)}s.append(C,x,l,i),O.prepend(s),I=s,r=null}async function H(){if(!f)return;if(r=H,!M){let s=t.view,l=s?.document.buttons[f.actionId],i=s&&l?.type==="checkout"?q(l.product,f.selection,s.capabilities):null;if(!i)throw new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let C=await n.resolveOfferId?.({actionId:f.actionId,productVersionId:i});if(d)return;C!==void 0&&(f.offerId=C),M=!0}if(!m()){c.hidden=!1;return}let e=await t.preview(f);d||X(e)}function g(e="destroy"){d||(d=!0,S.abort(),A?.destroy(),t.destroy(),u.open&&u.close(),u.remove(),v.remove(),_ instanceof HTMLElement&&_.isConnected&&_.focus(),e==="dismiss"&&z(n.onDismiss))}L.onclick=()=>{m()&&g("dismiss")},u.addEventListener("cancel",e=>{e.preventDefault(),m()&&g("dismiss")}),c.onclick=()=>{r&&k(r)};try{if(D.type==="inline")b.append(v);else{let e={sm:420,md:640,lg:900};u.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in D?e[D.size]+"px":"100vw"}`,u.setAttribute("aria-label",y.document.name),u.append(v),b.append(u),m()&&u.showModal()}A=J(Q,{mode:"live",rendererUrl:t.webViewUrl,title:y.document.name,onAction(e,s={}){if(!m())return;let l=t.view,i=l?.document.buttons[e];if(i){if(i.type==="close"){k(async()=>{await n.onAction?.(e),g(n.onAction?"action":"dismiss")});return}if(i.type==="action"){r=async()=>{if(i.action.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(i.action.event)}else n.onOpenUrl?await n.onOpenUrl(i.action.url):a.defaultView?.location.assign(i.action.url);await n.onAction?.(e),r=null},k(r);return}if((t.quote||f)&&t.canReselect===!1){r=t.quote?async()=>E(await t.read()):H,k(r);return}if(!l||!q(i.product,s,l.capabilities)){U(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(f&&f.actionId!==e){U(new w("COMMAND_PENDING","Finish the current purchase"));return}f||(f={requestId:crypto.randomUUID(),actionId:e,selection:s},M=!1),k(H)}},onEscape:()=>{m()&&g("dismiss")},onError:e=>U(new Error(e))}),A.update(y.document.screen,y.document.screen.strings.defaultLocale,{capabilities:y.capabilities,serverInput:{bindings:[],answers:{}}}),await A.ready}catch(e){throw g(),e}return{check:h,host:{setSuspended(e){G=e,v.hidden=e,e&&u.open?u.close():!e&&!d&&D.type!=="inline"&&!u.open&&u.showModal()},destroy:g,refresh:async()=>{if(!m()){if(t.view)return t.view;throw new w("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await t.refresh();return d||A?.updateCapabilities(e.capabilities),e}}}}export{ie as showPaywall};
|