@tinkerlandai/indiana-sdk 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +44 -3
  3. package/README.zh-CN.md +8 -0
  4. package/dist/{ai-usage-BV-FlgWr.d.ts → ai-usage-DUlre7JC.d.ts} +1 -1
  5. package/dist/{api-B3FIE41b.d.ts → api-XDc4pRlN.d.ts} +63 -10
  6. package/dist/chunk-3F2NQOR2.js +1 -0
  7. package/dist/{chunk-BNU6IG3F.js → chunk-663UOBHL.js} +1 -1
  8. package/dist/chunk-BUDTHBFF.js +173 -0
  9. package/dist/chunk-EJTBSGLV.js +10 -0
  10. package/dist/{chunk-SHSNIJJM.js → chunk-F2GOIBDQ.js} +1 -1
  11. package/dist/chunk-RZBZ6LCT.js +4 -0
  12. package/dist/{chunk-2QPETWDX.js → chunk-SSHUBTT3.js} +1 -1
  13. package/dist/chunk-SSLZKIIU.js +1 -0
  14. package/dist/{configuration-sync-DNvKXHk-.d.ts → configuration-sync-Ce3dShy7.d.ts} +6 -1
  15. package/dist/content-2FCUY6XX.js +1 -0
  16. package/dist/{customer-page-WUQVK_tp.d.ts → customer-page-9B97Qdt_.d.ts} +21 -1
  17. package/dist/{funnel-local-client-wbz-4gFx.d.ts → funnel-local-client-CUGavICI.d.ts} +43 -23
  18. package/dist/{funnel-runtime-host-C5P5JTV3.js → funnel-runtime-host-ENRTSXPJ.js} +1 -1
  19. package/dist/index.d.ts +76 -26
  20. package/dist/index.js +1 -1
  21. package/dist/native-shell.js +1 -1
  22. package/dist/openrouter.d.ts +2 -2
  23. package/dist/openrouter.js +1 -1
  24. package/dist/page.d.ts +1 -1
  25. package/dist/page.js +1 -1
  26. package/dist/paywall-734GWAS4.js +1 -0
  27. package/dist/popup.d.ts +14 -4
  28. package/dist/popup.js +1 -1
  29. package/dist/react-native.d.ts +1 -1
  30. package/dist/react-native.js +1 -1
  31. package/dist/screen-renderer-DLXDQQKK.js +1 -0
  32. package/dist/server.d.ts +13 -13
  33. package/dist/server.js +1 -1
  34. package/dist/src-CLEFCTAU.js +1 -0
  35. package/dist/visual.js +2 -2
  36. package/package.json +1 -1
  37. package/dist/chunk-ANOOBDW5.js +0 -350
  38. package/dist/chunk-X747SY26.js +0 -4
  39. package/dist/chunk-Y32NPIYY.js +0 -1
  40. package/dist/chunk-ZT66RIFU.js +0 -10
  41. package/dist/content-J3FKZTGT.js +0 -1
  42. package/dist/paywall-3GIRKSHN.js +0 -1
  43. package/dist/screen-renderer-5FPYVSPW.js +0 -1
  44. package/dist/src-BMJCIMIF.js +0 -1
