@tinkerlandai/indiana-sdk 0.8.0 → 0.8.1

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 (46) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +67 -20
  3. package/README.zh-CN.md +66 -19
  4. package/dist/ai-usage-JoM7ZWk-.d.ts +247 -0
  5. package/dist/{ai-usage-Bigjb8MS.d.ts → api-JVC7x2FV.d.ts} +175 -418
  6. package/dist/chunk-56AYS7RS.js +1 -0
  7. package/dist/chunk-AEUFCOFG.js +1 -0
  8. package/dist/chunk-F767CM3T.js +7 -0
  9. package/dist/chunk-KSNOXNTC.js +1 -0
  10. package/dist/{chunk-G2R56FKU.js → chunk-USLZX2ZA.js} +1 -1
  11. package/dist/{chunk-YAFMBXIE.js → chunk-X747SY26.js} +1 -1
  12. package/dist/{chunk-3ENVRJE6.js → chunk-X7JJAEQQ.js} +1 -1
  13. package/dist/chunk-YWFNWK7C.js +1 -0
  14. package/dist/{configuration-sync-VFbY1pCN.d.ts → configuration-sync-BexM2qbg.d.ts} +25 -25
  15. package/dist/{content-K2HCZVC2.js → content-YNL2CRJZ.js} +1 -1
  16. package/dist/{funnel-runtime-start-DKcTCRrd.d.ts → funnel-local-client-D1Fe7CZ6.d.ts} +694 -6057
  17. package/dist/funnel-runtime-host-CAMI6BJS.js +1 -0
  18. package/dist/index.d.ts +1755 -1915
  19. package/dist/index.js +1 -1
  20. package/dist/native-shell.js +1 -1
  21. package/dist/openrouter.d.ts +4 -3
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +7 -7
  24. package/dist/page.js +1 -1
  25. package/dist/paywall-MXRMMF3R.js +1 -0
  26. package/dist/popup.d.ts +2 -2
  27. package/dist/popup.js +1 -1
  28. package/dist/react-native.d.ts +2 -2
  29. package/dist/react-native.js +1 -1
  30. package/dist/screen-renderer-P7MLBHY5.js +1 -0
  31. package/dist/server.d.ts +4645 -8
  32. package/dist/server.js +1 -1
  33. package/dist/{src-4MRSESVS.js → src-G7UQB3QE.js} +1 -1
  34. package/dist/visual.js +1 -1
  35. package/package.json +3 -3
  36. package/dist/chunk-2A6UYUFA.js +0 -1
  37. package/dist/chunk-A3N4ZZTM.js +0 -7
  38. package/dist/chunk-CXYOZSOF.js +0 -1
  39. package/dist/funnel-runtime-host-HNZ47TZW.js +0 -1
  40. package/dist/paywall-PD62B2AY.js +0 -1
  41. package/dist/{chunk-OVMNCZYC.js → chunk-6HG7U6AU.js} +0 -0
  42. package/dist/{chunk-6X42DWOM.js → chunk-DSPLGTQI.js} +0 -0
  43. package/dist/{chunk-S5TVMQRC.js → chunk-EXCPE2XH.js} +0 -0
  44. package/dist/{customer-page-BrCZxcaQ.d.ts → customer-page-WUQVK_tp.d.ts} +4 -4
  45. package/dist/{errors-BpCmukJr.d.ts → errors-DrdTlPwf.d.ts} +1 -1
  46. package/dist/{screen-BazUOjwM.d.ts → screen-i6eHL11m.d.ts} +267 -267
