@tinkerlandai/indiana-sdk 0.7.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 (59) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/README.md +73 -25
  3. package/README.zh-CN.md +77 -25
  4. package/dist/ai-usage-JoM7ZWk-.d.ts +247 -0
  5. package/dist/{ai-usage-BsrSG955.d.ts → api-JVC7x2FV.d.ts} +337 -386
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-56AYS7RS.js +1 -0
  8. package/dist/{chunk-6MO6Y24B.js → chunk-6HG7U6AU.js} +1 -1
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-AEUFCOFG.js +1 -0
  11. package/dist/chunk-F767CM3T.js +7 -0
  12. package/dist/chunk-KSNOXNTC.js +1 -0
  13. package/dist/{chunk-4AWSZWZD.js → chunk-USLZX2ZA.js} +1 -1
  14. package/dist/{chunk-YAFMBXIE.js → chunk-X747SY26.js} +1 -1
  15. package/dist/chunk-X7JJAEQQ.js +350 -0
  16. package/dist/chunk-YWFNWK7C.js +1 -0
  17. package/dist/{configuration-sync-Bvd956GL.d.ts → configuration-sync-BexM2qbg.d.ts} +17 -18
  18. package/dist/content-YNL2CRJZ.js +1 -0
  19. package/dist/{customer-page-B4LkIr5q.d.ts → customer-page-WUQVK_tp.d.ts} +276 -3
  20. package/dist/{funnel-runtime-start-ChVYbLzV.d.ts → funnel-local-client-D1Fe7CZ6.d.ts} +2507 -8137
  21. package/dist/funnel-runtime-host-CAMI6BJS.js +1 -0
  22. package/dist/index.d.ts +13578 -13442
  23. package/dist/index.js +1 -1
  24. package/dist/native-shell.js +1 -1
  25. package/dist/openrouter.d.ts +5 -3
  26. package/dist/openrouter.js +1 -1
  27. package/dist/page.d.ts +4 -4
  28. package/dist/page.js +1 -1
  29. package/dist/paywall-MXRMMF3R.js +1 -0
  30. package/dist/popup.d.ts +3 -271
  31. package/dist/popup.js +1 -350
  32. package/dist/react-native.d.ts +7 -7
  33. package/dist/react-native.js +1 -1
  34. package/dist/{screen-iFngkxaL.d.ts → screen-i6eHL11m.d.ts} +120 -117
  35. package/dist/screen-renderer-P7MLBHY5.js +1 -0
  36. package/dist/server.d.ts +4645 -8
  37. package/dist/server.js +1 -1
  38. package/dist/src-G7UQB3QE.js +1 -0
  39. package/dist/visual.d.ts +5 -2
  40. package/dist/visual.js +2 -2
  41. package/package.json +3 -9
  42. package/dist/chunk-3SONNXFG.js +0 -1
  43. package/dist/chunk-467Z5ISI.js +0 -11
  44. package/dist/chunk-4K25DELJ.js +0 -1
  45. package/dist/chunk-HD74AAFS.js +0 -1
  46. package/dist/chunk-J4RHVU3W.js +0 -1
  47. package/dist/chunk-NOFNOHUI.js +0 -1
  48. package/dist/chunk-QO4YQLZ4.js +0 -1
  49. package/dist/chunk-U6S6AZM6.js +0 -1
  50. package/dist/chunk-WCFVNF5D.js +0 -1
  51. package/dist/client-F6UPJMHR.js +0 -1
  52. package/dist/controls-XG46TKUU.js +0 -2
  53. package/dist/funnel-runtime-host-26QI2W3S.js +0 -1
  54. package/dist/iam.d.ts +0 -131
  55. package/dist/iam.js +0 -1
  56. package/dist/paywall-WKOHBYW7.js +0 -1
  57. package/dist/src-UHLPVD6E.js +0 -1
  58. /package/dist/{chunk-6X42DWOM.js → chunk-DSPLGTQI.js} +0 -0
  59. /package/dist/{chunk-S5TVMQRC.js → chunk-EXCPE2XH.js} +0 -0
@@ -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{Qg as E,Rg as M,Sg as j,Tg as O,Ug as T}from"./chunk-467Z5ISI.js";import{a as u}from"./chunk-6MO6Y24B.js";import{h as w}from"./chunk-HD74AAFS.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};