@@ -1 +1 @@
1
- import{nh as E,oh as M,ph as j,qh as O,rh as T}from"./chunk-ZT66RIFU.js";import{a as u}from"./chunk-SOQO2RDZ.js";import{x as w}from"./chunk-LMR2TM3X.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{Bh as E,Ch as M,Dh as j,Eh as O,Fh as T}from"./chunk-EJTBSGLV.js";import{a as u}from"./chunk-SOQO2RDZ.js";import{x as w}from"./chunk-LMR2TM3X.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -0,0 +1,4 @@
1
+ import{a as P}from"./chunk-DSPLGTQI.js";import{a as $}from"./chunk-EXCPE2XH.js";import{e as C,h as O,k as D}from"./chunk-KQCTDXVD.js";function N(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let n of document.cookie.split(";"))if(n.trim().startsWith(`${e}=`))try{t=decodeURIComponent(n.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function j(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function H(e=$){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var w=new Set,R;function Y(e){let t=()=>e();if(w.add(t),!R){let n=!0,r=history.pushState,o=history.replaceState,s=()=>{if(n)for(let i of[...w])w.has(i)&&P(i)},c=function(...i){r.apply(this,i),s()},a=function(...i){o.apply(this,i),s()};history.pushState=c,history.replaceState=a,addEventListener("popstate",s),addEventListener("hashchange",s),R=()=>{n=!1,history.pushState===c&&(history.pushState=r),history.replaceState===a&&(history.replaceState=o),removeEventListener("popstate",s),removeEventListener("hashchange",s)}}return()=>{w.delete(t)&&(w.size||(R?.(),R=void 0))}}var ee=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function te(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function B(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{c()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(f){return r("not sent",{error:f}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let p;try{p=await i.json()}catch{p=void 0}return te(p,a.length)?(p.rejected.length&&r("rejected",{rejected:p.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function c(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||ee([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let p=a.filter(f=>++f.attempts<5);p.length<a.length&&r("dropped after retries",{events:a.length-p.length}),t.unshift(...p),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?c():o(1e3)},flush:c}}async function q(e,t,n,r={}){let o=r.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let c=e.body.getReader(),a=[],i=0,p=!1,f=()=>{},g=new Promise((y,h)=>{f=()=>h(Error(o)),n.addEventListener("abort",f,{once:!0}),n.aborted&&f()});try{for(;;){let m=await Promise.race([c.read(),g]);if(m.done){p=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let y=new Uint8Array(i),h=0;for(let m of a)y.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(y))}finally{n.removeEventListener("abort",f),p||c.cancel().catch(()=>{}),c.releaseLock()}}async function V(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,c,a=new Promise((f,g)=>{c=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},p=new Promise((f,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let f=await Promise.race([r.read(),a,p]);if(f.done){s=!0;return}if(o+=f.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(c),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var fe=2*1024*1024,G=256*1024;async function J(e,t,n,r){let o=()=>{},s=new Promise((c,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let c=e(t,{...n,signal:r});return c.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([c,s])}finally{r.removeEventListener("abort",o)}}async function ge(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,s=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let c=await J(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},o.signal);await V(c,o.signal)}finally{clearTimeout(s)}}function M(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:c}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await J(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},c),p=await q(i,o,c);return c.throwIfAborted(),p}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
2
+ Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
+ plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
+ */function re(e,t){let n,r;try{n=new URL(e),r=new URL(t)}catch{return t}return n.searchParams.forEach((o,s)=>{r.searchParams.has(s)||r.searchParams.set(s,o)}),r.toString()}function ne(e,t){let n=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let s of["source","medium","campaign","term","content"]){let c=r.get(`utm_${s}`);c!==null&&(o[`utm${s[0].toUpperCase()}${s.slice(1)}`]=c)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(n)?"edge":/Chrome/.test(n)?"chrome":/Firefox/.test(n)?"firefox":/Safari/.test(n)?"safari":"unknown",deviceType:/Mobi/.test(n)?"mobile":"desktop",...o}}function oe(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function xe(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=H(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),r=M(async(u,d)=>{let l=await n(u,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),o=e.log?(u,d)=>P(e.log,u,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,c=N(e.deviceIdCookie??"indiana_did"),a=j(),i=null,p={...e.attributes??{}},f="",g=!1,y=!1,h=0,m=new Map,T=B({endpoint:`${s}/events`,fetch:n,log:o,label:"Exposure"}),S=T.flush,E={trackedExperiments:new Set,log:o,onExperimentViewed:(u,d)=>{e.trackExposures===!1||i?.trackExposures===!1||T.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:c,...a?{sessionId:a}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:u.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...ne(c,location),...p}};function Q(u){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return u.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function W(u,d){let l=e.configuration?.snapshot?.generation;f=u;let v=e.navigate??(x=>location.replace(x)),X=e.navigateDelay??(e.navigate?0:100),Z=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(x=>setTimeout(x,Z))]),new Promise(x=>setTimeout(x,X))]).then(()=>{!g&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&v(u)})}function b(){if(!(!i||g||e.configuration&&!e.configuration.fresh)){z();for(let u of i.experiments){if(Q(u)){o?.("Auto experiment blocked",{id:u.key});continue}let d;try{d=D(u,E)}catch(l){o?.("Skipping page experiment",{id:u.key,error:String(l)});continue}if(m.set(u.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=u.persistQueryString?re(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,u.urlPatterns??[])?o?.("Skipping redirect because original URL matches redirect URL",{id:u.key}):l!==f&&W(l,S())}break}}}}let k="",F=()=>{location.href!==k&&(k=location.href,f="",b())},L,I;function K(){L??=Y(F),addEventListener("pagehide",U)}let U=()=>{S()};async function A(){if(g)return!1;let u=++h,d;try{d=e.configuration?await e.configuration.pageExperiments():await r.read(s,G)}catch(v){if(g||u!==h)return!1;throw v}if(g||u!==h)return!1;let l=oe(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return i?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),i=l,E.savedGroups=O(l.savedGroups),!0}function _(){g||(I??=e.configuration?.subscribe(()=>{!g&&e.configuration?.fresh&&A().then(u=>{u&&b()}).catch(u=>o?.("Page configuration unavailable",{error:String(u)}))}),K(),k=location.href)}return{async start(){y||g||(y=!0,await A()&&(_(),b()))},async refresh(){await A()&&(y&&_(),f="",b())},setAttributes(u){p={...u},b()},getResults(){return new Map(m)},get generation(){return i?.generation??null},destroy(){g||(g=!0,h++,r.destroy(),I?.(),L?.(),removeEventListener("pagehide",U),i=null,m.clear(),S())}}}export{N as a,j as b,H as c,Y as d,fe as e,ge as f,M as g,re as h,ne as i,oe as j,xe as k};
@@ -1 +1 @@
1
- import{o as v,p as k,s as S}from"./chunk-ZT66RIFU.js";import{a as e}from"./chunk-SOQO2RDZ.js";import{a as C,j,m as _,p as P}from"./chunk-LMR2TM3X.js";import{b}from"./chunk-OBYJWIRB.js";import{a as L}from"./chunk-EXCPE2XH.js";var M={name:"@tinkerlandai/indiana-sdk",version:"0.8.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:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var U=Symbol("IndianaNoContent");function Z(p,H,q=URL){let l=p.configuration?.scope,R=p.scope??(l&&{projectId:l.projectId,environment:l.environment}),s=R?b.parse(R):void 0;if(s&&l&&(s.projectId!==l.projectId||s.environment!==l.environment))throw new e("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=new q(p.baseUrl??L);if(a.username||a.password||a.search||a.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let V=p.fetch??globalThis.fetch.bind(globalThis),f=p.timeoutMs??1e4;if(!Number.isFinite(f)||f<1||f>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let h=null,u=0,m=null,g=new Set;function A(){u+=1,h=null,m=null;for(let i of g)i.abort();g.clear()}async function x(i,K={},I="POST",D={}){let d=D.installationDetach===!0;if(d&&(i!=="push/installations/detach"||I!=="POST"))throw new e("INVALID_REQUEST","Installation authority only detaches this installation");if(!h&&!d)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let E=u,o=new AbortController;d||g.add(o);let w=()=>!d&&E!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),T,F=new Promise((n,r)=>{T=()=>r(w()),o.signal.addEventListener("abort",T,{once:!0})}),G=setTimeout(()=>o.abort(),f),X=async()=>{let n=await V(`${a.href.replace(/\/$/,"")}/api/v1/${i}`,{method:I,headers:{"Content-Type":"application/json",...d?{}:{Authorization:`Bearer ${h}`},[v]:S.current,[k]:M.version,...s?{"X-Indiana-Project":s.projectId,"X-Indiana-Environment":s.environment}:{}},body:I==="POST"?JSON.stringify(K):void 0,signal:o.signal,credentials:"omit",cache:"no-store",redirect:"error",...D.keepalive?{keepalive:!0}:{}});if(o.signal.aborted)throw w();let r;try{r=n.status===204?U:await n.json()}catch{throw o.signal.aborted?w():new e(n.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",n.status,n.headers.get("X-Request-Id")??void 0)}if(o.signal.aborted)throw w();if(!d&&E!==u)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!n.ok){let t=_.safeParse(r),c=t.success&&(!C.safeParse(t.data.error.code).success||j(t.data.error.code,n.status)),N=c?t.data.error.code:"HTTP_ERROR",O=P(N,n.status,{retryAfter:n.headers.get("Retry-After"),recovery:c?t.data.error.recovery:void 0,reason:c?t.data.error.reason:void 0});throw new e(N,c?t.data.error.message:"Indiana request failed",n.status,n.headers.get("X-Request-Id")??(t.success?t.data.requestId:void 0),{...O,...t.success&&t.data.error.retryable===!1?{retryable:!1}:{},...O.retryAfterSeconds===void 0&&t.success&&t.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:t.data.error.retryAfterSeconds}:{}})}if(n.headers.get(v)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(s&&r!==U){let t=r&&typeof r=="object"&&"scope"in r?r:r&&typeof r=="object"&&"configuration"in r?r.configuration:null;if(!t||typeof t!="object"||!("scope"in t))throw new e("INVALID_RESPONSE","Response is missing its App/environment scope");let c=b.safeParse(t.scope);if(!c.success||c.data.projectId!==s.projectId||c.data.environment!==s.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let y=n.headers.get("X-Indiana-Telemetry-Subject");if(y){if(!/^[a-f0-9]{64}$/.test(y))throw new e("INVALID_RESPONSE","Invalid telemetry identity");m!==y&&(m=y,H?.(m))}return r};try{return await Promise.race([X(),F])}catch(n){throw!d&&E!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):n instanceof e?n:new e(o.signal.aborted?"TIMEOUT":"NETWORK_ERROR",o.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(G),o.signal.removeEventListener("abort",T),g.delete(o)}}return{subjectKey:()=>m,identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");A(),h=i},reset:A,request:x}}export{Z as a};
1
+ import{o as v,p as k,s as S}from"./chunk-EJTBSGLV.js";import{a as e}from"./chunk-SOQO2RDZ.js";import{a as C,j,m as _,p as P}from"./chunk-LMR2TM3X.js";import{b}from"./chunk-OBYJWIRB.js";import{a as L}from"./chunk-EXCPE2XH.js";var M={name:"@tinkerlandai/indiana-sdk",version:"0.8.4",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var U=Symbol("IndianaNoContent");function Z(p,H,q=URL){let l=p.configuration?.scope,R=p.scope??(l&&{projectId:l.projectId,environment:l.environment}),s=R?b.parse(R):void 0;if(s&&l&&(s.projectId!==l.projectId||s.environment!==l.environment))throw new e("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=new q(p.baseUrl??L);if(a.username||a.password||a.search||a.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let V=p.fetch??globalThis.fetch.bind(globalThis),f=p.timeoutMs??1e4;if(!Number.isFinite(f)||f<1||f>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let h=null,u=0,m=null,g=new Set;function A(){u+=1,h=null,m=null;for(let i of g)i.abort();g.clear()}async function x(i,K={},I="POST",D={}){let d=D.installationDetach===!0;if(d&&(i!=="push/installations/detach"||I!=="POST"))throw new e("INVALID_REQUEST","Installation authority only detaches this installation");if(!h&&!d)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let E=u,o=new AbortController;d||g.add(o);let w=()=>!d&&E!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),T,F=new Promise((n,r)=>{T=()=>r(w()),o.signal.addEventListener("abort",T,{once:!0})}),G=setTimeout(()=>o.abort(),f),X=async()=>{let n=await V(`${a.href.replace(/\/$/,"")}/api/v1/${i}`,{method:I,headers:{"Content-Type":"application/json",...d?{}:{Authorization:`Bearer ${h}`},[v]:S.current,[k]:M.version,...s?{"X-Indiana-Project":s.projectId,"X-Indiana-Environment":s.environment}:{}},body:I==="POST"?JSON.stringify(K):void 0,signal:o.signal,credentials:"omit",cache:"no-store",redirect:"error",...D.keepalive?{keepalive:!0}:{}});if(o.signal.aborted)throw w();let r;try{r=n.status===204?U:await n.json()}catch{throw o.signal.aborted?w():new e(n.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",n.status,n.headers.get("X-Request-Id")??void 0)}if(o.signal.aborted)throw w();if(!d&&E!==u)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!n.ok){let t=_.safeParse(r),c=t.success&&(!C.safeParse(t.data.error.code).success||j(t.data.error.code,n.status)),N=c?t.data.error.code:"HTTP_ERROR",O=P(N,n.status,{retryAfter:n.headers.get("Retry-After"),recovery:c?t.data.error.recovery:void 0,reason:c?t.data.error.reason:void 0});throw new e(N,c?t.data.error.message:"Indiana request failed",n.status,n.headers.get("X-Request-Id")??(t.success?t.data.requestId:void 0),{...O,...t.success&&t.data.error.retryable===!1?{retryable:!1}:{},...O.retryAfterSeconds===void 0&&t.success&&t.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:t.data.error.retryAfterSeconds}:{}})}if(n.headers.get(v)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(s&&r!==U){let t=r&&typeof r=="object"&&"scope"in r?r:r&&typeof r=="object"&&"configuration"in r?r.configuration:null;if(!t||typeof t!="object"||!("scope"in t))throw new e("INVALID_RESPONSE","Response is missing its App/environment scope");let c=b.safeParse(t.scope);if(!c.success||c.data.projectId!==s.projectId||c.data.environment!==s.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let y=n.headers.get("X-Indiana-Telemetry-Subject");if(y){if(!/^[a-f0-9]{64}$/.test(y))throw new e("INVALID_RESPONSE","Invalid telemetry identity");m!==y&&(m=y,H?.(m))}return r};try{return await Promise.race([X(),F])}catch(n){throw!d&&E!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):n instanceof e?n:new e(o.signal.aborted?"TIMEOUT":"NETWORK_ERROR",o.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(G),o.signal.removeEventListener("abort",T),g.delete(o)}}return{subjectKey:()=>m,identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");A(),h=i},reset:A,request:x}}export{Z as a};
@@ -0,0 +1 @@
1
+ var n=new WeakMap;function u(t,o){return n.set(t,o),()=>n.delete(t)}function c(t){let o=t.defaultView?.HTMLElement,e=t.activeElement;for(let r=0;r<16&&e?.shadowRoot?.activeElement;r++)e=e.shadowRoot.activeElement;let s=e?n.get(e)?.():void 0;return()=>{!e?.isConnected||!o||!(e instanceof o)||(e.focus({preventScroll:!0}),s?.())}}export{u as a,c as b};
@@ -1311,6 +1311,11 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1311
1311
  } | {
1312
1312
  type: "plans";
1313
1313
  planIds: string[];
1314
+ } | {
1315
+ type: "merchandise";
1316
+ scope: {
1317
+ type: "selected" | "all" | "condition";
1318
+ };
1314
1319
  };
1315
1320
  displayCopy: {
1316
1321
  defaultLocale: string;
@@ -1571,7 +1576,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1571
1576
  entry: string;
1572
1577
  nodes: {
1573
1578
  id: string;
1574
- type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
1579
+ type: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
1575
1580
  outputs: Record<string, string>;
1576
1581
  writes: Record<string, string>;
1577
1582
  resources: {
@@ -0,0 +1 @@
1
+ import{f as _,j as F}from"./chunk-BUDTHBFF.js";import{b as q}from"./chunk-SSLZKIIU.js";import"./chunk-SSHUBTT3.js";import{cd as U}from"./chunk-EJTBSGLV.js";import{a as d}from"./chunk-SOQO2RDZ.js";import{Eb as M,Mb as z,Ob as N,tb as P}from"./chunk-LMR2TM3X.js";import{a as v}from"./chunk-DSPLGTQI.js";import"./chunk-OBYJWIRB.js";import"./chunk-EXCPE2XH.js";import{a as O}from"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";import{z as p}from"zod";var V=new WeakMap;function Q(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:O}[r.type];return r.nullable?t.nullable():t}async function ne(r,t){return W(r,t,!1)}async function re(r,t){return W(r,t,!0)}async function W(r,t,w){t.signal?.throwIfAborted();let T=U.parse(t.content),o=T.document;if(V.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),O).parse(t.inputs??{});if(Object.keys(f).length>40)throw new d("INVALID_REQUEST","Too many content inputs");for(let[e,s]of Object.entries(f))z.parse({[e]:s});if(Object.keys(f).some(e=>!Object.hasOwn(o.contract.inputs,e)))throw new d("INVALID_REQUEST","Undeclared content input");for(let[e,s]of Object.entries(o.contract.inputs))if(Object.hasOwn(f,e))Q(s).parse(f[e]);else if(s.required)throw new d("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(o.contract.outputs))if(typeof t.actions[e]!="function")throw new d("INVALID_REQUEST",`Missing host handler for ${e}`);let $=N.parse(t.bindings??[]),a=r.ownerDocument,L,k=o.kind==="popup",n=k?a.createElement("dialog"):null,i=a.createElement("div");if(i.dataset.indianaContent=o.kind,i.setAttribute("aria-label",o.name),i.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",o.name);let e=o.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${P[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(i),r.append(n)}else r.append(i);let c=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||a.defaultView?.innerWidth||800}px`);let B=w?_(n??i):()=>{},H,x,A=new Promise((e,s)=>{H=e,x=s});A.catch(()=>{});let l=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let y;function m(){c||(c=!0,t.signal?.removeEventListener("abort",m),x(new Error("Content preparation cancelled")),y?.destroy(),n?.close(),n?.remove(),i.remove(),V.delete(r),n&&L?.())}let S=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=a.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),e.style.cssText="position:absolute;right:8px;top:8px;width:30px;height:30px;z-index:1",e.addEventListener("click",S),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),S()});async function D(){if(c||!g||C||!l)return;let e=l;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),l=null}catch(s){v(t.onError,s)}finally{C=!1,c||i.removeAttribute("aria-busy")}}function R(){if(c)throw new d("CONFLICT","Content host has been destroyed");g||(L=q(a),B(),w&&!n&&(i.style.width="100%"),n?.showModal(),g=!0)}try{w||R(),y=F(i,{mode:"live",title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||a.defaultView?.innerHeight||800:void 0,onRendered:H,onError:u=>{let I=new Error(u);x(I),v(t.onError,I)},onEscape:k?S:void 0,onAction:(u,I,J)=>{if(c||!g||C||l)return;let h=o.screen.actions.find(b=>b.id===u),j=o.contract.outputs[u];if(!(h?.type!=="event"||!j))try{let b=Q(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);l={requestId:crypto.randomUUID(),contentVersionId:T.id,actionId:u,event:h.event,value:b,selection:I??{},answers:J??{},requestedClose:h.close},D()}catch(b){v(t.onError,b)}}});let e={destroy:m,show:R,get pendingAction(){return l?structuredClone(l):null},retryAction:D,updateCapabilities:u=>y?.updateCapabilities(u)};V.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=M(E,[t.locale,...a.defaultView?.navigator.languages??[]]);if(y.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:$,answers:{},values:f}}),await Promise.race([y.ready,A]),w&&await A,c)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ne as mountContent,re as prepareContent};
@@ -311,6 +311,17 @@ declare const couponInputSchema: z.ZodObject<{
311
311
  }, z.core.$strict>, z.ZodObject<{
312
312
  type: z.ZodLiteral<"plans">;
313
313
  planIds: z.ZodArray<z.ZodUUID>;
314
+ }, z.core.$strict>, z.ZodObject<{
315
+ type: z.ZodLiteral<"merchandise">;
316
+ scope: z.ZodDiscriminatedUnion<[z.ZodObject<{
317
+ type: z.ZodLiteral<"all">;
318
+ }, z.core.$strict>, z.ZodObject<{
319
+ type: z.ZodLiteral<"selected">;
320
+ merchandiseIds: z.ZodArray<z.ZodUUID>;
321
+ }, z.core.$strict>, z.ZodObject<{
322
+ type: z.ZodLiteral<"condition">;
323
+ condition: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
324
+ }, z.core.$strict>], "type">;
314
325
  }, z.core.$strict>], "type">;
315
326
  eligibility: z.ZodObject<{
316
327
  firstPurchaseOnly: z.ZodBoolean;
@@ -397,6 +408,15 @@ declare const offerSchema: z.ZodObject<{
397
408
  }, z.core.$strict>, z.ZodObject<{
398
409
  type: z.ZodLiteral<"plans">;
399
410
  planIds: z.ZodArray<z.ZodUUID>;
411
+ }, z.core.$strict>, z.ZodObject<{
412
+ type: z.ZodLiteral<"merchandise">;
413
+ scope: z.ZodObject<{
414
+ type: z.ZodEnum<{
415
+ selected: "selected";
416
+ all: "all";
417
+ condition: "condition";
418
+ }>;
419
+ }, z.core.$strict>;
400
420
  }, z.core.$strict>], "type">;
401
421
  }, z.core.$strict>;
402
422
  }, z.core.$strict>;
@@ -404,8 +424,8 @@ type Offer = z.infer<typeof offerSchema>;
404
424
  /** 领取失败的原因:未生效 / 不在有效期 / 不符合标签 / 不是首购 / 已达每人上限 / 已领完。 */
405
425
  declare const offerUnavailableReasonSchema: z.ZodEnum<{
406
426
  unavailable: "unavailable";
407
- claim_disabled: "claim_disabled";
408
427
  inactive: "inactive";
428
+ claim_disabled: "claim_disabled";
409
429
  outside_window: "outside_window";
410
430
  not_targeted: "not_targeted";
411
431
  not_first_purchase: "not_first_purchase";
@@ -1,10 +1,10 @@
1
- import { I as InvoiceModeParams, b as InvoiceModeParamsInput, A as ApiInput } from './api-B3FIE41b.js';
1
+ import { I as InvoiceModeParams, b as InvoiceModeParamsInput, A as ApiInput } from './api-XDc4pRlN.js';
2
2
  import { S as StackNode, d as ScreenSelection } from './screen-BpAejkn0.js';
3
3
  import * as zod from 'zod';
4
4
  import { z } from 'zod';
5
5
  import { E as EvaluationContext, J as JsonValue, F as FeatureResult } from './growth-rules-B4YYy64R.js';
6
6
  import { a as PushHost, S as Scope } from './errors-C8lRYZ0n.js';
7
- import { C as ConfigurationSync } from './configuration-sync-DNvKXHk-.js';
7
+ import { C as ConfigurationSync } from './configuration-sync-Ce3dShy7.js';
8
8
 
9
9
  declare const currencySchema: z.ZodEnum<{
10
10
  USD: "USD";
@@ -261,12 +261,12 @@ declare const funnelRunViewSchema: z.ZodObject<{
261
261
  feature: "feature";
262
262
  split: "split";
263
263
  condition: "condition";
264
+ entry: "entry";
264
265
  coupon: "coupon";
265
266
  end: "end";
266
267
  screen: "screen";
267
268
  offering: "offering";
268
269
  coupons: "coupons";
269
- entry: "entry";
270
270
  external_page: "external_page";
271
271
  wait: "wait";
272
272
  }>;
@@ -2304,12 +2304,12 @@ declare const funnelRuntimeResponseSchema: z.ZodObject<{
2304
2304
  feature: "feature";
2305
2305
  split: "split";
2306
2306
  condition: "condition";
2307
+ entry: "entry";
2307
2308
  coupon: "coupon";
2308
2309
  end: "end";
2309
2310
  screen: "screen";
2310
2311
  offering: "offering";
2311
2312
  coupons: "coupons";
2312
- entry: "entry";
2313
2313
  external_page: "external_page";
2314
2314
  wait: "wait";
2315
2315
  }>;
@@ -5398,12 +5398,12 @@ declare const funnelConfigurationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
5398
5398
  feature: "feature";
5399
5399
  split: "split";
5400
5400
  condition: "condition";
5401
+ entry: "entry";
5401
5402
  coupon: "coupon";
5402
5403
  end: "end";
5403
5404
  screen: "screen";
5404
5405
  offering: "offering";
5405
5406
  coupons: "coupons";
5406
- entry: "entry";
5407
5407
  external_page: "external_page";
5408
5408
  wait: "wait";
5409
5409
  }>;
@@ -5443,12 +5443,12 @@ declare const funnelConfigurationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
5443
5443
  feature: "feature";
5444
5444
  split: "split";
5445
5445
  condition: "condition";
5446
+ entry: "entry";
5446
5447
  coupon: "coupon";
5447
5448
  end: "end";
5448
5449
  screen: "screen";
5449
5450
  offering: "offering";
5450
5451
  coupons: "coupons";
5451
- entry: "entry";
5452
5452
  external_page: "external_page";
5453
5453
  wait: "wait";
5454
5454
  }>;
@@ -5662,12 +5662,12 @@ declare const funnelLocalConfigurationSchema: z.ZodObject<{
5662
5662
  feature: "feature";
5663
5663
  split: "split";
5664
5664
  condition: "condition";
5665
+ entry: "entry";
5665
5666
  coupon: "coupon";
5666
5667
  end: "end";
5667
5668
  screen: "screen";
5668
5669
  offering: "offering";
5669
5670
  coupons: "coupons";
5670
- entry: "entry";
5671
5671
  external_page: "external_page";
5672
5672
  wait: "wait";
5673
5673
  }>;
@@ -7461,6 +7461,10 @@ declare const evaluateFeaturesResultSchema: z.ZodObject<{
7461
7461
  stickyBucketUsed: z.ZodOptional<z.ZodBoolean>;
7462
7462
  }, z.core.$strict>>;
7463
7463
  }, z.core.$strict>>;
7464
+ merchandiseContext: z.ZodOptional<z.ZodObject<{
7465
+ merchandiseId: z.ZodUUID;
7466
+ merchandise: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
7467
+ }, z.core.$strict>>;
7464
7468
  }, z.core.$strict>;
7465
7469
 
7466
7470
  type FunnelNodeEvaluationContext = Pick<EvaluationContext, "attributes" | "stickyBucketAssignmentDocs" | "saveStickyBucketAssignmentDoc" | "onFeatureUsage" | "onExperimentViewed">;
@@ -8567,8 +8571,14 @@ type FeatureClientOptions = {
8567
8571
  attributes?: Record<string, JsonValue>;
8568
8572
  scope: FeaturePayload["scope"];
8569
8573
  onError?: (error: unknown) => void;
8570
- onFeatureUsage?: EvaluationContext["onFeatureUsage"];
8571
- onExperimentViewed?: EvaluationContext["onExperimentViewed"];
8574
+ onFeatureUsage?: (...args: [
8575
+ ...Parameters<NonNullable<EvaluationContext["onFeatureUsage"]>>,
8576
+ Record<string, JsonValue>
8577
+ ]) => void;
8578
+ onExperimentViewed?: (...args: [
8579
+ ...Parameters<NonNullable<EvaluationContext["onExperimentViewed"]>>,
8580
+ Record<string, JsonValue>
8581
+ ]) => void;
8572
8582
  stickyBucketAssignmentDocs?: EvaluationContext["stickyBucketAssignmentDocs"];
8573
8583
  saveStickyBucketAssignmentDoc?: EvaluationContext["saveStickyBucketAssignmentDoc"];
8574
8584
  };
@@ -10205,6 +10215,11 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
10205
10215
  } | {
10206
10216
  type: "plans";
10207
10217
  planIds: string[];
10218
+ } | {
10219
+ type: "merchandise";
10220
+ scope: {
10221
+ type: "selected" | "all" | "condition";
10222
+ };
10208
10223
  };
10209
10224
  displayCopy: {
10210
10225
  defaultLocale: string;
@@ -10465,7 +10480,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
10465
10480
  entry: string;
10466
10481
  nodes: {
10467
10482
  id: string;
10468
- type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
10483
+ type: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
10469
10484
  outputs: Record<string, string>;
10470
10485
  writes: Record<string, string>;
10471
10486
  resources: {
@@ -10539,7 +10554,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
10539
10554
  revision: number;
10540
10555
  visit: number;
10541
10556
  nodeId: string;
10542
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
10557
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
10543
10558
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
10544
10559
  stopped: boolean;
10545
10560
  canBack: boolean;
@@ -11705,7 +11720,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
11705
11720
  revision: number;
11706
11721
  visit: number;
11707
11722
  nodeId: string;
11708
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
11723
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
11709
11724
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
11710
11725
  stopped: boolean;
11711
11726
  canBack: boolean;
@@ -13386,7 +13401,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
13386
13401
  revision: number;
13387
13402
  visit: number;
13388
13403
  nodeId: string;
13389
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
13404
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
13390
13405
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
13391
13406
  stopped: boolean;
13392
13407
  canBack: boolean;
@@ -14805,7 +14820,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
14805
14820
  revision: number;
14806
14821
  visit: number;
14807
14822
  nodeId: string;
14808
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
14823
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
14809
14824
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
14810
14825
  stopped: boolean;
14811
14826
  canBack: boolean;
@@ -16222,7 +16237,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
16222
16237
  revision: number;
16223
16238
  visit: number;
16224
16239
  nodeId: string;
16225
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
16240
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
16226
16241
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
16227
16242
  stopped: boolean;
16228
16243
  canBack: boolean;
@@ -17642,7 +17657,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
17642
17657
  revision: number;
17643
17658
  visit: number;
17644
17659
  nodeId: string;
17645
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
17660
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
17646
17661
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
17647
17662
  stopped: boolean;
17648
17663
  canBack: boolean;
@@ -20310,6 +20325,11 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
20310
20325
  } | {
20311
20326
  type: "plans";
20312
20327
  planIds: string[];
20328
+ } | {
20329
+ type: "merchandise";
20330
+ scope: {
20331
+ type: "selected" | "all" | "condition";
20332
+ };
20313
20333
  };
20314
20334
  displayCopy: {
20315
20335
  defaultLocale: string;
@@ -20570,7 +20590,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
20570
20590
  entry: string;
20571
20591
  nodes: {
20572
20592
  id: string;
20573
- type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
20593
+ type: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
20574
20594
  outputs: Record<string, string>;
20575
20595
  writes: Record<string, string>;
20576
20596
  resources: {
@@ -20644,7 +20664,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
20644
20664
  revision: number;
20645
20665
  visit: number;
20646
20666
  nodeId: string;
20647
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
20667
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
20648
20668
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
20649
20669
  stopped: boolean;
20650
20670
  canBack: boolean;
@@ -21810,7 +21830,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
21810
21830
  revision: number;
21811
21831
  visit: number;
21812
21832
  nodeId: string;
21813
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
21833
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
21814
21834
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
21815
21835
  stopped: boolean;
21816
21836
  canBack: boolean;
@@ -23491,7 +23511,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
23491
23511
  revision: number;
23492
23512
  visit: number;
23493
23513
  nodeId: string;
23494
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
23514
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
23495
23515
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
23496
23516
  stopped: boolean;
23497
23517
  canBack: boolean;
@@ -24910,7 +24930,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
24910
24930
  revision: number;
24911
24931
  visit: number;
24912
24932
  nodeId: string;
24913
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
24933
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
24914
24934
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
24915
24935
  stopped: boolean;
24916
24936
  canBack: boolean;
@@ -26327,7 +26347,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
26327
26347
  revision: number;
26328
26348
  visit: number;
26329
26349
  nodeId: string;
26330
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
26350
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
26331
26351
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
26332
26352
  stopped: boolean;
26333
26353
  canBack: boolean;
@@ -27747,7 +27767,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
27747
27767
  revision: number;
27748
27768
  visit: number;
27749
27769
  nodeId: string;
27750
- nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
27770
+ nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
27751
27771
  status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
27752
27772
  stopped: boolean;
27753
27773
  canBack: boolean;
@@ -1 +1 @@
1
- import{a as X}from"./chunk-DSPLGTQI.js";import{a as le,b as ue,d as de}from"./chunk-GRLMT5PR.js";import"./chunk-2QPETWDX.js";import{Hg as re,ue as ae}from"./chunk-ZT66RIFU.js";import{a as u}from"./chunk-SOQO2RDZ.js";import{Hb as se}from"./chunk-LMR2TM3X.js";import"./chunk-OBYJWIRB.js";import"./chunk-EXCPE2XH.js";import"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";function ce(e){let C=e.view;if(!C?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let n=C.paywall.receiptId,P=C.nodeId,h=C.visit,o=C.paywall.resolution,k=o,s="document"in o?o:null;function v(i){if(!le(i,o))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let a=C.paywall.quote,R=C.paywall.operation,S=!1,T=new AbortController,l=C.paywall.purchaseRequestId,r=0,f=C.paywall.selectionGeneration??0,E=C.paywall.canReselect===!0,y=null,O=new Map,U=new Map;function G(i){if(i.purchase&&i.purchase.receiptId!==n)throw new u("INVALID_RESPONSE","Purchase receipt changed");let w=i.run.paywall;return i.purchase??(w?.receiptId===n?w:null)}function F(){if(S)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,w,c){if(F(),w!==r||c!==void 0&&a?.operationId!==c)return!1;let I=f,d=i.run.paywall;if(d?.receiptId===n){if((d.selectionGeneration??0)<f)return!1;f=d.selectionGeneration??0,E=d.canReselect===!0,v(d.resolution)}let m=G(i),p=f>I,N=p?m?.quote??null:m?.quote??a,q=m?.operation??(N?.operationId===a?.operationId?R:null);return N&&q&&ue(q,{operationId:N.operationId},"Purchase operation changed"),d?.receiptId===n&&(k=d.resolution,s="document"in k?k:s?{...k,document:s.document,offering:s.offering}:null),(p||N?.operationId!==a?.operationId)&&(r++,d?.receiptId===n&&(l=d.purchaseRequestId)),a=N,R=de(R,q,!0),!0}function $(i,w,c){return new Promise((I,d)=>{let m=!1,p=()=>{clearTimeout(D),T.signal.removeEventListener("abort",J)},N=z=>{m||(m=!0,p(),I(z))},q=z=>{m||(m=!0,p(),d(z))},J=()=>q(new u("IDENTITY_CHANGED","Paywall presentation has closed")),D=setTimeout(()=>q(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,c)),Math.max(0,w-Date.now()));T.signal.addEventListener("abort",J,{once:!0}),T.signal.aborted&&J(),i.then(N,q)})}function j(i){return new Promise(w=>{let c=()=>{clearTimeout(I),T.signal.removeEventListener("abort",c),w()},I=setTimeout(c,i);T.signal.addEventListener("abort",c,{once:!0}),T.signal.aborted&&c()})}async function A(i,w,c){F();let I=O.get(i);if(!I){let p=e.pendingCommands?.find(N=>N.requestId===i)??e.pendingCommand;if(p?.operation==="submit"&&p.requestId===i&&p.nodeId===P&&p.visit===h){w.type==="paywall_quote"&&p.input.type==="paywall_quote"&&p.input.predecessor&&!w.predecessor&&(w={...w,predecessor:p.input.predecessor});let N=re.parse(p),q=re.parse({...p,input:w});if(q.operation!=="submit"||N.operation!=="submit"||JSON.stringify(q.input)!==JSON.stringify(N.input))throw new u("CONFLICT","A restored purchase request cannot change its input");w=q.input,I=N,O.set(i,I)}}if(I){if(JSON.stringify(I.input)!==JSON.stringify(w))throw new u("CONFLICT","A purchase request cannot change its input")}else{let p=e.view;if(!p||p.nodeId!==P||p.visit!==h||p.paywall?.receiptId!==n)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");I={operation:"submit",requestId:i,nodeId:P,visit:h,revision:p.revision,input:w},O.set(i,I)}let d=Date.now()+3e4,m=await $(e.submit(I),d,i);for(;m.run.pendingRequest?.requestId===i&&Date.now()<d&&!S&&(await j(Math.min(1e3,d-Date.now())),!(S||Date.now()>=d));)m=await $(e.resume(i),d,i);if(S)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(m.run.pendingRequest?.requestId===i)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,i);if(!_(m,c,w.type==="paywall_confirm"||w.type==="paywall_cancel"?w.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed")}async function Q(i){if(!a)throw new u("INVALID_REQUEST","A quoted purchase is required");let w=`${i}:${a.operationId}`,c=U.get(w);if(!c){let I=i==="confirm"?"paywall_confirm":"paywall_cancel",d=e.pendingCommands?.find(m=>m.operation==="submit"&&m.input.type===I&&"operationId"in m.input&&m.input.operationId===a.operationId)??e.pendingCommand;c=d?.operation==="submit"&&d.input.type===I&&"operationId"in d.input&&d.input.operationId===a.operationId?d.requestId:crypto.randomUUID(),U.set(w,c)}if(await A(c,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:a.operationId},r),!R)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(R)}return{get view(){return structuredClone(s)},get quote(){return a?structuredClone(a):null},get operation(){return R?structuredClone(R):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return E},async refresh(){F();let i=r,w=await e.get();if(_(w,i),w.run.paywall?.receiptId!==n)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");if(!s){if("document"in k||!e.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let c=await e.resolvePaywall(k);F(),v(c),s={...k,document:c.document,offering:c.offering}}return structuredClone(s)},preview(i){if(!s)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(l&&l!==i.requestId&&(y||!E))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));if(l===i.requestId&&y)return y;let w=s.document.buttons[i.actionId],c=w?.type==="checkout"?ae(w.product,i.selection,s.capabilities):null;if(!c)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=l!==i.requestId&&f>0?{operationId:a?.operationId??null,generation:f}:void 0;if(I&&(!E||f<=0))return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));l!==i.requestId&&r++;let d=r;l=i.requestId;let m=(async()=>{if(await A(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:c,...I?{predecessor:I}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}},d),!a)throw new u("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(a)})();return y=m,m.then(()=>{y===m&&(y=null)},p=>{y===m&&(y=null),l===i.requestId&&e.pendingCommand?.requestId!==i.requestId&&p instanceof u&&p.status!==void 0&&p.status<500&&![401,425].includes(p.status)&&(l=null)}),m},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),async read(){if(F(),!a)throw new u("INVALID_REQUEST","A quoted purchase is required");let i=a.operationId,w=r,c=e.pendingCommands?.find(p=>p.operation==="submit"&&(p.input.type==="paywall_confirm"||p.input.type==="paywall_cancel")&&p.input.operationId===i)??e.pendingCommand;c?.operation==="submit"&&(c.input.type==="paywall_confirm"||c.input.type==="paywall_cancel")&&c.input.operationId===i&&await e.settle?.(c.requestId);let I=await e.get(void 0,{receiptId:n,operationId:i});F();let d=G(I);if(d?.quote&&d.quote.operationId!==i||d?.operation&&d.operation.operationId!==i)throw new u("INVALID_RESPONSE","Purchase operation changed");let m=_(I,w,i)?R:d?.operation;if(!m)throw new u("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(m)},destroy(){S=!0,T.abort(),O.clear(),U.clear()}}}function pe(e){let C=new Set,n=new Set,P=null;function h(o){if(e.reviewing||C.has(o)||n.has(o)||e.stopped)return;n.add(o);let k=async()=>{if(e.reviewing||e.stopped||e.key!==o){n.delete(o);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{k()},250);return}let s=(async()=>{let a=e.client.view,R=e.expected(),S=R.requestId,T=!1;try{await e.client.submit({operation:"shown",...R})}catch(l){if(!(l instanceof u)||l.code!=="CONFLICT"||l.status!==409||e.client.pendingCommand)throw l;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==o||!r||!a||r.id!==a.id||r.source.versionId!==a.source.versionId||r.nodeId!==R.nodeId||r.visit!==R.visit||r.revision<=R.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw l;let f=e.expected();S=f.requestId,await e.client.submit({operation:"shown",...f})}for(;!e.stopped&&e.key===o&&e.client.pendingCommand?.requestId===S;){if(!e.client.settle)throw new u("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(S),T=!0,e.client.pendingCommand?.requestId===S&&await new Promise(l=>setTimeout(l,1500))}e.stopped||e.key!==o||(T&&await e.client.get(),!(e.stopped||e.key!==o)&&C.add(o))})();P=s;let v=()=>{P===s&&(P=null),n.delete(o)};s.then(v,a=>{v(),e.busy||e.fail(a)})};k()}return{report:h,get inFlight(){return P}}}function fe(e){let C={},n=new Map;async function P(h){let o=e.client.view,k=o?.screen,s=k?.customerData.nodes[h.nodeId];if(e.stopped||e.busy||!o||!k||!s)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(h.action)){let r=e.document,f=r?se(r,h.nodeId):null,E=f?.type==="customer_data"?f.data.outputs?.[h.action]:void 0;E&&k.outputs.includes(E)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:E,answers:e.answers,selection:h.value?{[h.nodeId]:h.value}:{}}})):await e.onIntent?.(h,o);return}let a=h.action.startsWith("sources_")?s.resources.find(r=>r.key===h.value):null;if(h.action.startsWith("sources_")&&!a)throw new u("INVALID_REQUEST","Choose a current resource");let R=`${o.visit}:${h.nodeId}:${a?.key??""}`,S=n.get(R)??[null],l=C[h.nodeId]??{page:1,after:null,filter:"all",...a?{resourceKey:a.key}:{}};if(h.action==="filter"){let r=h.value;if(!r||!(s.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new u("INVALID_REQUEST","Unknown data filter");l={page:1,after:null,filter:r},S.splice(0,S.length,null)}else if(h.action==="next"||h.action==="sources_next"){let r=a?.sources.at(-1),f=a?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:k.dataCursors[h.nodeId];if(!f||!a&&!s.hasNext)return;S[l.page]=f,l={...l,page:l.page+1,after:f}}else if(h.action==="previous"||h.action==="sources_previous"){if(l.page<=1)return;l={...l,page:l.page-1,after:S[l.page-2]??null}}n.set(R,S),C={...C,[h.nodeId]:l},await e.perform(()=>e.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:C}))}return{get queries(){return C},intent:P,reset(){C={},n.clear()}}}function we(e){let{doc:C,holder:n,reviewHolder:P,mountScreenPreview:h}=e,o=!1,k,s=0,v=null,a="",R=new Map,S=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function T(r){if(e.stopped||!e.client.review)return;o||(a=S(e.client.view),R.set(a,structuredClone(e.answers))),o=!0,k=r,n.hidden=!0,e.suspend(!0),P.hidden=!1;let f=++s;try{let E=await e.client.review(r);if(e.stopped||f!==s||!o)return;if(!E.review)throw new u("INVALID_RESPONSE","Historical projection is missing");v?.destroy(),v=null,P.replaceChildren();let y=E.run.locale.startsWith("zh"),O=C.createElement("p");O.textContent=y?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(O);for(let[F,_]of E.review.pages.entries()){let $=C.createElement("button");$.type="button",$.textContent=y?`\u7B2C ${F+1} \u9875`:`Page ${F+1}`,$.onclick=()=>{T(_.receiptId)},P.append($)}if(E.review.page){let F=E.review.page,_=C.createElement("div");if(_.inert=!0,P.append(_),v=h(_,{mode:"live",rendererUrl:e.client.webViewUrl,title:F.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{l()}}),v.update(F.document,E.run.locale,{serverInput:{bindings:F.inputs,answers:F.answers,values:F.values}}),await v.ready,e.stopped||f!==s||!o)return}let U=y?{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"},G=y?{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 F of[...E.review.coupons.map((_,$)=>`${y?"\u4F18\u60E0\u5238":"Coupon"} ${$+1}: ${U[_.status]}`),...E.review.purchases.map((_,$)=>`${y?"\u8D2D\u4E70":"Purchase"} ${$+1}: ${G[_.status]}`)]){let _=C.createElement("p");_.textContent=F,P.append(_)}e.client.view&&await e.enqueue(e.client.view)}catch(E){if(f!==s||e.stopped)return;v?.destroy(),v=null,P.replaceChildren(),e.fail(E)}}async function l(){if(!o||e.stopped||!e.client.review)return;let r=++s;try{if(await e.client.review(),e.stopped||r!==s)return;o=!1,s++,v?.destroy(),v=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1;let f=e.client.view;S(f)!==a?(R.set(a,structuredClone(e.answers)),e.resetScreen()):(R.delete(a),e.suspend(!1)),f&&await e.enqueue(f)}catch(f){if(r!==s||e.stopped)return;v?.destroy(),v=null,P.replaceChildren(),e.fail(f)}}return{get active(){return o},get receipt(){return k},open:T,exit:l,get drafts(){return new Map([...R].map(([r,f])=>[r,structuredClone(f)]))},stop(){o=!1,s++,v?.destroy(),v=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1}}}async function Ue(e,C){let n=C,{mountScreenPreview:P}=await import("./screen-renderer-5FPYVSPW.js"),{showPaywall:h}=await import("./paywall-3GIRKSHN.js"),o=e.ownerDocument,k=o.activeElement,s=o.createElement("section"),v=o.createElement("div"),a=o.createElement("div"),R=o.createElement("div"),S=o.createElement("button");R.hidden=!0,S.type="button";let T=o.createElement("p"),l=o.createElement("p"),r=o.createElement("button"),f=o.createElement("button"),E=o.createElement("button"),y=o.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",a.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",T.setAttribute("role","status"),l.setAttribute("role","alert"),l.hidden=!0,r.type=f.type=E.type="button",a.append(r,T,l,E,S,f),s.append(v,R,a),e.append(s);let O=null,U=null,G=null,F="",_="",$="",j="",A=!1,Q=0,i=!1,w="",c=null,I=Promise.resolve(),d=null,m=null,p=new Set,N={},q=(t,g=null)=>{A||(m=g,l.textContent=t instanceof Error?t.message:"Request failed",l.hidden=!1,E.hidden=n.client.pendingCommand===null,X(n.onError,t))};function J(){let t=n.client.view;if(!t)throw new u("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let D=we({client:n.client,doc:o,holder:v,reviewHolder:R,mountScreenPreview:P,get stopped(){return A},get answers(){return N},suspend(t){U?.setSuspended(t)},resetScreen(){F="",_=""},enqueue:W,fail:q}),z=pe({client:n.client,expected:J,fail:q,get stopped(){return A},get reviewing(){return D.active},get key(){return F},get busy(){return Q}}),Z=fe({client:n.client,expected:J,perform:B,onIntent:n.onCustomerDataIntent,get stopped(){return A},get busy(){return Q},get document(){return O?.document},get answers(){return N}});async function B(t,g=!1){if(!(Q&&!g||A||D.active&&!g)){Q++,s.setAttribute("aria-busy","true"),l.hidden=!0,m=null;try{if(!g&&z.inFlight){let b=n.client.view;await z.inFlight;let L=n.client.view;if(!b||!L||L.id!==b.id||L.nodeId!==b.nodeId||L.visit!==b.visit||L.stopped||!["running","waiting"].includes(L.status))throw new u("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(A)return;let M=await t();A||await W(n.client.view??M.run)}catch(M){q(M,n.client.pendingCommand?.requestId??null)}finally{Q=Math.max(0,Q-1),s.setAttribute("aria-busy",String(Q>0)),A||(E.hidden=n.client.pendingCommand===null,r.disabled=Q>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function x(){c&&clearTimeout(c),!(A||!G||!["running","waiting"].includes(G.status)&&!n.client.pendingCommand)&&(c=setTimeout(()=>{c=null,oe().finally(x)},G.pendingRequest||n.client.pendingCommand?1500:5e3))}async function oe(){if(!(A||i||Q)){if(D.active){await D.open(D.receipt);return}i=!0;try{let t=n.client.pendingCommand;t&&n.client.settle&&await n.client.settle(t.requestId);let g=n.client.view,M=Z.queries,b=await n.client.get(g?.screen&&Object.keys(M).length?{nodeId:g.nodeId,visit:g.visit,revision:g.revision,components:M}:void 0);!A&&M===Z.queries&&await W(n.client.view??b.run)}catch(t){q(t)}finally{i=!1}}}function me(t){let g=t.screen?.presentation;if(!g||g.type==="inline"){y.open&&y.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==y&&(y.append(s),e.append(y));let M={sm:420,md:640,lg:900};y.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in g?M[g.size]+"px":"100vw"}`,y.setAttribute("aria-label",O?.document?.name??t.screen?.content.document.name??"Funnel"),y.open||y.showModal()}async function ye(t){if(A)return;G=t,m&&n.client.pendingCommand?.requestId!==m&&(l.hidden=!0,m=null);let g=t.locale.startsWith("zh");if(S.textContent=g?"\u56DE\u770B":"History",S.hidden=!n.client.review,r.textContent=D.active?g?"\u8FD4\u56DE\u5F53\u524D":"Return to current":g?"\u8FD4\u56DE":"Back",f.textContent=g?"\u5173\u95ED":"Close",E.textContent=g?"\u91CD\u8BD5":"Retry",r.disabled=!D.active&&(Q>0||!!n.client.pendingCommand||!t.canBack),E.hidden=n.client.pendingCommand===null,T.textContent=t.pendingRequest?g?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?g?"\u7B49\u5F85\u4E2D":"Waiting":"",w!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(w=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,X(n.onState,structuredClone(t))),t.stopped||n.client.configurationReady===!1){D.stop(),O?.destroy(),O=null,U?.destroy(),U=null,v.replaceChildren(),F="",_="",j="",y.open&&y.close(),s.hidden=!0,x();return}if(s.hidden=!1,D.active){x();return}let M=t.screen||t.paywall?`${t.id}:${t.nodeId}:${t.visit}`:"";if(M!==F&&(O?.destroy(),O=null,U?.destroy(),U=null,v.replaceChildren(),F=M,_="",j="",N={...t.answers},Z.reset()),me(t),t.screen){let L=t.screen.content;O||(O=P(v,{mode:"live",rendererUrl:n.client.webViewUrl,title:L.document.name,onAction(H,te={},ie={}){if(D.active)return;N={...N,...ie};let Ie=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:ne})=>Object.hasOwn(N,ne)).map(({variable:ne})=>[ne,N[ne]]));B(()=>n.client.submit({operation:"submit",...J(),input:{type:"screen",output:H,answers:Ie,selection:te}}))},onAnswers:H=>{D.active||(N={...N,...H})},onCustomerDataIntent:H=>{D.active||Z.intent(H).catch(q)},onEscape:()=>{D.active||K()},onError:H=>q(new Error(H)),onRendered:()=>z.report(M)}));let V={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:N,values:t.screen.values}},Y=JSON.stringify([L,t.locale,V.parameters,t.screen.inputs,t.screen.values]);if(Y!==_)O.update(L.document,t.locale,V),_=Y,$=JSON.stringify(V.capabilities),j=JSON.stringify(V.customerData);else{let H=JSON.stringify(V.capabilities);H!==$&&(O.updateCapabilities(V.capabilities),$=H),JSON.stringify(V.customerData)!==j&&(O.updateCustomerData(V.customerData),j=JSON.stringify(V.customerData))}await O.ready}else if(t.paywall&&!U){let L=await h(v,{canInteract:()=>!D.active&&!A,start:async()=>ce(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:V=>n.onOpenUrl?n.onOpenUrl({receiptId:t.paywall.receiptId,url:V,openIn:"same_window"}):o.defaultView?.location.assign(V),onAction:async V=>{if(D.active)return;let Y=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:V,answers:{}}});await W(n.client.view??Y.run)},onError:q,onDismiss:()=>{!D.active&&!A&&n.client.view?.visit===t.visit&&K()}});A?L.host?.destroy():(U=L.host,U?.setSuspended(D.active)),z.report(M)}let b=t.instruction;if(b&&(b.type==="open_url"||b.type==="event")&&!p.has(b.receiptId)){let L=o.createElement("button");L.type="button",L.textContent=b.type==="open_url"?`${g?"\u524D\u5F80":"Continue to"} ${new URL(b.url).host}`:g?"\u7EE7\u7EED":"Continue",L.onclick=()=>{let V=J(),Y=b.type==="open_url"&&!n.onOpenUrl&&b.openIn==="new_window"?he(b.url):null;B(async()=>{let H="success";if(b.type==="open_url")if(n.onOpenUrl)try{H=await n.onOpenUrl({receiptId:b.receiptId,url:b.url,openIn:b.openIn})===!1?"failed":"opened"}catch(ie){X(n.onError,ie),H="failed"}else H=b.openIn==="new_window"&&!Y?"failed":"opened";if(b.type==="event"){if(!n.onEvent)throw new u("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(b.event)}if(A||n.client.view?.nodeId!==V.nodeId||n.client.view.visit!==V.visit)throw new u("PRECONDITION_FAILED","The client action visit changed");let te=await n.client.submit({operation:"submit",...V,input:{type:"client_action",receiptId:b.receiptId,outcome:H}});return p.add(b.receiptId),b.type==="open_url"&&!n.onOpenUrl&&b.openIn==="same_window"&&o.defaultView?.location.assign(b.url),te})},v.replaceChildren(L)}!t.pendingRequest&&t.status==="completed"&&!p.has(`complete:${t.id}`)&&(p.add(`complete:${t.id}`),X(n.onComplete,structuredClone(t))),x()}function he(t){let g=o.defaultView?.open(t,"_blank")??null;return g&&(g.opener=null),g}function W(t){return I=I.catch(()=>{}).then(()=>ye(t)),I}let ve=n.client.subscribe(t=>{n.client.configurationReady===!1&&(s.hidden=!0,O?.destroy(),O=null,U?.destroy(),U=null,v.replaceChildren(),F="",_="",j="",y.open&&y.close()),W(t).catch(q)}),ge=n.client.subscribeError?.(q);function K(){return d||(A?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ee(),Promise.resolve()):(d=B(()=>n.client.submit({operation:"close",...J()}),!0).then(()=>{n.client.view?.status==="closed"&&ee()}).finally(()=>{d=null}),d))}function ee(){A||(A=!0,c&&clearTimeout(c),ve(),ge?.(),O?.destroy(),D.stop(),U?.destroy(),y.close(),y.remove(),s.remove(),k instanceof HTMLElement&&k.isConnected&&k.focus(),X(n.onDismiss,G?structuredClone(G):null))}r.onclick=()=>{if(D.active){D.exit();return}B(()=>n.client.submit({operation:"back",...J()}))},S.onclick=()=>{D.open()},f.onclick=()=>{K()},E.onclick=()=>{B(()=>n.client.retry())},y.addEventListener("cancel",t=>{t.preventDefault(),K()});try{let t=await n.client.get();await W(n.client.view??t.run)}catch(t){throw ee(),t}return{destroy:ee,refresh:oe,review:D.open,exitReview:D.exit,get unappliedDrafts(){return D.drafts}}}export{Ue as showFunnelRun};
1
+ import{a as le,b as ue,d as de}from"./chunk-GRLMT5PR.js";import"./chunk-SSHUBTT3.js";import{Je as ae,Vg as re}from"./chunk-EJTBSGLV.js";import{a as u}from"./chunk-SOQO2RDZ.js";import{Hb as se}from"./chunk-LMR2TM3X.js";import{a as X}from"./chunk-DSPLGTQI.js";import"./chunk-OBYJWIRB.js";import"./chunk-EXCPE2XH.js";import"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";function ce(e){let C=e.view;if(!C?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let n=C.paywall.receiptId,P=C.nodeId,h=C.visit,o=C.paywall.resolution,k=o,s="document"in o?o:null;function v(i){if(!le(i,o))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let a=C.paywall.quote,R=C.paywall.operation,S=!1,T=new AbortController,l=C.paywall.purchaseRequestId,r=0,f=C.paywall.selectionGeneration??0,E=C.paywall.canReselect===!0,y=null,O=new Map,U=new Map;function G(i){if(i.purchase&&i.purchase.receiptId!==n)throw new u("INVALID_RESPONSE","Purchase receipt changed");let w=i.run.paywall;return i.purchase??(w?.receiptId===n?w:null)}function F(){if(S)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,w,c){if(F(),w!==r||c!==void 0&&a?.operationId!==c)return!1;let I=f,d=i.run.paywall;if(d?.receiptId===n){if((d.selectionGeneration??0)<f)return!1;f=d.selectionGeneration??0,E=d.canReselect===!0,v(d.resolution)}let m=G(i),p=f>I,N=p?m?.quote??null:m?.quote??a,q=m?.operation??(N?.operationId===a?.operationId?R:null);return N&&q&&ue(q,{operationId:N.operationId},"Purchase operation changed"),d?.receiptId===n&&(k=d.resolution,s="document"in k?k:s?{...k,document:s.document,offering:s.offering}:null),(p||N?.operationId!==a?.operationId)&&(r++,d?.receiptId===n&&(l=d.purchaseRequestId)),a=N,R=de(R,q,!0),!0}function $(i,w,c){return new Promise((I,d)=>{let m=!1,p=()=>{clearTimeout(D),T.signal.removeEventListener("abort",J)},N=z=>{m||(m=!0,p(),I(z))},q=z=>{m||(m=!0,p(),d(z))},J=()=>q(new u("IDENTITY_CHANGED","Paywall presentation has closed")),D=setTimeout(()=>q(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,c)),Math.max(0,w-Date.now()));T.signal.addEventListener("abort",J,{once:!0}),T.signal.aborted&&J(),i.then(N,q)})}function j(i){return new Promise(w=>{let c=()=>{clearTimeout(I),T.signal.removeEventListener("abort",c),w()},I=setTimeout(c,i);T.signal.addEventListener("abort",c,{once:!0}),T.signal.aborted&&c()})}async function A(i,w,c){F();let I=O.get(i);if(!I){let p=e.pendingCommands?.find(N=>N.requestId===i)??e.pendingCommand;if(p?.operation==="submit"&&p.requestId===i&&p.nodeId===P&&p.visit===h){w.type==="paywall_quote"&&p.input.type==="paywall_quote"&&p.input.predecessor&&!w.predecessor&&(w={...w,predecessor:p.input.predecessor});let N=re.parse(p),q=re.parse({...p,input:w});if(q.operation!=="submit"||N.operation!=="submit"||JSON.stringify(q.input)!==JSON.stringify(N.input))throw new u("CONFLICT","A restored purchase request cannot change its input");w=q.input,I=N,O.set(i,I)}}if(I){if(JSON.stringify(I.input)!==JSON.stringify(w))throw new u("CONFLICT","A purchase request cannot change its input")}else{let p=e.view;if(!p||p.nodeId!==P||p.visit!==h||p.paywall?.receiptId!==n)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");I={operation:"submit",requestId:i,nodeId:P,visit:h,revision:p.revision,input:w},O.set(i,I)}let d=Date.now()+3e4,m=await $(e.submit(I),d,i);for(;m.run.pendingRequest?.requestId===i&&Date.now()<d&&!S&&(await j(Math.min(1e3,d-Date.now())),!(S||Date.now()>=d));)m=await $(e.resume(i),d,i);if(S)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(m.run.pendingRequest?.requestId===i)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,i);if(!_(m,c,w.type==="paywall_confirm"||w.type==="paywall_cancel"?w.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed")}async function Q(i){if(!a)throw new u("INVALID_REQUEST","A quoted purchase is required");let w=`${i}:${a.operationId}`,c=U.get(w);if(!c){let I=i==="confirm"?"paywall_confirm":"paywall_cancel",d=e.pendingCommands?.find(m=>m.operation==="submit"&&m.input.type===I&&"operationId"in m.input&&m.input.operationId===a.operationId)??e.pendingCommand;c=d?.operation==="submit"&&d.input.type===I&&"operationId"in d.input&&d.input.operationId===a.operationId?d.requestId:crypto.randomUUID(),U.set(w,c)}if(await A(c,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:a.operationId},r),!R)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(R)}return{get view(){return structuredClone(s)},get quote(){return a?structuredClone(a):null},get operation(){return R?structuredClone(R):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return E},async refresh(){F();let i=r,w=await e.get();if(_(w,i),w.run.paywall?.receiptId!==n)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");if(!s){if("document"in k||!e.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let c=await e.resolvePaywall(k);F(),v(c),s={...k,document:c.document,offering:c.offering}}return structuredClone(s)},preview(i){if(!s)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(l&&l!==i.requestId&&(y||!E))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));if(l===i.requestId&&y)return y;let w=s.document.buttons[i.actionId],c=w?.type==="checkout"?ae(w.product,i.selection,s.capabilities):null;if(!c)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=l!==i.requestId&&f>0?{operationId:a?.operationId??null,generation:f}:void 0;if(I&&(!E||f<=0))return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));l!==i.requestId&&r++;let d=r;l=i.requestId;let m=(async()=>{if(await A(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:c,...I?{predecessor:I}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}},d),!a)throw new u("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(a)})();return y=m,m.then(()=>{y===m&&(y=null)},p=>{y===m&&(y=null),l===i.requestId&&e.pendingCommand?.requestId!==i.requestId&&p instanceof u&&p.status!==void 0&&p.status<500&&![401,425].includes(p.status)&&(l=null)}),m},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),async read(){if(F(),!a)throw new u("INVALID_REQUEST","A quoted purchase is required");let i=a.operationId,w=r,c=e.pendingCommands?.find(p=>p.operation==="submit"&&(p.input.type==="paywall_confirm"||p.input.type==="paywall_cancel")&&p.input.operationId===i)??e.pendingCommand;c?.operation==="submit"&&(c.input.type==="paywall_confirm"||c.input.type==="paywall_cancel")&&c.input.operationId===i&&await e.settle?.(c.requestId);let I=await e.get(void 0,{receiptId:n,operationId:i});F();let d=G(I);if(d?.quote&&d.quote.operationId!==i||d?.operation&&d.operation.operationId!==i)throw new u("INVALID_RESPONSE","Purchase operation changed");let m=_(I,w,i)?R:d?.operation;if(!m)throw new u("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(m)},destroy(){S=!0,T.abort(),O.clear(),U.clear()}}}function pe(e){let C=new Set,n=new Set,P=null;function h(o){if(e.reviewing||C.has(o)||n.has(o)||e.stopped)return;n.add(o);let k=async()=>{if(e.reviewing||e.stopped||e.key!==o){n.delete(o);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{k()},250);return}let s=(async()=>{let a=e.client.view,R=e.expected(),S=R.requestId,T=!1;try{await e.client.submit({operation:"shown",...R})}catch(l){if(!(l instanceof u)||l.code!=="CONFLICT"||l.status!==409||e.client.pendingCommand)throw l;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==o||!r||!a||r.id!==a.id||r.source.versionId!==a.source.versionId||r.nodeId!==R.nodeId||r.visit!==R.visit||r.revision<=R.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw l;let f=e.expected();S=f.requestId,await e.client.submit({operation:"shown",...f})}for(;!e.stopped&&e.key===o&&e.client.pendingCommand?.requestId===S;){if(!e.client.settle)throw new u("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(S),T=!0,e.client.pendingCommand?.requestId===S&&await new Promise(l=>setTimeout(l,1500))}e.stopped||e.key!==o||(T&&await e.client.get(),!(e.stopped||e.key!==o)&&C.add(o))})();P=s;let v=()=>{P===s&&(P=null),n.delete(o)};s.then(v,a=>{v(),e.busy||e.fail(a)})};k()}return{report:h,get inFlight(){return P}}}function fe(e){let C={},n=new Map;async function P(h){let o=e.client.view,k=o?.screen,s=k?.customerData.nodes[h.nodeId];if(e.stopped||e.busy||!o||!k||!s)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(h.action)){let r=e.document,f=r?se(r,h.nodeId):null,E=f?.type==="customer_data"?f.data.outputs?.[h.action]:void 0;E&&k.outputs.includes(E)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:E,answers:e.answers,selection:h.value?{[h.nodeId]:h.value}:{}}})):await e.onIntent?.(h,o);return}let a=h.action.startsWith("sources_")?s.resources.find(r=>r.key===h.value):null;if(h.action.startsWith("sources_")&&!a)throw new u("INVALID_REQUEST","Choose a current resource");let R=`${o.visit}:${h.nodeId}:${a?.key??""}`,S=n.get(R)??[null],l=C[h.nodeId]??{page:1,after:null,filter:"all",...a?{resourceKey:a.key}:{}};if(h.action==="filter"){let r=h.value;if(!r||!(s.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new u("INVALID_REQUEST","Unknown data filter");l={page:1,after:null,filter:r},S.splice(0,S.length,null)}else if(h.action==="next"||h.action==="sources_next"){let r=a?.sources.at(-1),f=a?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:k.dataCursors[h.nodeId];if(!f||!a&&!s.hasNext)return;S[l.page]=f,l={...l,page:l.page+1,after:f}}else if(h.action==="previous"||h.action==="sources_previous"){if(l.page<=1)return;l={...l,page:l.page-1,after:S[l.page-2]??null}}n.set(R,S),C={...C,[h.nodeId]:l},await e.perform(()=>e.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:C}))}return{get queries(){return C},intent:P,reset(){C={},n.clear()}}}function we(e){let{doc:C,holder:n,reviewHolder:P,mountScreenPreview:h}=e,o=!1,k,s=0,v=null,a="",R=new Map,S=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function T(r){if(e.stopped||!e.client.review)return;o||(a=S(e.client.view),R.set(a,structuredClone(e.answers))),o=!0,k=r,n.hidden=!0,e.suspend(!0),P.hidden=!1;let f=++s;try{let E=await e.client.review(r);if(e.stopped||f!==s||!o)return;if(!E.review)throw new u("INVALID_RESPONSE","Historical projection is missing");v?.destroy(),v=null,P.replaceChildren();let y=E.run.locale.startsWith("zh"),O=C.createElement("p");O.textContent=y?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(O);for(let[F,_]of E.review.pages.entries()){let $=C.createElement("button");$.type="button",$.textContent=y?`\u7B2C ${F+1} \u9875`:`Page ${F+1}`,$.onclick=()=>{T(_.receiptId)},P.append($)}if(E.review.page){let F=E.review.page,_=C.createElement("div");if(_.inert=!0,P.append(_),v=h(_,{mode:"live",rendererUrl:e.client.webViewUrl,title:F.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{l()}}),v.update(F.document,E.run.locale,{serverInput:{bindings:F.inputs,answers:F.answers,values:F.values}}),await v.ready,e.stopped||f!==s||!o)return}let U=y?{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"},G=y?{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 F of[...E.review.coupons.map((_,$)=>`${y?"\u4F18\u60E0\u5238":"Coupon"} ${$+1}: ${U[_.status]}`),...E.review.purchases.map((_,$)=>`${y?"\u8D2D\u4E70":"Purchase"} ${$+1}: ${G[_.status]}`)]){let _=C.createElement("p");_.textContent=F,P.append(_)}e.client.view&&await e.enqueue(e.client.view)}catch(E){if(f!==s||e.stopped)return;v?.destroy(),v=null,P.replaceChildren(),e.fail(E)}}async function l(){if(!o||e.stopped||!e.client.review)return;let r=++s;try{if(await e.client.review(),e.stopped||r!==s)return;o=!1,s++,v?.destroy(),v=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1;let f=e.client.view;S(f)!==a?(R.set(a,structuredClone(e.answers)),e.resetScreen()):(R.delete(a),e.suspend(!1)),f&&await e.enqueue(f)}catch(f){if(r!==s||e.stopped)return;v?.destroy(),v=null,P.replaceChildren(),e.fail(f)}}return{get active(){return o},get receipt(){return k},open:T,exit:l,get drafts(){return new Map([...R].map(([r,f])=>[r,structuredClone(f)]))},stop(){o=!1,s++,v?.destroy(),v=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1}}}async function Ue(e,C){let n=C,{mountScreenPreview:P}=await import("./screen-renderer-DLXDQQKK.js"),{showPaywall:h}=await import("./paywall-734GWAS4.js"),o=e.ownerDocument,k=o.activeElement,s=o.createElement("section"),v=o.createElement("div"),a=o.createElement("div"),R=o.createElement("div"),S=o.createElement("button");R.hidden=!0,S.type="button";let T=o.createElement("p"),l=o.createElement("p"),r=o.createElement("button"),f=o.createElement("button"),E=o.createElement("button"),y=o.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",a.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",T.setAttribute("role","status"),l.setAttribute("role","alert"),l.hidden=!0,r.type=f.type=E.type="button",a.append(r,T,l,E,S,f),s.append(v,R,a),e.append(s);let O=null,U=null,G=null,F="",_="",$="",j="",A=!1,Q=0,i=!1,w="",c=null,I=Promise.resolve(),d=null,m=null,p=new Set,N={},q=(t,g=null)=>{A||(m=g,l.textContent=t instanceof Error?t.message:"Request failed",l.hidden=!1,E.hidden=n.client.pendingCommand===null,X(n.onError,t))};function J(){let t=n.client.view;if(!t)throw new u("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let D=we({client:n.client,doc:o,holder:v,reviewHolder:R,mountScreenPreview:P,get stopped(){return A},get answers(){return N},suspend(t){U?.setSuspended(t)},resetScreen(){F="",_=""},enqueue:W,fail:q}),z=pe({client:n.client,expected:J,fail:q,get stopped(){return A},get reviewing(){return D.active},get key(){return F},get busy(){return Q}}),Z=fe({client:n.client,expected:J,perform:B,onIntent:n.onCustomerDataIntent,get stopped(){return A},get busy(){return Q},get document(){return O?.document},get answers(){return N}});async function B(t,g=!1){if(!(Q&&!g||A||D.active&&!g)){Q++,s.setAttribute("aria-busy","true"),l.hidden=!0,m=null;try{if(!g&&z.inFlight){let b=n.client.view;await z.inFlight;let L=n.client.view;if(!b||!L||L.id!==b.id||L.nodeId!==b.nodeId||L.visit!==b.visit||L.stopped||!["running","waiting"].includes(L.status))throw new u("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(A)return;let M=await t();A||await W(n.client.view??M.run)}catch(M){q(M,n.client.pendingCommand?.requestId??null)}finally{Q=Math.max(0,Q-1),s.setAttribute("aria-busy",String(Q>0)),A||(E.hidden=n.client.pendingCommand===null,r.disabled=Q>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function x(){c&&clearTimeout(c),!(A||!G||!["running","waiting"].includes(G.status)&&!n.client.pendingCommand)&&(c=setTimeout(()=>{c=null,oe().finally(x)},G.pendingRequest||n.client.pendingCommand?1500:5e3))}async function oe(){if(!(A||i||Q)){if(D.active){await D.open(D.receipt);return}i=!0;try{let t=n.client.pendingCommand;t&&n.client.settle&&await n.client.settle(t.requestId);let g=n.client.view,M=Z.queries,b=await n.client.get(g?.screen&&Object.keys(M).length?{nodeId:g.nodeId,visit:g.visit,revision:g.revision,components:M}:void 0);!A&&M===Z.queries&&await W(n.client.view??b.run)}catch(t){q(t)}finally{i=!1}}}function me(t){let g=t.screen?.presentation;if(!g||g.type==="inline"){y.open&&y.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==y&&(y.append(s),e.append(y));let M={sm:420,md:640,lg:900};y.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in g?M[g.size]+"px":"100vw"}`,y.setAttribute("aria-label",O?.document?.name??t.screen?.content.document.name??"Funnel"),y.open||y.showModal()}async function ye(t){if(A)return;G=t,m&&n.client.pendingCommand?.requestId!==m&&(l.hidden=!0,m=null);let g=t.locale.startsWith("zh");if(S.textContent=g?"\u56DE\u770B":"History",S.hidden=!n.client.review,r.textContent=D.active?g?"\u8FD4\u56DE\u5F53\u524D":"Return to current":g?"\u8FD4\u56DE":"Back",f.textContent=g?"\u5173\u95ED":"Close",E.textContent=g?"\u91CD\u8BD5":"Retry",r.disabled=!D.active&&(Q>0||!!n.client.pendingCommand||!t.canBack),E.hidden=n.client.pendingCommand===null,T.textContent=t.pendingRequest?g?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?g?"\u7B49\u5F85\u4E2D":"Waiting":"",w!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(w=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,X(n.onState,structuredClone(t))),t.stopped||n.client.configurationReady===!1){D.stop(),O?.destroy(),O=null,U?.destroy(),U=null,v.replaceChildren(),F="",_="",j="",y.open&&y.close(),s.hidden=!0,x();return}if(s.hidden=!1,D.active){x();return}let M=t.screen||t.paywall?`${t.id}:${t.nodeId}:${t.visit}`:"";if(M!==F&&(O?.destroy(),O=null,U?.destroy(),U=null,v.replaceChildren(),F=M,_="",j="",N={...t.answers},Z.reset()),me(t),t.screen){let L=t.screen.content;O||(O=P(v,{mode:"live",rendererUrl:n.client.webViewUrl,title:L.document.name,onAction(H,te={},ie={}){if(D.active)return;N={...N,...ie};let Ie=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:ne})=>Object.hasOwn(N,ne)).map(({variable:ne})=>[ne,N[ne]]));B(()=>n.client.submit({operation:"submit",...J(),input:{type:"screen",output:H,answers:Ie,selection:te}}))},onAnswers:H=>{D.active||(N={...N,...H})},onCustomerDataIntent:H=>{D.active||Z.intent(H).catch(q)},onEscape:()=>{D.active||K()},onError:H=>q(new Error(H)),onRendered:()=>z.report(M)}));let V={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:N,values:t.screen.values}},Y=JSON.stringify([L,t.locale,V.parameters,t.screen.inputs,t.screen.values]);if(Y!==_)O.update(L.document,t.locale,V),_=Y,$=JSON.stringify(V.capabilities),j=JSON.stringify(V.customerData);else{let H=JSON.stringify(V.capabilities);H!==$&&(O.updateCapabilities(V.capabilities),$=H),JSON.stringify(V.customerData)!==j&&(O.updateCustomerData(V.customerData),j=JSON.stringify(V.customerData))}await O.ready}else if(t.paywall&&!U){let L=await h(v,{canInteract:()=>!D.active&&!A,start:async()=>ce(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:V=>n.onOpenUrl?n.onOpenUrl({receiptId:t.paywall.receiptId,url:V,openIn:"same_window"}):o.defaultView?.location.assign(V),onAction:async V=>{if(D.active)return;let Y=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:V,answers:{}}});await W(n.client.view??Y.run)},onError:q,onDismiss:()=>{!D.active&&!A&&n.client.view?.visit===t.visit&&K()}});A?L.host?.destroy():(U=L.host,U?.setSuspended(D.active)),z.report(M)}let b=t.instruction;if(b&&(b.type==="open_url"||b.type==="event")&&!p.has(b.receiptId)){let L=o.createElement("button");L.type="button",L.textContent=b.type==="open_url"?`${g?"\u524D\u5F80":"Continue to"} ${new URL(b.url).host}`:g?"\u7EE7\u7EED":"Continue",L.onclick=()=>{let V=J(),Y=b.type==="open_url"&&!n.onOpenUrl&&b.openIn==="new_window"?he(b.url):null;B(async()=>{let H="success";if(b.type==="open_url")if(n.onOpenUrl)try{H=await n.onOpenUrl({receiptId:b.receiptId,url:b.url,openIn:b.openIn})===!1?"failed":"opened"}catch(ie){X(n.onError,ie),H="failed"}else H=b.openIn==="new_window"&&!Y?"failed":"opened";if(b.type==="event"){if(!n.onEvent)throw new u("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(b.event)}if(A||n.client.view?.nodeId!==V.nodeId||n.client.view.visit!==V.visit)throw new u("PRECONDITION_FAILED","The client action visit changed");let te=await n.client.submit({operation:"submit",...V,input:{type:"client_action",receiptId:b.receiptId,outcome:H}});return p.add(b.receiptId),b.type==="open_url"&&!n.onOpenUrl&&b.openIn==="same_window"&&o.defaultView?.location.assign(b.url),te})},v.replaceChildren(L)}!t.pendingRequest&&t.status==="completed"&&!p.has(`complete:${t.id}`)&&(p.add(`complete:${t.id}`),X(n.onComplete,structuredClone(t))),x()}function he(t){let g=o.defaultView?.open(t,"_blank")??null;return g&&(g.opener=null),g}function W(t){return I=I.catch(()=>{}).then(()=>ye(t)),I}let ve=n.client.subscribe(t=>{n.client.configurationReady===!1&&(s.hidden=!0,O?.destroy(),O=null,U?.destroy(),U=null,v.replaceChildren(),F="",_="",j="",y.open&&y.close()),W(t).catch(q)}),ge=n.client.subscribeError?.(q);function K(){return d||(A?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ee(),Promise.resolve()):(d=B(()=>n.client.submit({operation:"close",...J()}),!0).then(()=>{n.client.view?.status==="closed"&&ee()}).finally(()=>{d=null}),d))}function ee(){A||(A=!0,c&&clearTimeout(c),ve(),ge?.(),O?.destroy(),D.stop(),U?.destroy(),y.close(),y.remove(),s.remove(),k instanceof HTMLElement&&k.isConnected&&k.focus(),X(n.onDismiss,G?structuredClone(G):null))}r.onclick=()=>{if(D.active){D.exit();return}B(()=>n.client.submit({operation:"back",...J()}))},S.onclick=()=>{D.open()},f.onclick=()=>{K()},E.onclick=()=>{B(()=>n.client.retry())},y.addEventListener("cancel",t=>{t.preventDefault(),K()});try{let t=await n.client.get();await W(n.client.view??t.run)}catch(t){throw ee(),t}return{destroy:ee,refresh:oe,review:D.open,exitReview:D.exit,get unappliedDrafts(){return D.drafts}}}export{Ue as showFunnelRun};