@@ -0,0 +1 @@
1
+ import{a as u}from"./chunk-6HG7U6AU.js";import{ZodError as f}from"zod";function T(n,r,t,e){try{return n.parse(r)}catch(s){throw e&&s instanceof f?new u(t,e):s}}async function R(n,r,t,e={},s){let o=typeof e=="function"?{}:e,i=T(r.request,t,"INVALID_REQUEST",o.request),p=await n(r.path,i,r.method,s),a=typeof e=="function"?e:e.parseResponse;return a?a(r.response,p):T(r.response,p,"INVALID_RESPONSE",o.response)}export{R as a};
@@ -1 +1 @@
1
- import{Jg as E,Kg as M,Lg as j,Mg as O,Ng as T}from"./chunk-A3N4ZZTM.js";import{a as u}from"./chunk-OVMNCZYC.js";import{x as w}from"./chunk-3BQFJANQ.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{Jg as E,Kg as M,Lg as j,Mg as O,Ng as T}from"./chunk-F767CM3T.js";import{a as u}from"./chunk-6HG7U6AU.js";import{x as w}from"./chunk-3BQFJANQ.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,4 +1,4 @@
1
- import{a as U}from"./chunk-S5TVMQRC.js";import{e as T,h as I,k as A}from"./chunk-KQCTDXVD.js";function L(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let r of document.cookie.split(";"))if(r.trim().startsWith(`${e}=`))try{t=decodeURIComponent(r.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function C(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function _(e=U){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var y=new Set,E;function $(e){if(y.add(e),!E){let t=history.pushState,r=history.replaceState,n=()=>{for(let c of y)c()},a=function(...c){t.apply(this,c),n()},d=function(...c){r.apply(this,c),n()};history.pushState=a,history.replaceState=d,addEventListener("popstate",n),addEventListener("hashchange",n),E=()=>{history.pushState===a&&(history.pushState=t),history.replaceState===d&&(history.replaceState=r),removeEventListener("popstate",n),removeEventListener("hashchange",n)}}return()=>{y.delete(e),y.size||(E?.(),E=void 0)}}var G=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function Y(e,t){let r=e,n=a=>Number.isInteger(a)&&a>=0;return!!r&&typeof r=="object"&&n(r.inserted)&&n(r.duplicates)&&n(r.skipped)&&Array.isArray(r.rejected)&&r.inserted+r.duplicates+r.skipped+r.rejected.length===t}function D(e){let t=[],r,n=(s,o)=>e.log?.(`${e.label} ${s}`,o);function a(s){r===void 0&&t.length&&(r=setTimeout(()=>{c()},s))}async function d(s){let o;try{o=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:s}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(g){return n("not sent",{error:g}),!1}if(o.status===408||o.status===429||o.status>=500)return n("not sent",{status:o.status}),!1;if(!o.ok)return n("rejected",{status:o.status,events:s.length}),!0;let l;try{l=await o.json()}catch{l=void 0}return Y(l,s.length)?(l.rejected.length&&n("rejected",{rejected:l.rejected}),!0):(n("not acknowledged",{status:o.status}),!1)}function c(){clearTimeout(r),r=void 0;let s=[];for(;t.length&&s.length<20&&(!s.length||G([...s,t[0]].map(o=>o.event))<=65536);)s.push(t.shift());return s.length?d(s.map(o=>o.event)).then(o=>{if(o)return a(1e3);let l=s.filter(g=>++g.attempts<5);l.length<s.length&&n("dropped after retries",{events:s.length-l.length}),t.unshift(...l),a(5e3)}):Promise.resolve()}return{push(s){t.push({event:s,attempts:0}),t.length>=20?c():a(1e3)},flush:c}}/*!
1
+ import{a as U}from"./chunk-EXCPE2XH.js";import{e as T,h as I,k as A}from"./chunk-KQCTDXVD.js";function L(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let r of document.cookie.split(";"))if(r.trim().startsWith(`${e}=`))try{t=decodeURIComponent(r.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function C(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function _(e=U){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var y=new Set,E;function $(e){if(y.add(e),!E){let t=history.pushState,r=history.replaceState,n=()=>{for(let c of y)c()},a=function(...c){t.apply(this,c),n()},d=function(...c){r.apply(this,c),n()};history.pushState=a,history.replaceState=d,addEventListener("popstate",n),addEventListener("hashchange",n),E=()=>{history.pushState===a&&(history.pushState=t),history.replaceState===d&&(history.replaceState=r),removeEventListener("popstate",n),removeEventListener("hashchange",n)}}return()=>{y.delete(e),y.size||(E?.(),E=void 0)}}var G=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function Y(e,t){let r=e,n=a=>Number.isInteger(a)&&a>=0;return!!r&&typeof r=="object"&&n(r.inserted)&&n(r.duplicates)&&n(r.skipped)&&Array.isArray(r.rejected)&&r.inserted+r.duplicates+r.skipped+r.rejected.length===t}function D(e){let t=[],r,n=(s,o)=>e.log?.(`${e.label} ${s}`,o);function a(s){r===void 0&&t.length&&(r=setTimeout(()=>{c()},s))}async function d(s){let o;try{o=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:s}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(g){return n("not sent",{error:g}),!1}if(o.status===408||o.status===429||o.status>=500)return n("not sent",{status:o.status}),!1;if(!o.ok)return n("rejected",{status:o.status,events:s.length}),!0;let l;try{l=await o.json()}catch{l=void 0}return Y(l,s.length)?(l.rejected.length&&n("rejected",{rejected:l.rejected}),!0):(n("not acknowledged",{status:o.status}),!1)}function c(){clearTimeout(r),r=void 0;let s=[];for(;t.length&&s.length<20&&(!s.length||G([...s,t[0]].map(o=>o.event))<=65536);)s.push(t.shift());return s.length?d(s.map(o=>o.event)).then(o=>{if(o)return a(1e3);let l=s.filter(g=>++g.attempts<5);l.length<s.length&&n("dropped after retries",{events:s.length-l.length}),t.unshift(...l),a(5e3)}):Promise.resolve()}return{push(s){t.push({event:s,attempts:0}),t.length>=20?c():a(1e3)},flush:c}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function J(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return t}return r.searchParams.forEach((a,d)=>{n.searchParams.has(d)||n.searchParams.set(d,a)}),n.toString()}function Q(e,t){let r=navigator.userAgent,n=new URLSearchParams(t.search),a={};for(let d of["source","medium","campaign","term","content"]){let c=n.get(`utm_${d}`);c!==null&&(a[`utm${d[0].toUpperCase()}${d.slice(1)}`]=c)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(r)?"edge":/Chrome/.test(r)?"chrome":/Firefox/.test(r)?"firefox":/Safari/.test(r)?"safari":"unknown",deviceType:/Mobi/.test(r)?"mobile":"desktop",...a}}function z(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(a=>Object.hasOwn(n,a))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(a=>!!a&&typeof a.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ee(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=_(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=`${t}/api/v1/page-experiments/${e.environmentId}`,a=L(e.deviceIdCookie??"indiana_did"),d=C(),c=null,s={...e.attributes??{}},o="",l=!1,g=new Map,P=D({endpoint:`${n}/events`,fetch:r,log:e.log,label:"Exposure"}),x=P.flush,f={trackedExperiments:new Set,log:e.log,onExperimentViewed:(i,u)=>{e.trackExposures===!1||c?.trackExposures===!1||P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...d?{sessionId:d}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:u.key})}},j=()=>{f.url=location.href,f.attributes={...Q(a,location),...s}};function O(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let u=new URL(location.href);return i.variations.some(p=>{if(!p.urlRedirect)return!1;let v=new URL(p.urlRedirect);return v.protocol!==u.protocol||v.host!==u.host})}catch{return!0}}function N(i,u){let p=e.configuration?.snapshot?.generation;o=i;let v=e.navigate??(m=>location.replace(m)),M=e.navigateDelay??(e.navigate?0:100),V=e.maxNavigateDelay??1e3;Promise.all([Promise.race([u,new Promise(m=>setTimeout(m,V))]),new Promise(m=>setTimeout(m,M))]).then(()=>{!l&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===p)&&v(i)})}function h(){if(!(!c||l||e.configuration&&!e.configuration.fresh)){j();for(let i of c.experiments){if(O(i)){e.log?.("Auto experiment blocked",{id:i.key});continue}let u;try{u=A(i,f)}catch(p){e.log?.("Skipping page experiment",{id:i.key,error:String(p)});continue}if(g.set(i.key,u),!!u.inExperiment){if(u.value.urlRedirect){let p=i.persistQueryString?J(location.href,u.value.urlRedirect):u.value.urlRedirect;T(p,i.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):p!==o&&N(p,x())}break}}}}let b="",H=()=>{location.href!==b&&(b=location.href,o="",h())},R,S;function B(){R??=$(H),addEventListener("pagehide",k)}let k=()=>{x()};async function w(){let i=e.configuration?null:await r(n,{cache:"no-cache",credentials:"omit"});if(i&&!i.ok)throw new Error(`Page experiments unavailable (${i.status})`);let u=z(e.configuration?await e.configuration.pageExperiments():await i.json());if(u.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");c?.trackExposures===!1&&u.trackExposures&&f.trackedExperiments?.clear(),c=u,f.savedGroups=I(u.savedGroups)}return{async start(){await w(),S??=e.configuration?.subscribe(()=>{!l&&e.configuration?.fresh&&w().then(h).catch(i=>e.log?.("Page configuration unavailable",{error:String(i)}))}),B(),b=location.href,h()},async refresh(){await w(),o="",h()},setAttributes(i){s={...i},h()},getResults(){return new Map(g)},get generation(){return c?.generation??null},destroy(){l=!0,S?.(),R?.(),removeEventListener("pagehide",k),x()}}}export{L as a,C as b,_ as c,$ as d,J as e,Q as f,z as g,ee as h};
@@ -1,4 +1,4 @@
1
- import{a as X}from"./chunk-6X42DWOM.js";import{a as It}from"./chunk-OVMNCZYC.js";import{Da as Te,Ea as Ze,Eb as Be,Fb as He,Ga as Fe,Hb as ye,Ib as Qe,Jb as je,Ka as Ae,Lb as et,Mb as tt,Pb as at,ta as Ye,tb as Ge,wb as Xe}from"./chunk-3BQFJANQ.js";var Ne={tag:"9037543eaa371159fc84ea13106519e25928938624bf6894f60784756f21fba0",csp:"default-src 'none'; script-src 'sha256-yOhgPzcvKvEFpgU2Q0tFf8o/6yjrvhqAl7t90JWScno='; style-src 'unsafe-inline'; img-src https: data:; connect-src 'none'; font-src 'none'; media-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'",html:`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-yOhgPzcvKvEFpgU2Q0tFf8o/6yjrvhqAl7t90JWScno='; style-src 'unsafe-inline'; img-src https: data:; connect-src 'none'; font-src 'none'; media-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'"></head><body><script>(() => {
1
+ import{a as X}from"./chunk-DSPLGTQI.js";import{a as It}from"./chunk-6HG7U6AU.js";import{Da as Te,Ea as Ze,Eb as Be,Fb as He,Ga as Fe,Hb as ye,Ib as Qe,Jb as je,Ka as Ae,Lb as et,Mb as tt,Pb as at,ta as Ye,tb as Ge,wb as Xe}from"./chunk-3BQFJANQ.js";var Ne={tag:"9037543eaa371159fc84ea13106519e25928938624bf6894f60784756f21fba0",csp:"default-src 'none'; script-src 'sha256-yOhgPzcvKvEFpgU2Q0tFf8o/6yjrvhqAl7t90JWScno='; style-src 'unsafe-inline'; img-src https: data:; connect-src 'none'; font-src 'none'; media-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'",html:`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-yOhgPzcvKvEFpgU2Q0tFf8o/6yjrvhqAl7t90JWScno='; style-src 'unsafe-inline'; img-src https: data:; connect-src 'none'; font-src 'none'; media-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'"></head><body><script>(() => {
2
2
  try {
3
3
  const input = JSON.parse(decodeURIComponent(location.hash.slice(1)));
4
4
  if (!input || !/^[a-f0-9-]{36}$/.test(input.channel) || input.mode !== "live" || !Number.isInteger(input.hostDepth) || input.hostDepth < 1 || input.hostDepth > 16) return;
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-6HG7U6AU.js";function a(r,n){let t=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return r.id===n.id&&t(r)===t(n)&&r.content?.artifact.sha256===n.content?.artifact.sha256}function s(r,n,t){if(r.operationId!==n.operationId||n.currency!==void 0&&r.currency!==n.currency)throw new o("INVALID_RESPONSE",t)}function u(r,n,t){if(r.lines.length!==1||r.lines[0].productVersionId!==n.productVersionId||n.currency!==void 0&&r.currency!==n.currency||n.provider!==void 0&&r.provider!==n.provider)throw new o("INVALID_RESPONSE",t)}function c(r,n,t=!1){return!r||r.operationId!==n?.operationId?n:r.status==="complete"&&n.status!=="complete"||r.status!=="pending"&&(n.status==="pending"||t&&n.status!=="complete")?r:n}export{a,s as b,u as c,c as d};
@@ -1,11 +1,11 @@
1
1
  import { z } from 'zod';
2
- import { S as StackNode } from './screen-BazUOjwM.js';
2
+ import { S as StackNode } from './screen-i6eHL11m.js';
3
3
 
4
4
  declare const configurationScopeSchema: z.ZodObject<{
5
5
  projectId: z.ZodString;
6
6
  environment: z.ZodEnum<{
7
- live: "live";
8
7
  sandbox: "sandbox";
8
+ live: "live";
9
9
  }>;
10
10
  environmentId: z.ZodUUID;
11
11
  }, z.core.$strict>;
@@ -15,8 +15,8 @@ declare const sdkConfigurationManifestSchema: z.ZodObject<{
15
15
  scope: z.ZodObject<{
16
16
  projectId: z.ZodString;
17
17
  environment: z.ZodEnum<{
18
- live: "live";
19
18
  sandbox: "sandbox";
19
+ live: "live";
20
20
  }>;
21
21
  environmentId: z.ZodUUID;
22
22
  }, z.core.$strict>;
@@ -104,7 +104,7 @@ type Listener = () => void;
104
104
  declare function createConfigurationSync(options: ConfigurationSyncOptions): {
105
105
  scope: Readonly<{
106
106
  projectId: string;
107
- environment: "live" | "sandbox";
107
+ environment: "sandbox" | "live";
108
108
  environmentId: string;
109
109
  }>;
110
110
  refresh: () => Promise<Manifest>;
@@ -117,7 +117,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
117
117
  schemaVersion: 1;
118
118
  scope: {
119
119
  projectId: string;
120
- environment: "live" | "sandbox";
120
+ environment: "sandbox" | "live";
121
121
  environmentId: string;
122
122
  };
123
123
  revision: number;
@@ -268,7 +268,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
268
268
  }>;
269
269
  scope: {
270
270
  projectId: string;
271
- environment: "live" | "sandbox";
271
+ environment: "sandbox" | "live";
272
272
  };
273
273
  generation: string;
274
274
  savedGroups: Record<string, {
@@ -342,11 +342,6 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
342
342
  urlRedirect: string;
343
343
  }[];
344
344
  name?: string | undefined;
345
- meta?: {
346
- key?: string | undefined;
347
- name?: string | undefined;
348
- passthrough?: boolean | undefined;
349
- }[] | undefined;
350
345
  filters?: {
351
346
  seed: string;
352
347
  hashVersion: 2;
@@ -376,6 +371,11 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
376
371
  disableStickyBucketing?: boolean | undefined;
377
372
  bucketVersion?: number | undefined;
378
373
  minBucketVersion?: number | undefined;
374
+ meta?: {
375
+ key?: string | undefined;
376
+ name?: string | undefined;
377
+ passthrough?: boolean | undefined;
378
+ }[] | undefined;
379
379
  phase?: string | undefined;
380
380
  }[];
381
381
  savedGroups: Record<string, {
@@ -608,7 +608,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
608
608
  event: string;
609
609
  } | {
610
610
  type: "api";
611
- operation: "attach" | "refund" | "update" | "readBalanceSource" | "adjustBalance" | "readUsage" | "setUsage" | "manageBalanceGrant" | "listBalanceGrants" | "restoreNativePurchase" | "setupPayment" | "readPaymentSetup" | "verifySubscriptions" | "previewAttach" | "readSubscriptionOperation" | "previewUpdate" | "readSubscriptionUpdate" | "previewRefund" | "readRefund" | "readBillingControls" | "prepareBillingAuthorization" | "confirmBillingAuthorization" | "setBillingCoupons" | "revokeBillingAuthorization" | "listBillingInvoices" | "confirmBillingAdjustment" | "manageBillingLimits" | "manageUsageEntity" | "readUsageAnalytics" | "readCreditAnalytics" | "submitUsageBatch" | "readUsageBatch" | "checkEntitlement" | "resolveOffering" | "readHoldings" | "readLedger" | "readBillingInvoice" | "readCreditStatement" | "quoteBalance" | "trackUsage" | "mutateBalance" | "redeemReward" | "createReferralCode" | "claimRewardProduct" | "readSeats" | "manageSeat" | "redeemCoupon" | "listOffers" | "grantOffer";
611
+ operation: "update" | "attach" | "refund" | "readBalanceSource" | "adjustBalance" | "readUsage" | "setUsage" | "manageBalanceGrant" | "listBalanceGrants" | "restoreNativePurchase" | "setupPayment" | "readPaymentSetup" | "verifySubscriptions" | "previewAttach" | "readSubscriptionOperation" | "previewUpdate" | "readSubscriptionUpdate" | "previewRefund" | "readRefund" | "readBillingControls" | "prepareBillingAuthorization" | "confirmBillingAuthorization" | "setBillingCoupons" | "revokeBillingAuthorization" | "listBillingInvoices" | "confirmBillingAdjustment" | "manageBillingLimits" | "manageUsageEntity" | "readUsageAnalytics" | "readCreditAnalytics" | "submitUsageBatch" | "readUsageBatch" | "checkEntitlement" | "resolveOffering" | "readHoldings" | "readLedger" | "readBillingInvoice" | "readCreditStatement" | "quoteBalance" | "trackUsage" | "mutateBalance" | "redeemReward" | "createReferralCode" | "claimRewardProduct" | "readSeats" | "manageSeat" | "redeemCoupon" | "listOffers" | "grantOffer";
612
612
  inputs: Record<string, {
613
613
  source: "literal";
614
614
  value: z.core.util.JSONType;
@@ -664,7 +664,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
664
664
  } | undefined;
665
665
  } | {
666
666
  type: "end";
667
- outcome: "closed" | "failed" | "completed" | "ineligible";
667
+ outcome: "failed" | "completed" | "closed" | "ineligible";
668
668
  id: string;
669
669
  name: string;
670
670
  output?: {
@@ -731,7 +731,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
731
731
  primary: string;
732
732
  background: string;
733
733
  text: string;
734
- radius: "sm" | "md" | "lg" | "none" | "full";
734
+ radius: "none" | "sm" | "md" | "lg" | "full";
735
735
  font: "system" | "serif" | "rounded" | "mono";
736
736
  };
737
737
  pages: {
@@ -742,7 +742,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
742
742
  primary: string;
743
743
  background: string;
744
744
  text: string;
745
- radius: "sm" | "md" | "lg" | "none" | "full";
745
+ radius: "none" | "sm" | "md" | "lg" | "full";
746
746
  font: "system" | "serif" | "rounded" | "mono";
747
747
  } | undefined;
748
748
  editorPosition?: {
@@ -792,7 +792,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
792
792
  };
793
793
  publicData?: {
794
794
  couponDigests: Record<string, string>;
795
- variables: Record<string, Record<string, Partial<Record<"offer.ends_at" | "offer.headline" | "offer.name" | "offer.description" | "offer.eligibility" | "offer.validity" | "offer.terms" | "offer.discount" | "offer.months", string>>>>;
795
+ variables: Record<string, Record<string, Partial<Record<"offer.headline" | "offer.name" | "offer.description" | "offer.eligibility" | "offer.validity" | "offer.terms" | "offer.discount" | "offer.months" | "offer.ends_at", string>>>>;
796
796
  locales: Record<string, {
797
797
  nodes: Record<string, {
798
798
  base: {
@@ -983,7 +983,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
983
983
  }>;
984
984
  scope: {
985
985
  projectId: string;
986
- environment: "live" | "sandbox";
986
+ environment: "sandbox" | "live";
987
987
  };
988
988
  generation: string;
989
989
  savedGroups: Record<string, {
@@ -1069,7 +1069,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1069
1069
  schemaVersion: 1;
1070
1070
  scope: {
1071
1071
  projectId: string;
1072
- environment: "live" | "sandbox";
1072
+ environment: "sandbox" | "live";
1073
1073
  environmentId: string;
1074
1074
  };
1075
1075
  revision: number;
@@ -1156,7 +1156,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1156
1156
  primary: string;
1157
1157
  background: string;
1158
1158
  text: string;
1159
- radius: "sm" | "md" | "lg" | "none" | "full";
1159
+ radius: "none" | "sm" | "md" | "lg" | "full";
1160
1160
  font: "system" | "serif" | "rounded" | "mono";
1161
1161
  };
1162
1162
  pages: {
@@ -1167,7 +1167,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1167
1167
  primary: string;
1168
1168
  background: string;
1169
1169
  text: string;
1170
- radius: "sm" | "md" | "lg" | "none" | "full";
1170
+ radius: "none" | "sm" | "md" | "lg" | "full";
1171
1171
  font: "system" | "serif" | "rounded" | "mono";
1172
1172
  } | undefined;
1173
1173
  editorPosition?: {
@@ -1345,7 +1345,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1345
1345
  schemaVersion: 1;
1346
1346
  scope: {
1347
1347
  projectId: string;
1348
- environment: "live" | "sandbox";
1348
+ environment: "sandbox" | "live";
1349
1349
  environmentId: string;
1350
1350
  };
1351
1351
  revision: number;
@@ -1400,7 +1400,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1400
1400
  growth: {
1401
1401
  scope: {
1402
1402
  projectId: string;
1403
- environment: "live" | "sandbox";
1403
+ environment: "sandbox" | "live";
1404
1404
  };
1405
1405
  generation: string;
1406
1406
  evaluatedAt: string;
@@ -1561,7 +1561,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1561
1561
  }[]>;
1562
1562
  scope: {
1563
1563
  projectId: string;
1564
- environment: "live" | "sandbox";
1564
+ environment: "sandbox" | "live";
1565
1565
  };
1566
1566
  funnelId: string;
1567
1567
  versionId: string;
@@ -1571,7 +1571,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1571
1571
  entry: string;
1572
1572
  nodes: {
1573
1573
  id: string;
1574
- type: "output" | "action" | "screen" | "end" | "coupon" | "feature" | "split" | "condition" | "offering" | "coupons" | "entry" | "external_page" | "wait";
1574
+ type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "entry" | "external_page" | "wait";
1575
1575
  outputs: Record<string, string>;
1576
1576
  writes: Record<string, string>;
1577
1577
  resources: {
@@ -1616,7 +1616,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1616
1616
  } | undefined;
1617
1617
  };
1618
1618
  terminals: Record<string, {
1619
- outcome: "closed" | "failed" | "completed" | "ineligible";
1619
+ outcome: "failed" | "completed" | "closed" | "ineligible";
1620
1620
  output: {
1621
1621
  type: "literal";
1622
1622
  value: z.core.util.JSONType;
@@ -1 +1 @@
1
- import{h as H}from"./chunk-3ENVRJE6.js";import{a as b}from"./chunk-6X42DWOM.js";import"./chunk-CXYOZSOF.js";import{jc as D}from"./chunk-A3N4ZZTM.js";import{a as f}from"./chunk-OVMNCZYC.js";import{Eb as T,Mb as L,Ob as j,tb as k}from"./chunk-3BQFJANQ.js";import"./chunk-AE4CUTUE.js";import"./chunk-S5TVMQRC.js";import{a as I}from"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";import{z as l}from"zod";var x=new WeakMap;function P(o){let t={string:l.string(),number:l.number().finite(),boolean:l.boolean(),strings:l.array(l.string()),json:I}[o.type];return o.nullable?t.nullable():t}async function J(o,t){let S=D.parse(t.content),r=S.document;if(x.has(o))throw new f("CONFLICT","Content is already mounted in this container");let u=l.record(l.string(),I).parse(t.inputs??{});if(Object.keys(u).length>40)throw new f("INVALID_REQUEST","Too many content inputs");for(let[e,i]of Object.entries(u))L.parse({[e]:i});if(Object.keys(u).some(e=>!Object.hasOwn(r.contract.inputs,e)))throw new f("INVALID_REQUEST","Undeclared content input");for(let[e,i]of Object.entries(r.contract.inputs))if(Object.hasOwn(u,e))P(i).parse(u[e]);else if(i.required)throw new f("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(r.contract.outputs))if(typeof t.actions[e]!="function")throw new f("INVALID_REQUEST",`Missing host handler for ${e}`);let R=j.parse(t.bindings??[]),d=o.ownerDocument,v=d.activeElement,A=r.kind==="popup",n=A?d.createElement("dialog"):null,s=d.createElement("div");if(s.dataset.indianaContent=r.kind,s.setAttribute("aria-label",r.name),s.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",r.name);let e=r.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=`${k[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(s),o.append(n)}else o.append(s);let m=!1,g=!1,a=null,w=structuredClone(r.screen);w.actions=w.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let h;function E(){m||(m=!0,h?.destroy(),n?.close(),n?.remove(),s.remove(),x.delete(o),n&&v instanceof HTMLElement&&v.isConnected&&v.focus())}let C=()=>{E(),b(t.onDismiss)};if(n){let e=d.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",C),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),C()});async function V(){if(m||g||!a)return;let e=a;g=!0,s.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),a=null}catch(i){b(t.onError,i)}finally{g=!1,m||s.removeAttribute("aria-busy")}}try{n?.showModal(),h=H(s,{mode:"live",title:r.name,viewportHeight:r.kind==="page"?o.clientHeight||d.defaultView?.innerHeight||800:void 0,onError:c=>b(t.onError,new Error(c)),onEscape:A?C:void 0,onAction:(c,U,M)=>{if(m||g||a)return;let p=r.screen.actions.find(y=>y.id===c),O=r.contract.outputs[c];if(!(p?.type!=="event"||!O))try{let y=P(O).parse(Object.hasOwn(p.properties,"value")?p.properties.value:p.properties);a={requestId:crypto.randomUUID(),contentVersionId:S.id,actionId:c,event:p.event,value:y,selection:U??{},answers:M??{},requestedClose:p.close},V()}catch(y){b(t.onError,y)}}});let e={destroy:E,get pendingAction(){return a?structuredClone(a):null},retryAction:V,updateCapabilities:c=>h?.updateCapabilities(c)};x.set(o,e);let i=T(w,[t.locale,...d.defaultView?.navigator.languages??[]]);return h.update(w,i,{capabilities:t.capabilities,serverInput:{bindings:R,answers:{},values:u}}),await h.ready,e}catch(e){throw E(),e}}export{J as mountContent};
1
+ import{h as H}from"./chunk-X7JJAEQQ.js";import{a as b}from"./chunk-DSPLGTQI.js";import"./chunk-AEUFCOFG.js";import{jc as D}from"./chunk-F767CM3T.js";import{a as f}from"./chunk-6HG7U6AU.js";import{Eb as T,Mb as L,Ob as j,tb as k}from"./chunk-3BQFJANQ.js";import"./chunk-AE4CUTUE.js";import"./chunk-EXCPE2XH.js";import{a as I}from"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";import{z as l}from"zod";var x=new WeakMap;function P(o){let t={string:l.string(),number:l.number().finite(),boolean:l.boolean(),strings:l.array(l.string()),json:I}[o.type];return o.nullable?t.nullable():t}async function J(o,t){let S=D.parse(t.content),r=S.document;if(x.has(o))throw new f("CONFLICT","Content is already mounted in this container");let u=l.record(l.string(),I).parse(t.inputs??{});if(Object.keys(u).length>40)throw new f("INVALID_REQUEST","Too many content inputs");for(let[e,i]of Object.entries(u))L.parse({[e]:i});if(Object.keys(u).some(e=>!Object.hasOwn(r.contract.inputs,e)))throw new f("INVALID_REQUEST","Undeclared content input");for(let[e,i]of Object.entries(r.contract.inputs))if(Object.hasOwn(u,e))P(i).parse(u[e]);else if(i.required)throw new f("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(r.contract.outputs))if(typeof t.actions[e]!="function")throw new f("INVALID_REQUEST",`Missing host handler for ${e}`);let R=j.parse(t.bindings??[]),d=o.ownerDocument,v=d.activeElement,A=r.kind==="popup",n=A?d.createElement("dialog"):null,s=d.createElement("div");if(s.dataset.indianaContent=r.kind,s.setAttribute("aria-label",r.name),s.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",r.name);let e=r.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=`${k[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(s),o.append(n)}else o.append(s);let m=!1,g=!1,a=null,w=structuredClone(r.screen);w.actions=w.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let h;function E(){m||(m=!0,h?.destroy(),n?.close(),n?.remove(),s.remove(),x.delete(o),n&&v instanceof HTMLElement&&v.isConnected&&v.focus())}let C=()=>{E(),b(t.onDismiss)};if(n){let e=d.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",C),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),C()});async function V(){if(m||g||!a)return;let e=a;g=!0,s.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),a=null}catch(i){b(t.onError,i)}finally{g=!1,m||s.removeAttribute("aria-busy")}}try{n?.showModal(),h=H(s,{mode:"live",title:r.name,viewportHeight:r.kind==="page"?o.clientHeight||d.defaultView?.innerHeight||800:void 0,onError:c=>b(t.onError,new Error(c)),onEscape:A?C:void 0,onAction:(c,U,M)=>{if(m||g||a)return;let p=r.screen.actions.find(y=>y.id===c),O=r.contract.outputs[c];if(!(p?.type!=="event"||!O))try{let y=P(O).parse(Object.hasOwn(p.properties,"value")?p.properties.value:p.properties);a={requestId:crypto.randomUUID(),contentVersionId:S.id,actionId:c,event:p.event,value:y,selection:U??{},answers:M??{},requestedClose:p.close},V()}catch(y){b(t.onError,y)}}});let e={destroy:E,get pendingAction(){return a?structuredClone(a):null},retryAction:V,updateCapabilities:c=>h?.updateCapabilities(c)};x.set(o,e);let i=T(w,[t.locale,...d.defaultView?.navigator.languages??[]]);return h.update(w,i,{capabilities:t.capabilities,serverInput:{bindings:R,answers:{},values:u}}),await h.ready,e}catch(e){throw E(),e}}export{J as mountContent};