@omni-commerce/sdk 0.13.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var OmniCommerceChat=(()=>{var S=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(t,e,n)=>e in t?S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ne=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},oe=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Z(e))!ee.call(t,r)&&r!==n&&S(t,r,{get:()=>e[r],enumerable:!(i=K(e,r))||i.enumerable});return t};var ie=t=>oe(S({},"__esModule",{value:!0}),t);var q=(t,e,n)=>te(t,typeof e!="symbol"?e+"":e,n);var le={};ne(le,{DEFAULT_WIDGET_OFFSET:()=>_,MAX_WIDGET_OFFSET:()=>j,createOmniApplicationChatEmbed:()=>z,createOmniChatEmbed:()=>H,createOmniChatWidget:()=>G,getOmniApplicationChatUrl:()=>W,getOmniChatEmbedCode:()=>X,getOmniChatEmbedUrl:()=>x,getOmniChatReactCode:()=>Y});function U(t,e){let n=JSON.stringify(t);if(typeof n!="string"||new TextEncoder().encode(n).length>e||/data:[^"\s]{0,100};base64,/i.test(n))throw new Error("Application data must be bounded JSON without base64 payloads.");return JSON.parse(n)}function R(t){let e=new Map;return async n=>{if(!(typeof n.requestId!="string"||n.requestId.length>200))try{if(n.type==="omni-chat:application-request"){let i=t.options.application;t.reply({type:"omni-chat:application-response",requestId:n.requestId,application:i?U({name:i.name,description:i.description,context:await i.getContext()??null,tools:Object.entries(t.options.frontendTools??{}).map(([r,a])=>({name:r,description:a.description,parameters:a.parameters}))},65536):void 0})}else if(n.type==="omni-chat:tool-request"){let i=n.toolName,r=n.toolCallId;if(typeof i!="string"||!/^app_[a-z][a-z0-9_]{0,59}$/.test(i)||typeof r!="string"||!r||r.length>200)throw new Error("Invalid application tool request.");let a=Object.hasOwn(t.options.frontendTools??{},i)?t.options.frontendTools?.[i]:void 0;if(!t.options.application||!a)throw new Error("This application action is unavailable.");let o=n.args;if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Invalid application action arguments.");let l=JSON.stringify({name:i,args:o}),d=e.get(r);if(d&&d.signature!==l)throw new Error("This tool call ID was already used.");let s=d?.result??Promise.resolve().then(()=>a.execute(o,{toolCallId:r,abortSignal:t.signal}));if(!d){if(e.size>=200)throw new Error("Start a new application chat.");e.set(r,{signature:l,result:s})}t.reply({type:"omni-chat:tool-response",requestId:n.requestId,toolCallId:r,result:U(await s??null,12e3)})}}catch(i){t.reply({type:n.type==="omni-chat:application-request"?"omni-chat:application-response":"omni-chat:tool-response",requestId:n.requestId,toolCallId:n.toolCallId,error:i instanceof Error?i.message:"The application action failed."})}}}function D(t,e){return e.deploymentId!==void 0?t?.deploymentId===e.deploymentId&&t.chatId===void 0:t?.chatId===e.chatId&&t.deploymentId===void 0}var E=class extends Error{constructor(n,i){super(n);q(this,"status",i)}};function P(t,e,n){let i=t.ownerDocument,r=i.defaultView;if(!r)throw new Error("A browser document is required to mount chat.");let a=i.createElement("iframe");a.src=n.url,a.title=e.title??"OmniCommerce assistant",a.referrerPolicy="strict-origin-when-cross-origin",a.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),Object.assign(a.style,{width:"100%",height:"100%",minHeight:"320px",border:"0",display:"block"});let o=new URL(a.src).origin,l=!1,d,s,m=new AbortController,u=R({options:e,signal:m.signal,reply:c=>{l||a.contentWindow?.postMessage({...c,...n.scope},o)}}),g=c=>{if(l||c.source!==a.contentWindow||c.origin!==o||!D(c.data,n.scope))return;if(c.data.type==="omni-chat:application-request"||c.data.type==="omni-chat:tool-request"){u(c.data);return}if(c.data.type==="omni-chat:close-request"){e.onRequestClose?.();return}if(c.data.type!=="omni-chat:session-request"||!n.mint)return;let b=typeof c.data.visitorId=="string"?c.data.visitorId:void 0;d??(d=n.mint(s,b,m.signal)),d.then(f=>{if(!l){if(typeof f?.token!="string"||!f.token||f.token.length>4096||typeof f.threadId!="string"||!f.threadId||!Number.isFinite(f.expiresIn)||f.expiresIn<=0)throw new Error("Invalid chat session response.");s=f.token,a.contentWindow?.postMessage({type:"omni-chat:session",...n.scope,session:f,...e.application?{applicationEnabled:!0}:{}},o)}}).catch(f=>{if(l)return;let p=f instanceof Error?f:new Error("Could not open chat.");p instanceof E&&[401,403].includes(p.status)&&(s=void 0),e.onError?.(p),a.contentWindow?.postMessage({type:"omni-chat:session-error",...n.scope,error:p.message,...e.application?{applicationEnabled:!0}:{}},o)}).finally(()=>{d=void 0})};return r.addEventListener("message",g),t.append(a),{iframe:a,focus(){l||(a.focus(),a.contentWindow?.postMessage({type:"omni-chat:focus-composer",...n.scope},o))},destroy(){l||(l=!0,m.abort(),s=void 0,r.removeEventListener("message",g),a.remove())}}}function B(t){let e=new URL(t),n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw new Error("Use an HTTPS origin, or HTTP localhost for development.");return e.origin}function I(t){return B(t??"https://omnicommerce.sg")}function W(t,e,n){if(!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(n))throw new Error("A valid application chat ID is required.");let i=new URL("/sdk/application-chat",I(t.baseUrl)),r=I(e);i.searchParams.set("parentOrigin",r),i.searchParams.set("chatId",n);let a=t.appId?.trim()??r;if(!a||a.length>200)throw new Error("appId must contain 1\u2013200 characters.");i.searchParams.set("appId",a);for(let o of["organizationId","agentId"]){if(t[o]===void 0)continue;let l=t[o].trim();if(!l||l.length>120)throw new Error(`${o} must contain 1\u2013120 characters.`);i.searchParams.set(o,l)}return i.toString()}function z(t,e){let n=t.ownerDocument.defaultView;if(!n)throw new Error("A browser document is required to mount chat.");let i=n.crypto.randomUUID();return P(t,e,{url:W(e,n.location.origin,i),scope:{chatId:i}})}var re={chat:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z",close:"m6 6 12 12M6 18 18 6",collapse:"m6 9 6 6 6-6"};function k(t,e){let n=t.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.8"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true");let i=t.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d",re[e]),n.append(i),n}var F="(max-width: 640px), (max-height: 480px) and (pointer: coarse)",N=`
1
+ "use strict";var OmniCommerceChat=(()=>{var P=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(t,e,n)=>e in t?P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ne=(t,e)=>{for(var n in e)P(t,n,{get:e[n],enumerable:!0})},oe=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Z(e))!ee.call(t,r)&&r!==n&&P(t,r,{get:()=>e[r],enumerable:!(i=K(e,r))||i.enumerable});return t};var ie=t=>oe(P({},"__esModule",{value:!0}),t);var U=(t,e,n)=>te(t,typeof e!="symbol"?e+"":e,n);var le={};ne(le,{DEFAULT_WIDGET_OFFSET:()=>_,MAX_WIDGET_OFFSET:()=>j,createOmniApplicationChatEmbed:()=>z,createOmniChatEmbed:()=>M,createOmniChatWidget:()=>G,getOmniApplicationChatUrl:()=>F,getOmniChatEmbedCode:()=>X,getOmniChatEmbedUrl:()=>x,getOmniChatReactCode:()=>Y});function W(t,e){let n=JSON.stringify(t);if(typeof n!="string"||new TextEncoder().encode(n).length>e||/data:[^"\s]{0,100};base64,/i.test(n))throw new Error("Application data must be bounded JSON without base64 payloads.");return JSON.parse(n)}function R(t){let e=new Map;return async n=>{if(!(typeof n.requestId!="string"||n.requestId.length>200))try{if(n.type==="omni-chat:application-request"){let i=t.options.application;t.reply({type:"omni-chat:application-response",requestId:n.requestId,...t.assistant?{assistant:W(t.assistant(),65536)}:{},application:i?W({name:i.name,description:i.description,context:await i.getContext()??null,tools:Object.entries(t.options.frontendTools??{}).map(([r,a])=>({name:r,description:a.description,parameters:a.parameters}))},65536):void 0})}else if(n.type==="omni-chat:tool-request"){let i=n.toolName,r=n.toolCallId;if(typeof i!="string"||!/^app_[a-z][a-z0-9_]{0,59}$/.test(i)||typeof r!="string"||!r||r.length>200)throw new Error("Invalid application tool request.");let a=Object.hasOwn(t.options.frontendTools??{},i)?t.options.frontendTools?.[i]:void 0;if(!t.options.application||!a)throw new Error("This application action is unavailable.");let o=n.args;if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Invalid application action arguments.");let l=JSON.stringify({name:i,args:o}),d=e.get(r);if(d&&d.signature!==l)throw new Error("This tool call ID was already used.");let s=d?.result??Promise.resolve().then(()=>a.execute(o,{toolCallId:r,abortSignal:t.signal}));if(!d){if(e.size>=200)throw new Error("Start a new application chat.");e.set(r,{signature:l,result:s})}t.reply({type:"omni-chat:tool-response",requestId:n.requestId,toolCallId:r,result:W(await s??null,12e3)})}}catch(i){t.reply({type:n.type==="omni-chat:application-request"?"omni-chat:application-response":"omni-chat:tool-response",requestId:n.requestId,toolCallId:n.toolCallId,error:i instanceof Error?i.message:"The application action failed."})}}}function D(t,e){return e.deploymentId!==void 0?t?.deploymentId===e.deploymentId&&t.chatId===void 0:t?.chatId===e.chatId&&t.deploymentId===void 0}var E=class extends Error{constructor(n,i){super(n);U(this,"status",i)}};function S(t,e,n){let i=t.ownerDocument,r=i.defaultView;if(!r)throw new Error("A browser document is required to mount chat.");let a=i.createElement("iframe");a.src=n.url,a.title=e.title??"OmniCommerce assistant",a.referrerPolicy="strict-origin-when-cross-origin",a.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),Object.assign(a.style,{width:"100%",height:"100%",minHeight:"320px",border:"0",display:"block"});let o=new URL(a.src).origin,l=!1,d,s,m=new AbortController,u=R({options:e,assistant:n.assistant,signal:m.signal,reply:c=>{l||a.contentWindow?.postMessage({...c,...n.scope},o)}}),g=c=>{if(l||c.source!==a.contentWindow||c.origin!==o||!D(c.data,n.scope))return;if(c.data.type==="omni-chat:application-request"||c.data.type==="omni-chat:tool-request"){u(c.data);return}if(c.data.type==="omni-chat:close-request"){e.onRequestClose?.();return}if(c.data.type!=="omni-chat:session-request"||!n.mint)return;let b=typeof c.data.visitorId=="string"?c.data.visitorId:void 0;d??(d=n.mint(s,b,m.signal)),d.then(f=>{if(!l){if(typeof f?.token!="string"||!f.token||f.token.length>4096||typeof f.threadId!="string"||!f.threadId||!Number.isFinite(f.expiresIn)||f.expiresIn<=0)throw new Error("Invalid chat session response.");s=f.token,a.contentWindow?.postMessage({type:"omni-chat:session",...n.scope,session:f,...e.application?{applicationEnabled:!0}:{}},o)}}).catch(f=>{if(l)return;let p=f instanceof Error?f:new Error("Could not open chat.");p instanceof E&&[401,403].includes(p.status)&&(s=void 0),e.onError?.(p),a.contentWindow?.postMessage({type:"omni-chat:session-error",...n.scope,error:p.message,...e.application?{applicationEnabled:!0}:{}},o)}).finally(()=>{d=void 0})};return r.addEventListener("message",g),t.append(a),{iframe:a,focus(){l||(a.focus(),a.contentWindow?.postMessage({type:"omni-chat:focus-composer",...n.scope},o))},destroy(){l||(l=!0,m.abort(),s=void 0,r.removeEventListener("message",g),a.remove())}}}function B(t){let e=new URL(t),n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw new Error("Use an HTTPS origin, or HTTP localhost for development.");return e.origin}function I(t){return B(t??"https://omnicommerce.sg")}function F(t,e,n){if(!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(n))throw new Error("A valid application chat ID is required.");let i=new URL("/sdk/application-chat",I(t.baseUrl)),r=I(e);i.searchParams.set("parentOrigin",r),i.searchParams.set("chatId",n);let a=t.appId?.trim()??r;if(!a||a.length>200)throw new Error("appId must contain 1\u2013200 characters.");i.searchParams.set("appId",a);for(let o of["organizationId","agentId"]){if(t[o]===void 0)continue;let l=t[o].trim();if(!l||l.length>120)throw new Error(`${o} must contain 1\u2013120 characters.`);i.searchParams.set(o,l)}return i.toString()}function z(t,e){let n=t.ownerDocument.defaultView;if(!n)throw new Error("A browser document is required to mount chat.");let i=n.crypto.randomUUID();return S(t,e,{url:F(e,n.location.origin,i),scope:{chatId:i},assistant:()=>({...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.tools!==void 0?{tools:e.tools}:{}})})}var re={chat:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z",close:"m6 6 12 12M6 18 18 6",collapse:"m6 9 6 6 6-6"};function k(t,e){let n=t.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.8"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true");let i=t.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d",re[e]),n.append(i),n}var $="(max-width: 640px), (max-height: 480px) and (pointer: coarse)",N=`
2
2
  :host {
3
3
  all: initial; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color-scheme: light dark;
4
4
  --omni-active-bottom-offset: var(--omni-bottom-offset);
@@ -68,7 +68,7 @@
68
68
  @keyframes omni-sidebar-enter-left { from { opacity: 0; transform: translateX(-100%); } to { opacity: 1; transform: none; } }
69
69
  @keyframes omni-chat-enter { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
70
70
  @keyframes omni-chat-mobile-enter { from { opacity: 0; } to { opacity: 1; } }
71
- @media ${F} {
71
+ @media ${$} {
72
72
  :host {
73
73
  --omni-active-bottom-offset: var(--omni-mobile-bottom-offset);
74
74
  --omni-active-side-offset: var(--omni-mobile-side-offset);
@@ -91,7 +91,7 @@
91
91
  .close { top: calc(18px + env(safe-area-inset-top, 0px)); right: calc(14px + env(safe-area-inset-right, 0px)); }
92
92
  }
93
93
  @media (prefers-reduced-motion: reduce) { :host([data-presentation][data-position]) .panel { animation: none; transition: none; } .launcher { transition: none; } }
94
- `;var _=20,j=500;function L(t){let e=n=>{if(n===void 0)return 20;if(!Number.isInteger(n)||n<0||n>500)throw new Error("Chat spacing must be whole pixels between 0 and 500.");return n};return{bottomOffset:e(t.bottomOffset),sideOffset:e(t.sideOffset),mobileBottomOffset:e(t.mobileBottomOffset),mobileSideOffset:e(t.mobileSideOffset)}}async function V(t,e,n,i){let r=await t.fetch(`${e}/api/embed/${n}`,{credentials:"include",cache:"no-store",signal:i}),a=await r.json();if(!r.ok)throw new Error(a.error??"Could not load the chat design.");let o=a.design,l=/^#[0-9a-f]{6}$/i;if(!o||typeof o.title!="string"||!o.title.trim()||o.title.length>80||typeof o.launcherLabel!="string"||!o.launcherLabel.trim()||o.launcherLabel.length>60||!["left","right"].includes(o.position)||!["floating","sidebar"].includes(o.presentation)||!o.theme||![o.theme.primary,o.theme.primaryForeground,o.theme.background,o.theme.foreground].every(d=>typeof d=="string"&&l.test(d)))throw new Error("Invalid chat design response.");return{...L(o),deploymentId:n,title:o.title,launcherLabel:o.launcherLabel,position:o.position,presentation:o.presentation,launcherBackground:o.theme.primary,launcherForeground:o.theme.primaryForeground,panelBackground:o.theme.background,panelForeground:o.theme.foreground}}var $=new WeakMap;function ae(t){let e=$.get(t);if(!e){let n=[t.documentElement.style,t.body.style],i=n.map(r=>({value:r.getPropertyValue("overflow"),priority:r.getPropertyPriority("overflow")}));n.forEach(r=>r.setProperty("overflow","hidden","important")),e={count:0,release(){n.forEach((r,a)=>{let{value:o,priority:l}=i[a];o?r.setProperty("overflow",o,l):r.removeProperty("overflow")})}},$.set(t,e)}return e.count++,()=>{--e.count===0&&(e.release(),$.delete(t))}}function J(t,e,n){let i=t.ownerDocument.defaultView,r=i.matchMedia(F),a=i.visualViewport,o=!1,l,d,s=()=>{d!==void 0&&(i.cancelAnimationFrame(d),d=void 0)},m=()=>{t.style.removeProperty("--omni-viewport-shift"),t.style.removeProperty("--omni-viewport-height")},u=()=>{if(e.hidden||!r.matches||!a||a.scale!==1){m();return}let p=t.ownerDocument,w=(p.compatMode==="CSS1Compat"?p.documentElement:p.body).clientHeight||i.innerHeight,y=Math.min(0,a.offsetTop+a.height-w);t.style.setProperty("--omni-viewport-shift",`${y}px`);let v=`${w}px`;t.style.getPropertyValue("--omni-viewport-height")!==v&&t.style.setProperty("--omni-viewport-height",v)},g=()=>{d===void 0&&(d=i.requestAnimationFrame(()=>{d=void 0,u()}))},c=()=>{if(e.hidden)return;let p=null;e.open&&o!==r.matches&&(p=t.shadowRoot?.activeElement,e.close()),o=r.matches,o?l??(l=ae(t.ownerDocument)):(l?.(),l=void 0),s(),u(),e.open||(o?e.showModal():e.show()),p&&e.contains(p)&&p.focus()},b=p=>{p.preventDefault(),n()},f=()=>{s(),e.hidden=!0,e.open&&e.close(),l?.(),l=void 0,m()};return r.addEventListener("change",c),a?.addEventListener("resize",g),a?.addEventListener("scroll",g),e.addEventListener("cancel",b),{open(){e.hidden=!1,c()},close:f,destroy(){f(),r.removeEventListener("change",c),a?.removeEventListener("resize",g),a?.removeEventListener("scroll",g),e.removeEventListener("cancel",b)}}}var se=0;function G(t,e){let n=new URL(x(e)).origin,i=t.ownerDocument,r=i.defaultView;if(!r)throw new Error("A browser document is required to mount chat.");let a=new AbortController,o=i.createElement("div");o.setAttribute("data-omni-chat-widget","");let l=o.attachShadow({mode:"open"}),d=i.createElement("style");d.textContent=N;let s=i.createElement("button"),m=i.createElement("dialog"),u=i.createElement("button"),g=i.createElement("div"),c,b=!1,f=!1,p=!1,h=e;Object.assign(o.style,{position:"fixed",zIndex:"2147483000"}),s.type=u.type="button",s.className="launcher";let w=i.createElement("span");w.className="label",w.textContent=e.launcherLabel??"Chat with us",s.append(k(i,"chat"),w),s.setAttribute("aria-expanded","false"),s.setAttribute("aria-label",w.textContent),m.hidden=!0,m.className="panel",m.setAttribute("aria-label",e.title??"Assistant chat"),m.id=`omni-chat-widget-${++se}`,s.setAttribute("aria-controls",m.id),g.className="frame",u.className="close",u.setAttribute("aria-label","Close chat"),u.title="Close chat",u.append(k(i,"close"));let y=()=>{b||(p=!1,v.close(),s.hidden=!1,s.setAttribute("aria-expanded","false"),s.setAttribute("aria-label",w.textContent),s.querySelector("svg")?.replaceWith(k(i,"chat")),s.focus())},v=J(o,m,y),T=()=>{if(!b){if(!f){p=!0;return}c??(c=H(g,{...h,onRequestClose:y})),c.iframe.style.minHeight="0",v.open(),s.hidden=h.presentation==="sidebar",s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label","Close chat"),s.querySelector("svg")?.replaceWith(k(i,"collapse")),c.focus()}};s.addEventListener("click",()=>m.hidden?T():y()),u.addEventListener("click",y),l.addEventListener("keydown",O=>{O.key==="Escape"&&!m.hidden&&y()}),m.append(u,g),l.append(d,m,s);let M=V(r,n,e.deploymentId,a.signal).then(O=>{if(b)return;h=Object.assign(O,Object.fromEntries(Object.entries(e).filter(([,Q])=>Q!==void 0))),o.dataset.position=h.position??"right",o.dataset.presentation=h.presentation??"floating";let A=L(h);o.style.setProperty("--omni-bottom-offset",`${A.bottomOffset}px`),o.style.setProperty("--omni-side-offset",`${A.sideOffset}px`),o.style.setProperty("--omni-mobile-bottom-offset",`${A.mobileBottomOffset}px`),o.style.setProperty("--omni-mobile-side-offset",`${A.mobileSideOffset}px`),o.style.setProperty("--omni-launcher-bg",h.launcherBackground),o.style.setProperty("--omni-launcher-fg",h.launcherForeground),o.style.setProperty("--omni-panel-bg",h.panelBackground),o.style.setProperty("--omni-panel-fg",h.panelForeground),w.textContent=h.launcherLabel,s.setAttribute("aria-label",w.textContent),m.setAttribute("aria-label",h.title),f=!0,t.append(o),p&&T()});return M.catch(O=>{b||e.onError?.(O instanceof Error?O:new Error("Could not load chat."))}),{ready:M,open:T,close:y,destroy(){b=!0,a.abort(),v.destroy(),c?.destroy(),o.remove()}}}var C=t=>JSON.stringify(t,null,2).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`);function X(t,e="widget"){let n=new URL(x(t)).origin,i={...t,baseUrl:n},r=`omni-chat-${t.deploymentId}`,a=e==="widget"?`OmniCommerceChat.createOmniChatWidget(document.body, ${C(i)});`:`OmniCommerceChat.createOmniChatEmbed(document.getElementById(${C(r)}), ${C(i)});`;return`${e==="inline"?`<div id="${r}" style="height:600px"></div>
94
+ `;var _=20,j=500;function L(t){let e=n=>{if(n===void 0)return 20;if(!Number.isInteger(n)||n<0||n>500)throw new Error("Chat spacing must be whole pixels between 0 and 500.");return n};return{bottomOffset:e(t.bottomOffset),sideOffset:e(t.sideOffset),mobileBottomOffset:e(t.mobileBottomOffset),mobileSideOffset:e(t.mobileSideOffset)}}async function V(t,e,n,i){let r=await t.fetch(`${e}/api/embed/${n}`,{credentials:"include",cache:"no-store",signal:i}),a=await r.json();if(!r.ok)throw new Error(a.error??"Could not load the chat design.");let o=a.design,l=/^#[0-9a-f]{6}$/i;if(!o||typeof o.title!="string"||!o.title.trim()||o.title.length>80||typeof o.launcherLabel!="string"||!o.launcherLabel.trim()||o.launcherLabel.length>60||!["left","right"].includes(o.position)||!["floating","sidebar"].includes(o.presentation)||!o.theme||![o.theme.primary,o.theme.primaryForeground,o.theme.background,o.theme.foreground].every(d=>typeof d=="string"&&l.test(d)))throw new Error("Invalid chat design response.");return{...L(o),deploymentId:n,title:o.title,launcherLabel:o.launcherLabel,position:o.position,presentation:o.presentation,launcherBackground:o.theme.primary,launcherForeground:o.theme.primaryForeground,panelBackground:o.theme.background,panelForeground:o.theme.foreground}}var H=new WeakMap;function ae(t){let e=H.get(t);if(!e){let n=[t.documentElement.style,t.body.style],i=n.map(r=>({value:r.getPropertyValue("overflow"),priority:r.getPropertyPriority("overflow")}));n.forEach(r=>r.setProperty("overflow","hidden","important")),e={count:0,release(){n.forEach((r,a)=>{let{value:o,priority:l}=i[a];o?r.setProperty("overflow",o,l):r.removeProperty("overflow")})}},H.set(t,e)}return e.count++,()=>{--e.count===0&&(e.release(),H.delete(t))}}function J(t,e,n){let i=t.ownerDocument.defaultView,r=i.matchMedia($),a=i.visualViewport,o=!1,l,d,s=()=>{d!==void 0&&(i.cancelAnimationFrame(d),d=void 0)},m=()=>{t.style.removeProperty("--omni-viewport-shift"),t.style.removeProperty("--omni-viewport-height")},u=()=>{if(e.hidden||!r.matches||!a||a.scale!==1){m();return}let p=t.ownerDocument,y=(p.compatMode==="CSS1Compat"?p.documentElement:p.body).clientHeight||i.innerHeight,w=Math.min(0,a.offsetTop+a.height-y);t.style.setProperty("--omni-viewport-shift",`${w}px`);let v=`${y}px`;t.style.getPropertyValue("--omni-viewport-height")!==v&&t.style.setProperty("--omni-viewport-height",v)},g=()=>{d===void 0&&(d=i.requestAnimationFrame(()=>{d=void 0,u()}))},c=()=>{if(e.hidden)return;let p=null;e.open&&o!==r.matches&&(p=t.shadowRoot?.activeElement,e.close()),o=r.matches,o?l??(l=ae(t.ownerDocument)):(l?.(),l=void 0),s(),u(),e.open||(o?e.showModal():e.show()),p&&e.contains(p)&&p.focus()},b=p=>{p.preventDefault(),n()},f=()=>{s(),e.hidden=!0,e.open&&e.close(),l?.(),l=void 0,m()};return r.addEventListener("change",c),a?.addEventListener("resize",g),a?.addEventListener("scroll",g),e.addEventListener("cancel",b),{open(){e.hidden=!1,c()},close:f,destroy(){f(),r.removeEventListener("change",c),a?.removeEventListener("resize",g),a?.removeEventListener("scroll",g),e.removeEventListener("cancel",b)}}}var se=0;function G(t,e){let n=new URL(x(e)).origin,i=t.ownerDocument,r=i.defaultView;if(!r)throw new Error("A browser document is required to mount chat.");let a=new AbortController,o=i.createElement("div");o.setAttribute("data-omni-chat-widget","");let l=o.attachShadow({mode:"open"}),d=i.createElement("style");d.textContent=N;let s=i.createElement("button"),m=i.createElement("dialog"),u=i.createElement("button"),g=i.createElement("div"),c,b=!1,f=!1,p=!1,h=e;Object.assign(o.style,{position:"fixed",zIndex:"2147483000"}),s.type=u.type="button",s.className="launcher";let y=i.createElement("span");y.className="label",y.textContent=e.launcherLabel??"Chat with us",s.append(k(i,"chat"),y),s.setAttribute("aria-expanded","false"),s.setAttribute("aria-label",y.textContent),m.hidden=!0,m.className="panel",m.setAttribute("aria-label",e.title??"Assistant chat"),m.id=`omni-chat-widget-${++se}`,s.setAttribute("aria-controls",m.id),g.className="frame",u.className="close",u.setAttribute("aria-label","Close chat"),u.title="Close chat",u.append(k(i,"close"));let w=()=>{b||(p=!1,v.close(),s.hidden=!1,s.setAttribute("aria-expanded","false"),s.setAttribute("aria-label",y.textContent),s.querySelector("svg")?.replaceWith(k(i,"chat")),s.focus())},v=J(o,m,w),T=()=>{if(!b){if(!f){p=!0;return}c??(c=M(g,{...h,onRequestClose:w})),c.iframe.style.minHeight="0",v.open(),s.hidden=h.presentation==="sidebar",s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label","Close chat"),s.querySelector("svg")?.replaceWith(k(i,"collapse")),c.focus()}};s.addEventListener("click",()=>m.hidden?T():w()),u.addEventListener("click",w),l.addEventListener("keydown",O=>{O.key==="Escape"&&!m.hidden&&w()}),m.append(u,g),l.append(d,m,s);let q=V(r,n,e.deploymentId,a.signal).then(O=>{if(b)return;h=Object.assign(O,Object.fromEntries(Object.entries(e).filter(([,Q])=>Q!==void 0))),o.dataset.position=h.position??"right",o.dataset.presentation=h.presentation??"floating";let A=L(h);o.style.setProperty("--omni-bottom-offset",`${A.bottomOffset}px`),o.style.setProperty("--omni-side-offset",`${A.sideOffset}px`),o.style.setProperty("--omni-mobile-bottom-offset",`${A.mobileBottomOffset}px`),o.style.setProperty("--omni-mobile-side-offset",`${A.mobileSideOffset}px`),o.style.setProperty("--omni-launcher-bg",h.launcherBackground),o.style.setProperty("--omni-launcher-fg",h.launcherForeground),o.style.setProperty("--omni-panel-bg",h.panelBackground),o.style.setProperty("--omni-panel-fg",h.panelForeground),y.textContent=h.launcherLabel,s.setAttribute("aria-label",y.textContent),m.setAttribute("aria-label",h.title),f=!0,t.append(o),p&&T()});return q.catch(O=>{b||e.onError?.(O instanceof Error?O:new Error("Could not load chat."))}),{ready:q,open:T,close:w,destroy(){b=!0,a.abort(),v.destroy(),c?.destroy(),o.remove()}}}var C=t=>JSON.stringify(t,null,2).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`);function X(t,e="widget"){let n=new URL(x(t)).origin,i={...t,baseUrl:n},r=`omni-chat-${t.deploymentId}`,a=e==="widget"?`OmniCommerceChat.createOmniChatWidget(document.body, ${C(i)});`:`OmniCommerceChat.createOmniChatEmbed(document.getElementById(${C(r)}), ${C(i)});`;return`${e==="inline"?`<div id="${r}" style="height:600px"></div>
95
95
  `:""}<script src="${n}/sdk/embed.global.js"><\/script>
96
96
  <script>
97
97
  ${a.replace(/\n/g,`
@@ -102,5 +102,5 @@
102
102
  baseUrl={${C(e)}}${t.title?`
103
103
  title={${C(t.title)}}`:""}>
104
104
  <OmniChat style={{ height: 600 }} />
105
- </OmniProvider>`}function x(t,e){if(!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(t.deploymentId))throw new Error("A valid chat deployment ID is required.");let n=I(t.baseUrl),i=new URL(`/embed/${t.deploymentId}`,n);return e&&i.searchParams.set("parentOrigin",new URL(e).origin),i.toString()}function H(t,e){let n=t.ownerDocument.defaultView;if(!n)throw new Error("A browser document is required to mount chat.");let i=x(e,n.location.origin),r=new URL(i).origin;return P(t,e,{url:i,scope:{deploymentId:e.deploymentId},mint:async(a,o,l)=>{if(e.getSession)return e.getSession();let d=await n.fetch(`${r}/api/embed/${e.deploymentId}/session`,{method:"POST",credentials:"include",signal:l,headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify(o&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o)?{visitorId:o}:{})}),s=await d.json();if(!d.ok)throw new E(s.error??"Could not open the chat session.",d.status);return s}})}return ie(le);})();
105
+ </OmniProvider>`}function x(t,e){if(!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(t.deploymentId))throw new Error("A valid chat deployment ID is required.");let n=I(t.baseUrl),i=new URL(`/embed/${t.deploymentId}`,n);return e&&i.searchParams.set("parentOrigin",new URL(e).origin),i.toString()}function M(t,e){let n=t.ownerDocument.defaultView;if(!n)throw new Error("A browser document is required to mount chat.");let i=x(e,n.location.origin),r=new URL(i).origin;return S(t,e,{url:i,scope:{deploymentId:e.deploymentId},mint:async(a,o,l)=>{if(e.getSession)return e.getSession();let d=await n.fetch(`${r}/api/embed/${e.deploymentId}/session`,{method:"POST",credentials:"include",signal:l,headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify(o&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o)?{visitorId:o}:{})}),s=await d.json();if(!d.ok)throw new E(s.error??"Could not open the chat session.",d.status);return s}})}return ie(le);})();
106
106
  //# sourceMappingURL=embed.global.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed.ts","../src/application.ts","../../../lib/assistant/application-chat/bridge-scope.ts","../src/hosted-chat.ts","../../../lib/assistant/hosted-chat-origin.ts","../src/chat-origin.ts","../src/application-embed.ts","../src/widget-chrome.ts","../src/widget-placement.ts","../src/widget-config.ts","../src/widget-panel.ts","../src/widget.ts","../src/embed-code.ts"],"sourcesContent":["import { mountHostedChat, ChatSessionError } from \"./hosted-chat\";\nimport { chatOrigin } from \"./chat-origin\";\nimport { type OmniApplicationOptions } from \"./application\";\nexport type {\n OmniFrontendTool,\n OmniChatApplication,\n OmniApplicationOptions,\n} from \"./application\";\n/** A hosted chat session. Keep its short-lived token in memory, never in iframe URLs. */\nexport {\n createOmniApplicationChatEmbed,\n getOmniApplicationChatUrl,\n type OmniApplicationChatOptions,\n} from \"./application-embed\";\nexport { createOmniChatWidget, type OmniChatWidgetOptions } from \"./widget\";\nexport {\n DEFAULT_WIDGET_OFFSET,\n MAX_WIDGET_OFFSET,\n type OmniChatWidgetPlacement,\n} from \"./widget-placement\";\nexport { getOmniChatEmbedCode, getOmniChatReactCode } from \"./embed-code\";\nexport interface OmniChatSession {\n token: string;\n threadId: string;\n expiresIn: number;\n}\nexport interface OmniChatEmbedOptions extends OmniApplicationOptions {\n deploymentId: string;\n baseUrl?: string;\n /** Optional authenticated session mint on the host application's server. */\n getSession?: () => Promise<OmniChatSession>;\n title?: string;\n onError?: (error: Error) => void;\n /** Floating widgets use this to close on Escape from the hosted chat. */\n onRequestClose?: () => void;\n}\nexport interface OmniChatEmbed {\n iframe: HTMLIFrameElement;\n /** Focus the hosted composer, including when reopening a retained chat. */\n focus(): void;\n destroy(): void;\n}\n\nexport function getOmniChatEmbedUrl(\n options: Pick<OmniChatEmbedOptions, \"baseUrl\" | \"deploymentId\">,\n parentOrigin?: string,\n): string {\n if (\n !/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/i.test(\n options.deploymentId,\n )\n )\n throw new Error(\"A valid chat deployment ID is required.\");\n const base = chatOrigin(options.baseUrl);\n const url = new URL(`/embed/${options.deploymentId}`, base);\n if (parentOrigin)\n url.searchParams.set(\"parentOrigin\", new URL(parentOrigin).origin);\n return url.toString();\n}\n\n/** Browser-only mounting; importing this entry point is safe during SSR. */\nexport function createOmniChatEmbed(\n container: HTMLElement,\n options: OmniChatEmbedOptions,\n): OmniChatEmbed {\n const host = container.ownerDocument.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const url = getOmniChatEmbedUrl(options, host.location.origin);\n const chatOrigin = new URL(url).origin;\n return mountHostedChat(container, options, {\n url,\n scope: { deploymentId: options.deploymentId },\n mint: async (previousToken, visitorId, signal) => {\n if (options.getSession) return options.getSession();\n const response = await host.fetch(\n `${chatOrigin}/api/embed/${options.deploymentId}/session`,\n {\n method: \"POST\",\n credentials: \"include\",\n signal,\n headers: {\n \"Content-Type\": \"application/json\",\n ...(previousToken\n ? { Authorization: `Bearer ${previousToken}` }\n : {}),\n },\n body: JSON.stringify(\n visitorId &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n visitorId,\n )\n ? { visitorId }\n : {},\n ),\n },\n );\n const result = (await response.json()) as OmniChatSession & {\n error?: string;\n };\n if (!response.ok)\n throw new ChatSessionError(\n result.error ?? \"Could not open the chat session.\",\n response.status,\n );\n return result;\n },\n });\n}\n","/** Host-defined actions execute inside the application, never on the assistant server. */\nexport interface OmniFrontendTool {\n description: string;\n parameters: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n context: { toolCallId: string; abortSignal: AbortSignal },\n ) => unknown | Promise<unknown>;\n}\nexport interface OmniChatApplication {\n name: string;\n description: string;\n /** Return a small, explicitly selected snapshot. Do not include secrets. */\n getContext: () => unknown | Promise<unknown>;\n}\nexport interface OmniApplicationOptions {\n application?: OmniChatApplication;\n /** Names must start with app_; use array arguments for actions with multiple targets. */\n frontendTools?: Record<string, OmniFrontendTool>;\n}\n\nfunction boundedJson(value: unknown, maximum: number): unknown {\n const encoded = JSON.stringify(value);\n if (\n typeof encoded !== \"string\" ||\n new TextEncoder().encode(encoded).length > maximum ||\n /data:[^\"\\s]{0,100};base64,/i.test(encoded)\n )\n throw new Error(\n \"Application data must be bounded JSON without base64 payloads.\",\n );\n return JSON.parse(encoded);\n}\n\nexport function createApplicationMessageHandler(input: {\n options: OmniApplicationOptions;\n signal: AbortSignal;\n reply: (message: Record<string, unknown>) => void;\n}) {\n // A repeated parked call reuses its result instead of applying an action twice.\n const calls = new Map<\n string,\n { signature: string; result: Promise<unknown> }\n >();\n return async (message: Record<string, unknown>) => {\n if (typeof message.requestId !== \"string\" || message.requestId.length > 200)\n return;\n try {\n if (message.type === \"omni-chat:application-request\") {\n const application = input.options.application;\n input.reply({\n type: \"omni-chat:application-response\",\n requestId: message.requestId,\n application: application\n ? boundedJson(\n {\n name: application.name,\n description: application.description,\n context: (await application.getContext()) ?? null,\n tools: Object.entries(input.options.frontendTools ?? {}).map(\n ([name, definition]) => ({\n name,\n description: definition.description,\n parameters: definition.parameters,\n }),\n ),\n },\n 65536,\n )\n : undefined,\n });\n } else if (message.type === \"omni-chat:tool-request\") {\n const name = message.toolName;\n const toolCallId = message.toolCallId;\n if (\n typeof name !== \"string\" ||\n !/^app_[a-z][a-z0-9_]{0,59}$/.test(name) ||\n typeof toolCallId !== \"string\" ||\n !toolCallId ||\n toolCallId.length > 200\n )\n throw new Error(\"Invalid application tool request.\");\n const definition = Object.hasOwn(\n input.options.frontendTools ?? {},\n name,\n )\n ? input.options.frontendTools?.[name]\n : undefined;\n if (!input.options.application || !definition)\n throw new Error(\"This application action is unavailable.\");\n const args = message.args;\n if (!args || typeof args !== \"object\" || Array.isArray(args))\n throw new Error(\"Invalid application action arguments.\");\n const signature = JSON.stringify({ name, args });\n const prior = calls.get(toolCallId);\n if (prior && prior.signature !== signature)\n throw new Error(\"This tool call ID was already used.\");\n const result =\n prior?.result ??\n Promise.resolve().then(() =>\n definition.execute(args as Record<string, unknown>, {\n toolCallId,\n abortSignal: input.signal,\n }),\n );\n if (!prior) {\n if (calls.size >= 200)\n throw new Error(\"Start a new application chat.\");\n calls.set(toolCallId, { signature, result });\n }\n input.reply({\n type: \"omni-chat:tool-response\",\n requestId: message.requestId,\n toolCallId,\n result: boundedJson((await result) ?? null, 12000),\n });\n }\n } catch (error) {\n input.reply({\n type:\n message.type === \"omni-chat:application-request\"\n ? \"omni-chat:application-response\"\n : \"omni-chat:tool-response\",\n requestId: message.requestId,\n toolCallId: message.toolCallId,\n error:\n error instanceof Error\n ? error.message\n : \"The application action failed.\",\n });\n }\n };\n}\n","/** Scope each hosted frame independently; application chats have no deployment. */\nexport type HostedChatScope =\n | { deploymentId: string; chatId?: never }\n | { chatId: string; deploymentId?: never };\n\nexport function hostedChatId(scope: HostedChatScope) {\n return scope.deploymentId ?? scope.chatId;\n}\n\nexport function matchesHostedChatScope(\n message: Record<string, unknown> | null | undefined,\n scope: HostedChatScope,\n) {\n return scope.deploymentId !== undefined\n ? message?.deploymentId === scope.deploymentId &&\n message.chatId === undefined\n : message?.chatId === scope.chatId && message.deploymentId === undefined;\n}\n","import {\n createApplicationMessageHandler,\n type OmniApplicationOptions,\n} from \"./application\";\nimport {\n matchesHostedChatScope,\n type HostedChatScope,\n} from \"../../../lib/assistant/application-chat/bridge-scope\";\nimport type { OmniChatEmbed, OmniChatSession } from \"./embed\";\n\nexport interface OmniHostedChatOptions extends OmniApplicationOptions {\n baseUrl?: string;\n title?: string;\n onError?: (error: Error) => void;\n onRequestClose?: () => void;\n}\n\nexport class ChatSessionError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n }\n}\n\n/** One frame broker for member application chat and published storefront chat. */\nexport function mountHostedChat(\n container: HTMLElement,\n options: OmniHostedChatOptions,\n target: {\n url: string;\n scope: HostedChatScope;\n mint?: (\n previousToken: string | undefined,\n visitorId: string | undefined,\n signal: AbortSignal,\n ) => Promise<OmniChatSession>;\n },\n): OmniChatEmbed {\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const iframe = document.createElement(\"iframe\");\n iframe.src = target.url;\n iframe.title = options.title ?? \"OmniCommerce assistant\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\",\n );\n Object.assign(iframe.style, {\n width: \"100%\",\n height: \"100%\",\n minHeight: \"320px\",\n border: \"0\",\n display: \"block\",\n });\n const chatOrigin = new URL(iframe.src).origin;\n let destroyed = false;\n let pending: Promise<OmniChatSession> | undefined;\n let previousToken: string | undefined;\n const controller = new AbortController();\n\n const applicationMessage = createApplicationMessageHandler({\n options,\n signal: controller.signal,\n reply: (message) => {\n if (!destroyed)\n iframe.contentWindow?.postMessage(\n { ...message, ...target.scope },\n chatOrigin,\n );\n },\n });\n const receive = (event: MessageEvent) => {\n if (\n destroyed ||\n event.source !== iframe.contentWindow ||\n event.origin !== chatOrigin ||\n !matchesHostedChatScope(event.data, target.scope)\n )\n return;\n if (\n event.data.type === \"omni-chat:application-request\" ||\n event.data.type === \"omni-chat:tool-request\"\n ) {\n void applicationMessage(event.data);\n return;\n }\n if (event.data.type === \"omni-chat:close-request\") {\n options.onRequestClose?.();\n return;\n }\n if (event.data.type !== \"omni-chat:session-request\" || !target.mint) return;\n const visitorId =\n typeof event.data.visitorId === \"string\"\n ? event.data.visitorId\n : undefined;\n pending ??= target.mint(previousToken, visitorId, controller.signal);\n void pending\n .then((session) => {\n if (destroyed) return;\n if (\n typeof session?.token !== \"string\" ||\n !session.token ||\n session.token.length > 4096 ||\n typeof session.threadId !== \"string\" ||\n !session.threadId ||\n !Number.isFinite(session.expiresIn) ||\n session.expiresIn <= 0\n )\n throw new Error(\"Invalid chat session response.\");\n previousToken = session.token;\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session\",\n ...target.scope,\n session,\n ...(options.application ? { applicationEnabled: true } : {}),\n },\n chatOrigin,\n );\n })\n .catch((error: unknown) => {\n if (destroyed) return;\n const failure =\n error instanceof Error ? error : new Error(\"Could not open chat.\");\n if (\n failure instanceof ChatSessionError &&\n [401, 403].includes(failure.status)\n )\n previousToken = undefined;\n options.onError?.(failure);\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session-error\",\n ...target.scope,\n error: failure.message,\n ...(options.application ? { applicationEnabled: true } : {}),\n },\n chatOrigin,\n );\n })\n .finally(() => {\n pending = undefined;\n });\n };\n host.addEventListener(\"message\", receive);\n container.append(iframe);\n return {\n iframe,\n focus() {\n if (destroyed) return;\n iframe.focus();\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:focus-composer\",\n ...target.scope,\n },\n chatOrigin,\n );\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n controller.abort();\n previousToken = undefined;\n host.removeEventListener(\"message\", receive);\n iframe.remove();\n },\n };\n}\n","/** Exact hosted-chat origins, including trustworthy localhost development hosts. */\nexport function normalizeHostedChatOrigin(value: string): string {\n const url = new URL(value);\n const local =\n url.hostname === \"localhost\" ||\n url.hostname.endsWith(\".localhost\") ||\n url.hostname === \"127.0.0.1\";\n if (\n (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local)) ||\n url.username ||\n url.password ||\n url.pathname !== \"/\" ||\n url.search ||\n url.hash\n )\n throw new Error(\"Use an HTTPS origin, or HTTP localhost for development.\");\n return url.origin;\n}\n","import { normalizeHostedChatOrigin } from \"../../../lib/assistant/hosted-chat-origin\";\n\nexport function chatOrigin(baseUrl?: string): string {\n return normalizeHostedChatOrigin(baseUrl ?? \"https://omnicommerce.sg\");\n}\n","import { chatOrigin } from \"./chat-origin\";\nimport { mountHostedChat, type OmniHostedChatOptions } from \"./hosted-chat\";\n\n/** Application chat authenticates the viewer; it never uses a storefront deployment. */\nexport interface OmniApplicationChatOptions extends OmniHostedChatOptions {\n deploymentId?: never;\n /** Omit to use the member's currently selected organization. */\n organizationId?: string;\n /** Omit to use the default native assistant. */\n agentId?: string;\n /** Groups this application's conversation history; defaults to its origin. */\n appId?: string;\n}\n\nexport function getOmniApplicationChatUrl(\n options: OmniApplicationChatOptions,\n parentOrigin: string,\n chatId: string,\n) {\n if (\n !/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/i.test(chatId)\n )\n throw new Error(\"A valid application chat ID is required.\");\n const url = new URL(\"/sdk/application-chat\", chatOrigin(options.baseUrl));\n const parent = chatOrigin(parentOrigin);\n url.searchParams.set(\"parentOrigin\", parent);\n url.searchParams.set(\"chatId\", chatId);\n const appId = options.appId?.trim() ?? parent;\n if (!appId || appId.length > 200)\n throw new Error(\"appId must contain 1–200 characters.\");\n url.searchParams.set(\"appId\", appId);\n for (const key of [\"organizationId\", \"agentId\"] as const) {\n if (options[key] === undefined) continue;\n const value = options[key].trim();\n if (!value || value.length > 120)\n throw new Error(`${key} must contain 1–120 characters.`);\n url.searchParams.set(key, value);\n }\n return url.toString();\n}\n\nexport function createOmniApplicationChatEmbed(\n container: HTMLElement,\n options: OmniApplicationChatOptions,\n) {\n const host = container.ownerDocument.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const chatId = host.crypto.randomUUID();\n return mountHostedChat(container, options, {\n url: getOmniApplicationChatUrl(options, host.location.origin, chatId),\n scope: { chatId },\n });\n}\n","const iconPaths = {\n chat: \"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z\",\n close: \"m6 6 12 12M6 18 18 6\",\n collapse: \"m6 9 6 6 6-6\",\n};\n\nexport function widgetIcon(document: Document, name: keyof typeof iconPaths) {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 24 24\");\n svg.setAttribute(\"fill\", \"none\");\n svg.setAttribute(\"stroke\", \"currentColor\");\n svg.setAttribute(\"stroke-width\", \"1.8\");\n svg.setAttribute(\"stroke-linecap\", \"round\");\n svg.setAttribute(\"stroke-linejoin\", \"round\");\n svg.setAttribute(\"aria-hidden\", \"true\");\n const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n path.setAttribute(\"d\", iconPaths[name]);\n svg.append(path);\n return svg;\n}\n\nexport const widgetMobileQuery =\n \"(max-width: 640px), (max-height: 480px) and (pointer: coarse)\";\n\n/** Shadow DOM keeps a store's button, font and dialog CSS out of the widget. */\nexport const widgetStyles = `\n :host {\n all: initial; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; color-scheme: light dark;\n --omni-active-bottom-offset: var(--omni-bottom-offset);\n --omni-active-side-offset: var(--omni-side-offset);\n --omni-side-safe-area: env(safe-area-inset-right, 0px);\n --omni-opposite-safe-area: env(safe-area-inset-left, 0px);\n /* Reserve 240px of panel height, the 66px launcher gap and 20px at the opposite edges. */\n --omni-effective-bottom-offset: clamp(0px, calc(var(--omni-active-bottom-offset) + env(safe-area-inset-bottom, 0px)), max(0px, calc(100dvh - 326px - env(safe-area-inset-top, 0px))));\n --omni-effective-side-offset: clamp(0px, calc(var(--omni-active-side-offset) + var(--omni-side-safe-area)), max(0px, calc(100vw - 260px - var(--omni-opposite-safe-area))));\n bottom: var(--omni-effective-bottom-offset); right: var(--omni-effective-side-offset);\n width: max-content; max-width: calc(100vw - var(--omni-effective-side-offset) - 20px - var(--omni-opposite-safe-area));\n }\n *, *::before, *::after { box-sizing: border-box; }\n button { font: inherit; cursor: pointer; -webkit-tap-highlight-color: transparent; }\n button:focus-visible { outline: 3px solid var(--omni-launcher-bg); outline-offset: 4px; }\n svg { display: block; width: 22px; height: 22px; flex: none; }\n .launcher {\n display: flex; align-items: center; justify-content: center; gap: 10px;\n height: 52px; padding: 0 20px; border: 1px solid rgba(255,255,255,.14);\n border-radius: 999px; background: var(--omni-launcher-bg); color: var(--omni-launcher-fg);\n font-size: 14px; font-weight: 600; line-height: 1; letter-spacing: -.01em;\n box-shadow: 0 6px 24px rgba(0,0,0,.16), 0 2px 6px rgba(0,0,0,.08);\n transition: transform 160ms ease, box-shadow 160ms ease;\n margin-left: auto;\n max-width: 100%;\n }\n .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .launcher:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(0,0,0,.2); }\n .launcher[hidden] { display: none; }\n .launcher[aria-expanded=\"true\"] { width: 52px; padding: 0; }\n .launcher[aria-expanded=\"true\"] .label { display: none; }\n .panel {\n position: absolute; top: auto; bottom: 66px; right: 0; left: auto; width: min(392px, calc(100vw - var(--omni-effective-side-offset) - 20px - var(--omni-opposite-safe-area)));\n margin: 0; padding: 0; max-width: none; max-height: none; color: var(--omni-panel-fg);\n overflow: hidden; border: 0; border-radius: 20px;\n background: var(--omni-panel-bg); box-shadow: 0 24px 80px rgba(0,0,0,.18), 0 4px 16px rgba(0,0,0,.06);\n animation: omni-chat-enter 180ms ease-out;\n }\n .panel[hidden] { display: none; }\n .panel::backdrop { background: transparent; }\n .frame { height: min(780px, calc(100dvh - var(--omni-effective-bottom-offset) - 92px - env(safe-area-inset-top, 0px))); min-height: 240px; }\n .close {\n position: absolute; z-index: 1; top: 18px; right: 14px;\n display: flex; align-items: center; justify-content: center; width: 34px; height: 34px;\n border: 1px solid color-mix(in srgb, var(--omni-panel-fg) 10%, transparent); border-radius: 50%;\n background: var(--omni-panel-bg); color: var(--omni-panel-fg); transition: background 160ms ease;\n }\n .close svg { width: 17px; height: 17px; }\n .close:hover { background: color-mix(in srgb, var(--omni-panel-fg) 6%, var(--omni-panel-bg)); }\n :host([data-position=\"left\"]) {\n --omni-side-safe-area: env(safe-area-inset-left, 0px);\n --omni-opposite-safe-area: env(safe-area-inset-right, 0px);\n right: auto; left: var(--omni-effective-side-offset);\n }\n :host([data-position=\"left\"]) .panel { right: auto; left: 0; }\n :host([data-position=\"left\"]) .launcher { margin-left: 0; }\n :host([data-presentation=\"sidebar\"]) .panel {\n position: fixed; top: 0; bottom: 0; right: 0; left: auto;\n width: min(440px, 100vw); border-radius: 0;\n animation: omni-sidebar-enter 180ms ease-out;\n }\n :host([data-presentation=\"sidebar\"]) .frame { height: 100dvh; min-height: 0; }\n :host([data-presentation=\"sidebar\"][data-position=\"left\"]) .panel {\n right: auto; left: 0; animation-name: omni-sidebar-enter-left;\n }\n @keyframes omni-sidebar-enter { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-sidebar-enter-left { from { opacity: 0; transform: translateX(-100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-chat-enter { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }\n @keyframes omni-chat-mobile-enter { from { opacity: 0; } to { opacity: 1; } }\n @media ${widgetMobileQuery} {\n :host {\n --omni-active-bottom-offset: var(--omni-mobile-bottom-offset);\n --omni-active-side-offset: var(--omni-mobile-side-offset);\n /* Mobile panels fill the screen independently; only the closed pill needs to fit. */\n --omni-effective-bottom-offset: clamp(0px, calc(var(--omni-active-bottom-offset) + env(safe-area-inset-bottom, 0px)), max(0px, calc(100dvh - 72px - env(safe-area-inset-top, 0px))));\n --omni-effective-side-offset: clamp(0px, calc(var(--omni-active-side-offset) + var(--omni-side-safe-area)), max(0px, calc(100vw - 112px - var(--omni-opposite-safe-area))));\n }\n :host([data-presentation]) .panel {\n position: fixed; top: 0; right: 0; bottom: auto; left: 0;\n width: 100%; height: 100vh; height: var(--omni-viewport-height, 100dvh);\n transform: translateY(var(--omni-viewport-shift, 0px));\n transition: transform 180ms ease-out;\n border: 0; border-radius: 0; box-shadow: none; animation: omni-chat-mobile-enter 180ms ease-out;\n }\n :host([data-presentation]) .frame {\n height: 100%; min-height: 0;\n padding: env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px);\n }\n .launcher[aria-expanded=\"true\"] { display: none; }\n .close { top: calc(18px + env(safe-area-inset-top, 0px)); right: calc(14px + env(safe-area-inset-right, 0px)); }\n }\n @media (prefers-reduced-motion: reduce) { :host([data-presentation][data-position]) .panel { animation: none; transition: none; } .launcher { transition: none; } }\n`;\n","export const DEFAULT_WIDGET_OFFSET = 20;\nexport const MAX_WIDGET_OFFSET = 500;\n\nexport type OmniChatWidgetPlacement = {\n /** Desktop distance from the bottom edge, in pixels. */\n bottomOffset: number;\n /** Desktop distance from the selected side, in pixels. */\n sideOffset: number;\n /** Mobile distance from the bottom edge, in pixels. */\n mobileBottomOffset: number;\n /** Mobile distance from the selected side, in pixels. */\n mobileSideOffset: number;\n};\n\n/** Saved designs and SDK overrides use the same bounded pixel values. */\nexport function resolveWidgetPlacement(\n options: Partial<OmniChatWidgetPlacement>,\n): OmniChatWidgetPlacement {\n const offset = (value: number | undefined) => {\n if (value === undefined) return DEFAULT_WIDGET_OFFSET;\n if (!Number.isInteger(value) || value < 0 || value > MAX_WIDGET_OFFSET)\n throw new Error(\n `Chat spacing must be whole pixels between 0 and ${MAX_WIDGET_OFFSET}.`,\n );\n return value;\n };\n return {\n bottomOffset: offset(options.bottomOffset),\n sideOffset: offset(options.sideOffset),\n mobileBottomOffset: offset(options.mobileBottomOffset),\n mobileSideOffset: offset(options.mobileSideOffset),\n };\n}\n","import type { OmniChatWidgetOptions } from \"./widget\";\nimport { resolveWidgetPlacement } from \"./widget-placement\";\n\n/** Only public appearance is loaded here; agent settings remain on the server. */\nexport async function loadWidgetConfiguration(\n host: Window,\n origin: string,\n deploymentId: string,\n signal: AbortSignal,\n): Promise<OmniChatWidgetOptions> {\n const response = await host.fetch(`${origin}/api/embed/${deploymentId}`, {\n credentials: \"include\",\n cache: \"no-store\",\n signal,\n });\n const result = await response.json();\n if (!response.ok)\n throw new Error(result.error ?? \"Could not load the chat design.\");\n const design = result.design;\n const color = /^#[0-9a-f]{6}$/i;\n if (\n !design ||\n typeof design.title !== \"string\" ||\n !design.title.trim() ||\n design.title.length > 80 ||\n typeof design.launcherLabel !== \"string\" ||\n !design.launcherLabel.trim() ||\n design.launcherLabel.length > 60 ||\n ![\"left\", \"right\"].includes(design.position) ||\n ![\"floating\", \"sidebar\"].includes(design.presentation) ||\n !design.theme ||\n ![\n design.theme.primary,\n design.theme.primaryForeground,\n design.theme.background,\n design.theme.foreground,\n ].every((value) => typeof value === \"string\" && color.test(value))\n )\n throw new Error(\"Invalid chat design response.\");\n return {\n ...resolveWidgetPlacement(design),\n deploymentId,\n title: design.title,\n launcherLabel: design.launcherLabel,\n position: design.position,\n presentation: design.presentation,\n launcherBackground: design.theme.primary,\n launcherForeground: design.theme.primaryForeground,\n panelBackground: design.theme.background,\n panelForeground: design.theme.foreground,\n };\n}\n","import { widgetMobileQuery } from \"./widget-chrome\";\nconst scrollLocks = new WeakMap<Document, { count: number; release(): void }>();\n\nfunction lockScroll(document: Document) {\n let lock = scrollLocks.get(document);\n if (!lock) {\n const styles = [document.documentElement.style, document.body.style];\n const saved = styles.map((style) => ({\n value: style.getPropertyValue(\"overflow\"),\n priority: style.getPropertyPriority(\"overflow\"),\n }));\n styles.forEach((style) =>\n style.setProperty(\"overflow\", \"hidden\", \"important\"),\n );\n lock = {\n count: 0,\n release() {\n styles.forEach((style, index) => {\n const { value, priority } = saved[index]!;\n if (value) style.setProperty(\"overflow\", value, priority);\n else style.removeProperty(\"overflow\");\n });\n },\n };\n scrollLocks.set(document, lock);\n }\n lock.count++;\n return () => {\n if (--lock.count === 0) {\n lock.release();\n scrollLocks.delete(document);\n }\n };\n}\n\n/** Mobile modality and keyboard sizing belong to the host, outside the chat iframe. */\nexport function createWidgetPanel(\n root: HTMLElement,\n panel: HTMLDialogElement,\n onRequestClose: () => void,\n) {\n const host = root.ownerDocument.defaultView!;\n const mobile = host.matchMedia(widgetMobileQuery);\n const viewport = host.visualViewport;\n let modal = false;\n let releaseScroll: (() => void) | undefined;\n let viewportFrame: number | undefined;\n const cancelViewportFrame = () => {\n if (viewportFrame === undefined) return;\n host.cancelAnimationFrame(viewportFrame);\n viewportFrame = undefined;\n };\n const clearViewport = () => {\n root.style.removeProperty(\"--omni-viewport-shift\");\n root.style.removeProperty(\"--omni-viewport-height\");\n };\n const resize = () => {\n // Keep pinch zoom available; only position above the keyboard at normal scale.\n if (panel.hidden || !mobile.matches || !viewport || viewport.scale !== 1) {\n clearViewport();\n return;\n }\n // When the keyboard reduces the visual viewport, keep the iframe at the\n // layout height and move its bottom to the visible bottom edge.\n const document = root.ownerDocument;\n const viewportRoot =\n document.compatMode === \"CSS1Compat\"\n ? document.documentElement\n : document.body;\n const height = viewportRoot.clientHeight || host.innerHeight;\n // Safari can pan before reporting the keyboard's reduced height. Never\n // counteract that native upward movement with a downward translation.\n const shift = Math.min(0, viewport.offsetTop + viewport.height - height);\n root.style.setProperty(\"--omni-viewport-shift\", `${shift}px`);\n const heightValue = `${height}px`;\n if (root.style.getPropertyValue(\"--omni-viewport-height\") !== heightValue)\n root.style.setProperty(\"--omni-viewport-height\", heightValue);\n };\n const scheduleResize = () => {\n if (viewportFrame !== undefined) return;\n viewportFrame = host.requestAnimationFrame(() => {\n viewportFrame = undefined;\n resize();\n });\n };\n const show = () => {\n if (panel.hidden) return;\n let focused: HTMLElement | null = null;\n if (panel.open && modal !== mobile.matches) {\n focused = root.shadowRoot?.activeElement as HTMLElement | null;\n panel.close();\n }\n modal = mobile.matches;\n if (modal) releaseScroll ??= lockScroll(root.ownerDocument);\n else {\n releaseScroll?.();\n releaseScroll = undefined;\n }\n cancelViewportFrame();\n resize();\n if (!panel.open) {\n if (modal) panel.showModal();\n else panel.show();\n }\n if (focused && panel.contains(focused)) focused.focus();\n };\n const cancel = (event: Event) => {\n event.preventDefault();\n onRequestClose();\n };\n const close = () => {\n cancelViewportFrame();\n panel.hidden = true;\n if (panel.open) panel.close();\n releaseScroll?.();\n releaseScroll = undefined;\n clearViewport();\n };\n mobile.addEventListener(\"change\", show);\n viewport?.addEventListener(\"resize\", scheduleResize);\n viewport?.addEventListener(\"scroll\", scheduleResize);\n panel.addEventListener(\"cancel\", cancel);\n return {\n open() {\n panel.hidden = false;\n show();\n },\n close,\n destroy() {\n close();\n mobile.removeEventListener(\"change\", show);\n viewport?.removeEventListener(\"resize\", scheduleResize);\n viewport?.removeEventListener(\"scroll\", scheduleResize);\n panel.removeEventListener(\"cancel\", cancel);\n },\n };\n}\n","import {\n createOmniChatEmbed,\n getOmniChatEmbedUrl,\n type OmniChatEmbedOptions,\n type OmniChatEmbed,\n} from \"./embed\";\nimport { widgetIcon, widgetStyles } from \"./widget-chrome\";\nimport { loadWidgetConfiguration } from \"./widget-config\";\nimport { createWidgetPanel } from \"./widget-panel\";\nimport {\n resolveWidgetPlacement,\n type OmniChatWidgetPlacement,\n} from \"./widget-placement\";\n\nexport type OmniChatWidgetOptions = OmniChatEmbedOptions &\n Partial<OmniChatWidgetPlacement> & {\n /** Desktop layout; both presentations fill the viewport on mobile. */\n presentation?: \"floating\" | \"sidebar\";\n launcherLabel?: string;\n position?: \"left\" | \"right\";\n launcherBackground?: string;\n launcherForeground?: string;\n panelBackground?: string;\n panelForeground?: string;\n };\nlet widgetSequence = 0;\n/** Loads saved appearance by deployment ID. Explicit options override saved appearance. */\nexport function createOmniChatWidget(\n container: HTMLElement,\n options: OmniChatWidgetOptions,\n) {\n const origin = new URL(getOmniChatEmbedUrl(options)).origin;\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const controller = new AbortController();\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-omni-chat-widget\", \"\");\n const shadow = root.attachShadow({ mode: \"open\" });\n const style = document.createElement(\"style\");\n style.textContent = widgetStyles;\n const launcher = document.createElement(\"button\");\n const panel = document.createElement(\"dialog\");\n const close = document.createElement(\"button\");\n const frame = document.createElement(\"div\");\n let embed: OmniChatEmbed | undefined;\n let destroyed = false;\n let loaded = false;\n let openRequested = false;\n let appearance = options;\n Object.assign(root.style, {\n position: \"fixed\",\n zIndex: \"2147483000\",\n });\n launcher.type = close.type = \"button\";\n launcher.className = \"launcher\";\n const label = document.createElement(\"span\");\n label.className = \"label\";\n label.textContent = options.launcherLabel ?? \"Chat with us\";\n launcher.append(widgetIcon(document, \"chat\"), label);\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.hidden = true;\n panel.className = \"panel\";\n panel.setAttribute(\"aria-label\", options.title ?? \"Assistant chat\");\n panel.id = `omni-chat-widget-${++widgetSequence}`;\n launcher.setAttribute(\"aria-controls\", panel.id);\n frame.className = \"frame\";\n close.className = \"close\";\n close.setAttribute(\"aria-label\", \"Close chat\");\n close.title = \"Close chat\";\n close.append(widgetIcon(document, \"close\"));\n const closeChat = () => {\n if (destroyed) return;\n openRequested = false;\n panelController.close();\n launcher.hidden = false;\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent!);\n launcher.querySelector(\"svg\")?.replaceWith(widgetIcon(document, \"chat\"));\n launcher.focus();\n };\n const panelController = createWidgetPanel(root, panel, closeChat);\n const openChat = () => {\n if (destroyed) return;\n if (!loaded) {\n openRequested = true;\n return;\n }\n embed ??= createOmniChatEmbed(frame, {\n ...appearance,\n onRequestClose: closeChat,\n });\n embed.iframe.style.minHeight = \"0\";\n panelController.open();\n launcher.hidden = appearance.presentation === \"sidebar\";\n launcher.setAttribute(\"aria-expanded\", \"true\");\n launcher.setAttribute(\"aria-label\", \"Close chat\");\n launcher\n .querySelector(\"svg\")\n ?.replaceWith(widgetIcon(document, \"collapse\"));\n embed.focus();\n };\n launcher.addEventListener(\"click\", () =>\n panel.hidden ? openChat() : closeChat(),\n );\n close.addEventListener(\"click\", closeChat);\n shadow.addEventListener(\"keydown\", (event) => {\n if ((event as KeyboardEvent).key === \"Escape\" && !panel.hidden) closeChat();\n });\n panel.append(close, frame);\n shadow.append(style, panel, launcher);\n const ready = loadWidgetConfiguration(\n host,\n origin,\n options.deploymentId,\n controller.signal,\n ).then((configuration) => {\n if (destroyed) return;\n appearance = Object.assign(\n configuration,\n Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined),\n ),\n );\n root.dataset.position = appearance.position ?? \"right\";\n root.dataset.presentation = appearance.presentation ?? \"floating\";\n const placement = resolveWidgetPlacement(appearance);\n root.style.setProperty(\n \"--omni-bottom-offset\",\n `${placement.bottomOffset}px`,\n );\n root.style.setProperty(\"--omni-side-offset\", `${placement.sideOffset}px`);\n root.style.setProperty(\n \"--omni-mobile-bottom-offset\",\n `${placement.mobileBottomOffset}px`,\n );\n root.style.setProperty(\n \"--omni-mobile-side-offset\",\n `${placement.mobileSideOffset}px`,\n );\n root.style.setProperty(\n \"--omni-launcher-bg\",\n appearance.launcherBackground!,\n );\n root.style.setProperty(\n \"--omni-launcher-fg\",\n appearance.launcherForeground!,\n );\n root.style.setProperty(\"--omni-panel-bg\", appearance.panelBackground!);\n root.style.setProperty(\"--omni-panel-fg\", appearance.panelForeground!);\n label.textContent = appearance.launcherLabel!;\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.setAttribute(\"aria-label\", appearance.title!);\n loaded = true;\n container.append(root);\n if (openRequested) openChat();\n });\n void ready.catch((error: unknown) => {\n if (!destroyed)\n options.onError?.(\n error instanceof Error ? error : new Error(\"Could not load chat.\"),\n );\n });\n return {\n /** Resolves once saved appearance is loaded and the launcher is mounted. */\n ready,\n open: openChat,\n close: closeChat,\n destroy() {\n destroyed = true;\n controller.abort();\n panelController.destroy();\n embed?.destroy();\n root.remove();\n },\n };\n}\n","import { getOmniChatEmbedUrl, type OmniChatEmbedOptions } from \"./embed\";\nimport type { OmniChatWidgetOptions } from \"./widget\";\n\ntype EmbedCodeOptions = Pick<\n OmniChatEmbedOptions,\n \"baseUrl\" | \"deploymentId\" | \"title\"\n> &\n Pick<\n OmniChatWidgetOptions,\n | \"presentation\"\n | \"launcherLabel\"\n | \"position\"\n | \"bottomOffset\"\n | \"sideOffset\"\n | \"mobileBottomOffset\"\n | \"mobileSideOffset\"\n | \"launcherBackground\"\n | \"launcherForeground\"\n | \"panelBackground\"\n | \"panelForeground\"\n >;\nconst scriptJson = (value: unknown) =>\n JSON.stringify(value, null, 2).replace(\n /[<>&\\u2028\\u2029]/g,\n (character) =>\n `\\\\u${character.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n\n/** Copyable integrations contain only public deployment configuration. */\nexport function getOmniChatEmbedCode(\n options: EmbedCodeOptions,\n mode: \"widget\" | \"inline\" = \"widget\",\n) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n const config = { ...options, baseUrl };\n const id = `omni-chat-${options.deploymentId}`;\n const mount =\n mode === \"widget\"\n ? `OmniCommerceChat.createOmniChatWidget(document.body, ${scriptJson(config)});`\n : `OmniCommerceChat.createOmniChatEmbed(document.getElementById(${scriptJson(id)}), ${scriptJson(config)});`;\n return `${mode === \"inline\" ? `<div id=\"${id}\" style=\"height:600px\"></div>\\n` : \"\"}<script src=\"${baseUrl}/sdk/embed.global.js\"></script>\\n<script>\\n ${mount.replace(/\\n/g, \"\\n \")}\\n</script>`;\n}\nexport function getOmniChatReactCode(options: EmbedCodeOptions) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n return `import { OmniProvider, OmniChat } from \"@omni-commerce/sdk/react\";\\n\\n<OmniProvider deploymentId={${scriptJson(options.deploymentId)}}\\n baseUrl={${scriptJson(baseUrl)}}${options.title ? `\\n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D,IAAME,EAAOC,EAAWH,EAAQ,OAAO,EACjCI,EAAM,IAAI,IAAI,UAAUJ,EAAQ,YAAY,GAAIE,CAAI,EAC1D,OAAID,GACFG,EAAI,aAAa,IAAI,eAAgB,IAAI,IAAIH,CAAY,EAAE,MAAM,EAC5DG,EAAI,SAAS,CACtB,CAGO,SAASC,EACdC,EACAN,EACe,CACf,IAAMO,EAAOD,EAAU,cAAc,YACrC,GAAI,CAACC,EAAM,MAAM,IAAI,MAAM,+CAA+C,EAC1E,IAAMH,EAAML,EAAoBC,EAASO,EAAK,SAAS,MAAM,EACvDJ,EAAa,IAAI,IAAIC,CAAG,EAAE,OAChC,OAAOI,EAAgBF,EAAWN,EAAS,CACzC,IAAAI,EACA,MAAO,CAAE,aAAcJ,EAAQ,YAAa,EAC5C,KAAM,MAAOS,EAAeC,EAAWC,IAAW,CAChD,GAAIX,EAAQ,WAAY,OAAOA,EAAQ,WAAW,EAClD,IAAMY,EAAW,MAAML,EAAK,MAC1B,GAAGJ,CAAU,cAAcH,EAAQ,YAAY,WAC/C,CACE,OAAQ,OACR,YAAa,UACb,OAAAW,EACA,QAAS,CACP,eAAgB,mBAChB,GAAIF,EACA,CAAE,cAAe,UAAUA,CAAa,EAAG,EAC3C,CAAC,CACP,EACA,KAAM,KAAK,UACTC,GACE,6EAA6E,KAC3EA,CACF,EACE,CAAE,UAAAA,CAAU,EACZ,CAAC,CACP,CACF,CACF,EACMG,EAAU,MAAMD,EAAS,KAAK,EAGpC,GAAI,CAACA,EAAS,GACZ,MAAM,IAAIE,EACRD,EAAO,OAAS,mCAChBD,EAAS,MACX,EACF,OAAOC,CACT,CACF,CAAC,CACH","names":["embed_exports","__export","DEFAULT_WIDGET_OFFSET","MAX_WIDGET_OFFSET","createOmniApplicationChatEmbed","createOmniChatEmbed","createOmniChatWidget","getOmniApplicationChatUrl","getOmniChatEmbedCode","getOmniChatEmbedUrl","getOmniChatReactCode","boundedJson","value","maximum","encoded","createApplicationMessageHandler","input","calls","message","application","name","definition","toolCallId","args","signature","prior","result","error","matchesHostedChatScope","message","scope","ChatSessionError","message","status","__publicField","mountHostedChat","container","options","target","document","host","iframe","chatOrigin","destroyed","pending","previousToken","controller","applicationMessage","createApplicationMessageHandler","receive","event","matchesHostedChatScope","visitorId","session","error","failure","normalizeHostedChatOrigin","value","url","local","chatOrigin","baseUrl","normalizeHostedChatOrigin","getOmniApplicationChatUrl","options","parentOrigin","chatId","url","chatOrigin","parent","appId","key","value","createOmniApplicationChatEmbed","container","host","mountHostedChat","iconPaths","widgetIcon","document","name","svg","path","widgetMobileQuery","widgetStyles","DEFAULT_WIDGET_OFFSET","MAX_WIDGET_OFFSET","resolveWidgetPlacement","options","offset","value","loadWidgetConfiguration","host","origin","deploymentId","signal","response","result","design","color","value","resolveWidgetPlacement","scrollLocks","lockScroll","document","lock","styles","saved","style","index","value","priority","createWidgetPanel","root","panel","onRequestClose","host","mobile","widgetMobileQuery","viewport","modal","releaseScroll","viewportFrame","cancelViewportFrame","clearViewport","resize","height","shift","heightValue","scheduleResize","show","focused","cancel","event","close","widgetSequence","createOmniChatWidget","container","options","origin","getOmniChatEmbedUrl","document","host","controller","root","shadow","style","widgetStyles","launcher","panel","close","frame","embed","destroyed","loaded","openRequested","appearance","label","widgetIcon","closeChat","panelController","createWidgetPanel","openChat","createOmniChatEmbed","event","ready","loadWidgetConfiguration","configuration","value","placement","resolveWidgetPlacement","error","scriptJson","value","character","getOmniChatEmbedCode","options","mode","baseUrl","getOmniChatEmbedUrl","config","id","mount","getOmniChatReactCode","getOmniChatEmbedUrl","options","parentOrigin","base","chatOrigin","url","createOmniChatEmbed","container","host","mountHostedChat","previousToken","visitorId","signal","response","result","ChatSessionError"]}
1
+ {"version":3,"sources":["../src/embed.ts","../src/application.ts","../../../lib/assistant/application-chat/bridge-scope.ts","../src/hosted-chat.ts","../../../lib/assistant/hosted-chat-origin.ts","../src/chat-origin.ts","../src/application-embed.ts","../src/widget-chrome.ts","../src/widget-placement.ts","../src/widget-config.ts","../src/widget-panel.ts","../src/widget.ts","../src/embed-code.ts"],"sourcesContent":["import { mountHostedChat, ChatSessionError } from \"./hosted-chat\";\nimport { chatOrigin } from \"./chat-origin\";\nimport { type OmniApplicationOptions } from \"./application\";\nexport type {\n OmniFrontendTool,\n OmniChatApplication,\n OmniApplicationOptions,\n} from \"./application\";\n/** A hosted chat session. Keep its short-lived token in memory, never in iframe URLs. */\nexport {\n createOmniApplicationChatEmbed,\n getOmniApplicationChatUrl,\n type OmniApplicationChatOptions,\n} from \"./application-embed\";\nexport { createOmniChatWidget, type OmniChatWidgetOptions } from \"./widget\";\nexport {\n DEFAULT_WIDGET_OFFSET,\n MAX_WIDGET_OFFSET,\n type OmniChatWidgetPlacement,\n} from \"./widget-placement\";\nexport { getOmniChatEmbedCode, getOmniChatReactCode } from \"./embed-code\";\nexport interface OmniChatSession {\n token: string;\n threadId: string;\n expiresIn: number;\n}\nexport interface OmniChatEmbedOptions extends OmniApplicationOptions {\n deploymentId: string;\n baseUrl?: string;\n /** Optional authenticated session mint on the host application's server. */\n getSession?: () => Promise<OmniChatSession>;\n title?: string;\n onError?: (error: Error) => void;\n /** Floating widgets use this to close on Escape from the hosted chat. */\n onRequestClose?: () => void;\n}\nexport interface OmniChatEmbed {\n iframe: HTMLIFrameElement;\n /** Focus the hosted composer, including when reopening a retained chat. */\n focus(): void;\n destroy(): void;\n}\n\nexport function getOmniChatEmbedUrl(\n options: Pick<OmniChatEmbedOptions, \"baseUrl\" | \"deploymentId\">,\n parentOrigin?: string,\n): string {\n if (\n !/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/i.test(\n options.deploymentId,\n )\n )\n throw new Error(\"A valid chat deployment ID is required.\");\n const base = chatOrigin(options.baseUrl);\n const url = new URL(`/embed/${options.deploymentId}`, base);\n if (parentOrigin)\n url.searchParams.set(\"parentOrigin\", new URL(parentOrigin).origin);\n return url.toString();\n}\n\n/** Browser-only mounting; importing this entry point is safe during SSR. */\nexport function createOmniChatEmbed(\n container: HTMLElement,\n options: OmniChatEmbedOptions,\n): OmniChatEmbed {\n const host = container.ownerDocument.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const url = getOmniChatEmbedUrl(options, host.location.origin);\n const chatOrigin = new URL(url).origin;\n return mountHostedChat(container, options, {\n url,\n scope: { deploymentId: options.deploymentId },\n mint: async (previousToken, visitorId, signal) => {\n if (options.getSession) return options.getSession();\n const response = await host.fetch(\n `${chatOrigin}/api/embed/${options.deploymentId}/session`,\n {\n method: \"POST\",\n credentials: \"include\",\n signal,\n headers: {\n \"Content-Type\": \"application/json\",\n ...(previousToken\n ? { Authorization: `Bearer ${previousToken}` }\n : {}),\n },\n body: JSON.stringify(\n visitorId &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n visitorId,\n )\n ? { visitorId }\n : {},\n ),\n },\n );\n const result = (await response.json()) as OmniChatSession & {\n error?: string;\n };\n if (!response.ok)\n throw new ChatSessionError(\n result.error ?? \"Could not open the chat session.\",\n response.status,\n );\n return result;\n },\n });\n}\n","/** Host-defined actions execute inside the application, never on the assistant server. */\nexport interface OmniFrontendTool {\n description: string;\n parameters: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n context: { toolCallId: string; abortSignal: AbortSignal },\n ) => unknown | Promise<unknown>;\n}\nexport interface OmniChatApplication {\n name: string;\n description: string;\n /** Return a small, explicitly selected snapshot. Do not include secrets. */\n getContext: () => unknown | Promise<unknown>;\n}\nexport interface OmniApplicationOptions {\n application?: OmniChatApplication;\n /** Names must start with app_; use array arguments for actions with multiple targets. */\n frontendTools?: Record<string, OmniFrontendTool>;\n}\n\nfunction boundedJson(value: unknown, maximum: number): unknown {\n const encoded = JSON.stringify(value);\n if (\n typeof encoded !== \"string\" ||\n new TextEncoder().encode(encoded).length > maximum ||\n /data:[^\"\\s]{0,100};base64,/i.test(encoded)\n )\n throw new Error(\n \"Application data must be bounded JSON without base64 payloads.\",\n );\n return JSON.parse(encoded);\n}\n\nexport function createApplicationMessageHandler(input: {\n options: OmniApplicationOptions;\n assistant?: () => { systemPrompt?: string; tools?: readonly string[] };\n signal: AbortSignal;\n reply: (message: Record<string, unknown>) => void;\n}) {\n // A repeated parked call reuses its result instead of applying an action twice.\n const calls = new Map<\n string,\n { signature: string; result: Promise<unknown> }\n >();\n return async (message: Record<string, unknown>) => {\n if (typeof message.requestId !== \"string\" || message.requestId.length > 200)\n return;\n try {\n if (message.type === \"omni-chat:application-request\") {\n const application = input.options.application;\n input.reply({\n type: \"omni-chat:application-response\",\n requestId: message.requestId,\n ...(input.assistant\n ? { assistant: boundedJson(input.assistant(), 65536) }\n : {}),\n application: application\n ? boundedJson(\n {\n name: application.name,\n description: application.description,\n context: (await application.getContext()) ?? null,\n tools: Object.entries(input.options.frontendTools ?? {}).map(\n ([name, definition]) => ({\n name,\n description: definition.description,\n parameters: definition.parameters,\n }),\n ),\n },\n 65536,\n )\n : undefined,\n });\n } else if (message.type === \"omni-chat:tool-request\") {\n const name = message.toolName;\n const toolCallId = message.toolCallId;\n if (\n typeof name !== \"string\" ||\n !/^app_[a-z][a-z0-9_]{0,59}$/.test(name) ||\n typeof toolCallId !== \"string\" ||\n !toolCallId ||\n toolCallId.length > 200\n )\n throw new Error(\"Invalid application tool request.\");\n const definition = Object.hasOwn(\n input.options.frontendTools ?? {},\n name,\n )\n ? input.options.frontendTools?.[name]\n : undefined;\n if (!input.options.application || !definition)\n throw new Error(\"This application action is unavailable.\");\n const args = message.args;\n if (!args || typeof args !== \"object\" || Array.isArray(args))\n throw new Error(\"Invalid application action arguments.\");\n const signature = JSON.stringify({ name, args });\n const prior = calls.get(toolCallId);\n if (prior && prior.signature !== signature)\n throw new Error(\"This tool call ID was already used.\");\n const result =\n prior?.result ??\n Promise.resolve().then(() =>\n definition.execute(args as Record<string, unknown>, {\n toolCallId,\n abortSignal: input.signal,\n }),\n );\n if (!prior) {\n if (calls.size >= 200)\n throw new Error(\"Start a new application chat.\");\n calls.set(toolCallId, { signature, result });\n }\n input.reply({\n type: \"omni-chat:tool-response\",\n requestId: message.requestId,\n toolCallId,\n result: boundedJson((await result) ?? null, 12000),\n });\n }\n } catch (error) {\n input.reply({\n type:\n message.type === \"omni-chat:application-request\"\n ? \"omni-chat:application-response\"\n : \"omni-chat:tool-response\",\n requestId: message.requestId,\n toolCallId: message.toolCallId,\n error:\n error instanceof Error\n ? error.message\n : \"The application action failed.\",\n });\n }\n };\n}\n","/** Scope each hosted frame independently; application chats have no deployment. */\nexport type HostedChatScope =\n | { deploymentId: string; chatId?: never }\n | { chatId: string; deploymentId?: never };\n\nexport function hostedChatId(scope: HostedChatScope) {\n return scope.deploymentId ?? scope.chatId;\n}\n\nexport function matchesHostedChatScope(\n message: Record<string, unknown> | null | undefined,\n scope: HostedChatScope,\n) {\n return scope.deploymentId !== undefined\n ? message?.deploymentId === scope.deploymentId &&\n message.chatId === undefined\n : message?.chatId === scope.chatId && message.deploymentId === undefined;\n}\n","import {\n createApplicationMessageHandler,\n type OmniApplicationOptions,\n} from \"./application\";\nimport {\n matchesHostedChatScope,\n type HostedChatScope,\n} from \"../../../lib/assistant/application-chat/bridge-scope\";\nimport type { OmniChatEmbed, OmniChatSession } from \"./embed\";\n\nexport interface OmniHostedChatOptions extends OmniApplicationOptions {\n baseUrl?: string;\n title?: string;\n onError?: (error: Error) => void;\n onRequestClose?: () => void;\n}\n\nexport class ChatSessionError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n }\n}\n\n/** One frame broker for member application chat and published storefront chat. */\nexport function mountHostedChat(\n container: HTMLElement,\n options: OmniHostedChatOptions,\n target: {\n url: string;\n scope: HostedChatScope;\n assistant?: () => { systemPrompt?: string; tools?: readonly string[] };\n mint?: (\n previousToken: string | undefined,\n visitorId: string | undefined,\n signal: AbortSignal,\n ) => Promise<OmniChatSession>;\n },\n): OmniChatEmbed {\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const iframe = document.createElement(\"iframe\");\n iframe.src = target.url;\n iframe.title = options.title ?? \"OmniCommerce assistant\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\",\n );\n Object.assign(iframe.style, {\n width: \"100%\",\n height: \"100%\",\n minHeight: \"320px\",\n border: \"0\",\n display: \"block\",\n });\n const chatOrigin = new URL(iframe.src).origin;\n let destroyed = false;\n let pending: Promise<OmniChatSession> | undefined;\n let previousToken: string | undefined;\n const controller = new AbortController();\n\n const applicationMessage = createApplicationMessageHandler({\n options,\n assistant: target.assistant,\n signal: controller.signal,\n reply: (message) => {\n if (!destroyed)\n iframe.contentWindow?.postMessage(\n { ...message, ...target.scope },\n chatOrigin,\n );\n },\n });\n const receive = (event: MessageEvent) => {\n if (\n destroyed ||\n event.source !== iframe.contentWindow ||\n event.origin !== chatOrigin ||\n !matchesHostedChatScope(event.data, target.scope)\n )\n return;\n if (\n event.data.type === \"omni-chat:application-request\" ||\n event.data.type === \"omni-chat:tool-request\"\n ) {\n void applicationMessage(event.data);\n return;\n }\n if (event.data.type === \"omni-chat:close-request\") {\n options.onRequestClose?.();\n return;\n }\n if (event.data.type !== \"omni-chat:session-request\" || !target.mint) return;\n const visitorId =\n typeof event.data.visitorId === \"string\"\n ? event.data.visitorId\n : undefined;\n pending ??= target.mint(previousToken, visitorId, controller.signal);\n void pending\n .then((session) => {\n if (destroyed) return;\n if (\n typeof session?.token !== \"string\" ||\n !session.token ||\n session.token.length > 4096 ||\n typeof session.threadId !== \"string\" ||\n !session.threadId ||\n !Number.isFinite(session.expiresIn) ||\n session.expiresIn <= 0\n )\n throw new Error(\"Invalid chat session response.\");\n previousToken = session.token;\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session\",\n ...target.scope,\n session,\n ...(options.application ? { applicationEnabled: true } : {}),\n },\n chatOrigin,\n );\n })\n .catch((error: unknown) => {\n if (destroyed) return;\n const failure =\n error instanceof Error ? error : new Error(\"Could not open chat.\");\n if (\n failure instanceof ChatSessionError &&\n [401, 403].includes(failure.status)\n )\n previousToken = undefined;\n options.onError?.(failure);\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:session-error\",\n ...target.scope,\n error: failure.message,\n ...(options.application ? { applicationEnabled: true } : {}),\n },\n chatOrigin,\n );\n })\n .finally(() => {\n pending = undefined;\n });\n };\n host.addEventListener(\"message\", receive);\n container.append(iframe);\n return {\n iframe,\n focus() {\n if (destroyed) return;\n iframe.focus();\n iframe.contentWindow?.postMessage(\n {\n type: \"omni-chat:focus-composer\",\n ...target.scope,\n },\n chatOrigin,\n );\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n controller.abort();\n previousToken = undefined;\n host.removeEventListener(\"message\", receive);\n iframe.remove();\n },\n };\n}\n","/** Exact hosted-chat origins, including trustworthy localhost development hosts. */\nexport function normalizeHostedChatOrigin(value: string): string {\n const url = new URL(value);\n const local =\n url.hostname === \"localhost\" ||\n url.hostname.endsWith(\".localhost\") ||\n url.hostname === \"127.0.0.1\";\n if (\n (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local)) ||\n url.username ||\n url.password ||\n url.pathname !== \"/\" ||\n url.search ||\n url.hash\n )\n throw new Error(\"Use an HTTPS origin, or HTTP localhost for development.\");\n return url.origin;\n}\n","import { normalizeHostedChatOrigin } from \"../../../lib/assistant/hosted-chat-origin\";\n\nexport function chatOrigin(baseUrl?: string): string {\n return normalizeHostedChatOrigin(baseUrl ?? \"https://omnicommerce.sg\");\n}\n","import { chatOrigin } from \"./chat-origin\";\nimport { mountHostedChat, type OmniHostedChatOptions } from \"./hosted-chat\";\n\n/** Application chat authenticates the viewer; it never uses a storefront deployment. */\nexport interface OmniApplicationChatOptions extends OmniHostedChatOptions {\n deploymentId?: never;\n /** Omit to use the member's currently selected organization. */\n organizationId?: string;\n /** Omit to use the default native assistant. */\n agentId?: string;\n /** Groups this application's conversation history; defaults to its origin. */\n appId?: string;\n /** Application role instructions. Omit or clear to use the selected agent's prompt. */\n systemPrompt?: string;\n /** Backend tool/toolkit allowlist within the selected agent's permissions.\n * Omit to inherit; [] allows only registered frontendTools. */\n tools?: readonly string[];\n}\n\nexport function getOmniApplicationChatUrl(\n options: OmniApplicationChatOptions,\n parentOrigin: string,\n chatId: string,\n) {\n if (\n !/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/i.test(chatId)\n )\n throw new Error(\"A valid application chat ID is required.\");\n const url = new URL(\"/sdk/application-chat\", chatOrigin(options.baseUrl));\n const parent = chatOrigin(parentOrigin);\n url.searchParams.set(\"parentOrigin\", parent);\n url.searchParams.set(\"chatId\", chatId);\n const appId = options.appId?.trim() ?? parent;\n if (!appId || appId.length > 200)\n throw new Error(\"appId must contain 1–200 characters.\");\n url.searchParams.set(\"appId\", appId);\n for (const key of [\"organizationId\", \"agentId\"] as const) {\n if (options[key] === undefined) continue;\n const value = options[key].trim();\n if (!value || value.length > 120)\n throw new Error(`${key} must contain 1–120 characters.`);\n url.searchParams.set(key, value);\n }\n return url.toString();\n}\n\nexport function createOmniApplicationChatEmbed(\n container: HTMLElement,\n options: OmniApplicationChatOptions,\n) {\n const host = container.ownerDocument.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const chatId = host.crypto.randomUUID();\n return mountHostedChat(container, options, {\n url: getOmniApplicationChatUrl(options, host.location.origin, chatId),\n scope: { chatId },\n assistant: () => ({\n ...(options.systemPrompt !== undefined\n ? { systemPrompt: options.systemPrompt }\n : {}),\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n }),\n });\n}\n","const iconPaths = {\n chat: \"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z\",\n close: \"m6 6 12 12M6 18 18 6\",\n collapse: \"m6 9 6 6 6-6\",\n};\n\nexport function widgetIcon(document: Document, name: keyof typeof iconPaths) {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 24 24\");\n svg.setAttribute(\"fill\", \"none\");\n svg.setAttribute(\"stroke\", \"currentColor\");\n svg.setAttribute(\"stroke-width\", \"1.8\");\n svg.setAttribute(\"stroke-linecap\", \"round\");\n svg.setAttribute(\"stroke-linejoin\", \"round\");\n svg.setAttribute(\"aria-hidden\", \"true\");\n const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n path.setAttribute(\"d\", iconPaths[name]);\n svg.append(path);\n return svg;\n}\n\nexport const widgetMobileQuery =\n \"(max-width: 640px), (max-height: 480px) and (pointer: coarse)\";\n\n/** Shadow DOM keeps a store's button, font and dialog CSS out of the widget. */\nexport const widgetStyles = `\n :host {\n all: initial; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; color-scheme: light dark;\n --omni-active-bottom-offset: var(--omni-bottom-offset);\n --omni-active-side-offset: var(--omni-side-offset);\n --omni-side-safe-area: env(safe-area-inset-right, 0px);\n --omni-opposite-safe-area: env(safe-area-inset-left, 0px);\n /* Reserve 240px of panel height, the 66px launcher gap and 20px at the opposite edges. */\n --omni-effective-bottom-offset: clamp(0px, calc(var(--omni-active-bottom-offset) + env(safe-area-inset-bottom, 0px)), max(0px, calc(100dvh - 326px - env(safe-area-inset-top, 0px))));\n --omni-effective-side-offset: clamp(0px, calc(var(--omni-active-side-offset) + var(--omni-side-safe-area)), max(0px, calc(100vw - 260px - var(--omni-opposite-safe-area))));\n bottom: var(--omni-effective-bottom-offset); right: var(--omni-effective-side-offset);\n width: max-content; max-width: calc(100vw - var(--omni-effective-side-offset) - 20px - var(--omni-opposite-safe-area));\n }\n *, *::before, *::after { box-sizing: border-box; }\n button { font: inherit; cursor: pointer; -webkit-tap-highlight-color: transparent; }\n button:focus-visible { outline: 3px solid var(--omni-launcher-bg); outline-offset: 4px; }\n svg { display: block; width: 22px; height: 22px; flex: none; }\n .launcher {\n display: flex; align-items: center; justify-content: center; gap: 10px;\n height: 52px; padding: 0 20px; border: 1px solid rgba(255,255,255,.14);\n border-radius: 999px; background: var(--omni-launcher-bg); color: var(--omni-launcher-fg);\n font-size: 14px; font-weight: 600; line-height: 1; letter-spacing: -.01em;\n box-shadow: 0 6px 24px rgba(0,0,0,.16), 0 2px 6px rgba(0,0,0,.08);\n transition: transform 160ms ease, box-shadow 160ms ease;\n margin-left: auto;\n max-width: 100%;\n }\n .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .launcher:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(0,0,0,.2); }\n .launcher[hidden] { display: none; }\n .launcher[aria-expanded=\"true\"] { width: 52px; padding: 0; }\n .launcher[aria-expanded=\"true\"] .label { display: none; }\n .panel {\n position: absolute; top: auto; bottom: 66px; right: 0; left: auto; width: min(392px, calc(100vw - var(--omni-effective-side-offset) - 20px - var(--omni-opposite-safe-area)));\n margin: 0; padding: 0; max-width: none; max-height: none; color: var(--omni-panel-fg);\n overflow: hidden; border: 0; border-radius: 20px;\n background: var(--omni-panel-bg); box-shadow: 0 24px 80px rgba(0,0,0,.18), 0 4px 16px rgba(0,0,0,.06);\n animation: omni-chat-enter 180ms ease-out;\n }\n .panel[hidden] { display: none; }\n .panel::backdrop { background: transparent; }\n .frame { height: min(780px, calc(100dvh - var(--omni-effective-bottom-offset) - 92px - env(safe-area-inset-top, 0px))); min-height: 240px; }\n .close {\n position: absolute; z-index: 1; top: 18px; right: 14px;\n display: flex; align-items: center; justify-content: center; width: 34px; height: 34px;\n border: 1px solid color-mix(in srgb, var(--omni-panel-fg) 10%, transparent); border-radius: 50%;\n background: var(--omni-panel-bg); color: var(--omni-panel-fg); transition: background 160ms ease;\n }\n .close svg { width: 17px; height: 17px; }\n .close:hover { background: color-mix(in srgb, var(--omni-panel-fg) 6%, var(--omni-panel-bg)); }\n :host([data-position=\"left\"]) {\n --omni-side-safe-area: env(safe-area-inset-left, 0px);\n --omni-opposite-safe-area: env(safe-area-inset-right, 0px);\n right: auto; left: var(--omni-effective-side-offset);\n }\n :host([data-position=\"left\"]) .panel { right: auto; left: 0; }\n :host([data-position=\"left\"]) .launcher { margin-left: 0; }\n :host([data-presentation=\"sidebar\"]) .panel {\n position: fixed; top: 0; bottom: 0; right: 0; left: auto;\n width: min(440px, 100vw); border-radius: 0;\n animation: omni-sidebar-enter 180ms ease-out;\n }\n :host([data-presentation=\"sidebar\"]) .frame { height: 100dvh; min-height: 0; }\n :host([data-presentation=\"sidebar\"][data-position=\"left\"]) .panel {\n right: auto; left: 0; animation-name: omni-sidebar-enter-left;\n }\n @keyframes omni-sidebar-enter { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-sidebar-enter-left { from { opacity: 0; transform: translateX(-100%); } to { opacity: 1; transform: none; } }\n @keyframes omni-chat-enter { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }\n @keyframes omni-chat-mobile-enter { from { opacity: 0; } to { opacity: 1; } }\n @media ${widgetMobileQuery} {\n :host {\n --omni-active-bottom-offset: var(--omni-mobile-bottom-offset);\n --omni-active-side-offset: var(--omni-mobile-side-offset);\n /* Mobile panels fill the screen independently; only the closed pill needs to fit. */\n --omni-effective-bottom-offset: clamp(0px, calc(var(--omni-active-bottom-offset) + env(safe-area-inset-bottom, 0px)), max(0px, calc(100dvh - 72px - env(safe-area-inset-top, 0px))));\n --omni-effective-side-offset: clamp(0px, calc(var(--omni-active-side-offset) + var(--omni-side-safe-area)), max(0px, calc(100vw - 112px - var(--omni-opposite-safe-area))));\n }\n :host([data-presentation]) .panel {\n position: fixed; top: 0; right: 0; bottom: auto; left: 0;\n width: 100%; height: 100vh; height: var(--omni-viewport-height, 100dvh);\n transform: translateY(var(--omni-viewport-shift, 0px));\n transition: transform 180ms ease-out;\n border: 0; border-radius: 0; box-shadow: none; animation: omni-chat-mobile-enter 180ms ease-out;\n }\n :host([data-presentation]) .frame {\n height: 100%; min-height: 0;\n padding: env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px);\n }\n .launcher[aria-expanded=\"true\"] { display: none; }\n .close { top: calc(18px + env(safe-area-inset-top, 0px)); right: calc(14px + env(safe-area-inset-right, 0px)); }\n }\n @media (prefers-reduced-motion: reduce) { :host([data-presentation][data-position]) .panel { animation: none; transition: none; } .launcher { transition: none; } }\n`;\n","export const DEFAULT_WIDGET_OFFSET = 20;\nexport const MAX_WIDGET_OFFSET = 500;\n\nexport type OmniChatWidgetPlacement = {\n /** Desktop distance from the bottom edge, in pixels. */\n bottomOffset: number;\n /** Desktop distance from the selected side, in pixels. */\n sideOffset: number;\n /** Mobile distance from the bottom edge, in pixels. */\n mobileBottomOffset: number;\n /** Mobile distance from the selected side, in pixels. */\n mobileSideOffset: number;\n};\n\n/** Saved designs and SDK overrides use the same bounded pixel values. */\nexport function resolveWidgetPlacement(\n options: Partial<OmniChatWidgetPlacement>,\n): OmniChatWidgetPlacement {\n const offset = (value: number | undefined) => {\n if (value === undefined) return DEFAULT_WIDGET_OFFSET;\n if (!Number.isInteger(value) || value < 0 || value > MAX_WIDGET_OFFSET)\n throw new Error(\n `Chat spacing must be whole pixels between 0 and ${MAX_WIDGET_OFFSET}.`,\n );\n return value;\n };\n return {\n bottomOffset: offset(options.bottomOffset),\n sideOffset: offset(options.sideOffset),\n mobileBottomOffset: offset(options.mobileBottomOffset),\n mobileSideOffset: offset(options.mobileSideOffset),\n };\n}\n","import type { OmniChatWidgetOptions } from \"./widget\";\nimport { resolveWidgetPlacement } from \"./widget-placement\";\n\n/** Only public appearance is loaded here; agent settings remain on the server. */\nexport async function loadWidgetConfiguration(\n host: Window,\n origin: string,\n deploymentId: string,\n signal: AbortSignal,\n): Promise<OmniChatWidgetOptions> {\n const response = await host.fetch(`${origin}/api/embed/${deploymentId}`, {\n credentials: \"include\",\n cache: \"no-store\",\n signal,\n });\n const result = await response.json();\n if (!response.ok)\n throw new Error(result.error ?? \"Could not load the chat design.\");\n const design = result.design;\n const color = /^#[0-9a-f]{6}$/i;\n if (\n !design ||\n typeof design.title !== \"string\" ||\n !design.title.trim() ||\n design.title.length > 80 ||\n typeof design.launcherLabel !== \"string\" ||\n !design.launcherLabel.trim() ||\n design.launcherLabel.length > 60 ||\n ![\"left\", \"right\"].includes(design.position) ||\n ![\"floating\", \"sidebar\"].includes(design.presentation) ||\n !design.theme ||\n ![\n design.theme.primary,\n design.theme.primaryForeground,\n design.theme.background,\n design.theme.foreground,\n ].every((value) => typeof value === \"string\" && color.test(value))\n )\n throw new Error(\"Invalid chat design response.\");\n return {\n ...resolveWidgetPlacement(design),\n deploymentId,\n title: design.title,\n launcherLabel: design.launcherLabel,\n position: design.position,\n presentation: design.presentation,\n launcherBackground: design.theme.primary,\n launcherForeground: design.theme.primaryForeground,\n panelBackground: design.theme.background,\n panelForeground: design.theme.foreground,\n };\n}\n","import { widgetMobileQuery } from \"./widget-chrome\";\nconst scrollLocks = new WeakMap<Document, { count: number; release(): void }>();\n\nfunction lockScroll(document: Document) {\n let lock = scrollLocks.get(document);\n if (!lock) {\n const styles = [document.documentElement.style, document.body.style];\n const saved = styles.map((style) => ({\n value: style.getPropertyValue(\"overflow\"),\n priority: style.getPropertyPriority(\"overflow\"),\n }));\n styles.forEach((style) =>\n style.setProperty(\"overflow\", \"hidden\", \"important\"),\n );\n lock = {\n count: 0,\n release() {\n styles.forEach((style, index) => {\n const { value, priority } = saved[index]!;\n if (value) style.setProperty(\"overflow\", value, priority);\n else style.removeProperty(\"overflow\");\n });\n },\n };\n scrollLocks.set(document, lock);\n }\n lock.count++;\n return () => {\n if (--lock.count === 0) {\n lock.release();\n scrollLocks.delete(document);\n }\n };\n}\n\n/** Mobile modality and keyboard sizing belong to the host, outside the chat iframe. */\nexport function createWidgetPanel(\n root: HTMLElement,\n panel: HTMLDialogElement,\n onRequestClose: () => void,\n) {\n const host = root.ownerDocument.defaultView!;\n const mobile = host.matchMedia(widgetMobileQuery);\n const viewport = host.visualViewport;\n let modal = false;\n let releaseScroll: (() => void) | undefined;\n let viewportFrame: number | undefined;\n const cancelViewportFrame = () => {\n if (viewportFrame === undefined) return;\n host.cancelAnimationFrame(viewportFrame);\n viewportFrame = undefined;\n };\n const clearViewport = () => {\n root.style.removeProperty(\"--omni-viewport-shift\");\n root.style.removeProperty(\"--omni-viewport-height\");\n };\n const resize = () => {\n // Keep pinch zoom available; only position above the keyboard at normal scale.\n if (panel.hidden || !mobile.matches || !viewport || viewport.scale !== 1) {\n clearViewport();\n return;\n }\n // When the keyboard reduces the visual viewport, keep the iframe at the\n // layout height and move its bottom to the visible bottom edge.\n const document = root.ownerDocument;\n const viewportRoot =\n document.compatMode === \"CSS1Compat\"\n ? document.documentElement\n : document.body;\n const height = viewportRoot.clientHeight || host.innerHeight;\n // Safari can pan before reporting the keyboard's reduced height. Never\n // counteract that native upward movement with a downward translation.\n const shift = Math.min(0, viewport.offsetTop + viewport.height - height);\n root.style.setProperty(\"--omni-viewport-shift\", `${shift}px`);\n const heightValue = `${height}px`;\n if (root.style.getPropertyValue(\"--omni-viewport-height\") !== heightValue)\n root.style.setProperty(\"--omni-viewport-height\", heightValue);\n };\n const scheduleResize = () => {\n if (viewportFrame !== undefined) return;\n viewportFrame = host.requestAnimationFrame(() => {\n viewportFrame = undefined;\n resize();\n });\n };\n const show = () => {\n if (panel.hidden) return;\n let focused: HTMLElement | null = null;\n if (panel.open && modal !== mobile.matches) {\n focused = root.shadowRoot?.activeElement as HTMLElement | null;\n panel.close();\n }\n modal = mobile.matches;\n if (modal) releaseScroll ??= lockScroll(root.ownerDocument);\n else {\n releaseScroll?.();\n releaseScroll = undefined;\n }\n cancelViewportFrame();\n resize();\n if (!panel.open) {\n if (modal) panel.showModal();\n else panel.show();\n }\n if (focused && panel.contains(focused)) focused.focus();\n };\n const cancel = (event: Event) => {\n event.preventDefault();\n onRequestClose();\n };\n const close = () => {\n cancelViewportFrame();\n panel.hidden = true;\n if (panel.open) panel.close();\n releaseScroll?.();\n releaseScroll = undefined;\n clearViewport();\n };\n mobile.addEventListener(\"change\", show);\n viewport?.addEventListener(\"resize\", scheduleResize);\n viewport?.addEventListener(\"scroll\", scheduleResize);\n panel.addEventListener(\"cancel\", cancel);\n return {\n open() {\n panel.hidden = false;\n show();\n },\n close,\n destroy() {\n close();\n mobile.removeEventListener(\"change\", show);\n viewport?.removeEventListener(\"resize\", scheduleResize);\n viewport?.removeEventListener(\"scroll\", scheduleResize);\n panel.removeEventListener(\"cancel\", cancel);\n },\n };\n}\n","import {\n createOmniChatEmbed,\n getOmniChatEmbedUrl,\n type OmniChatEmbedOptions,\n type OmniChatEmbed,\n} from \"./embed\";\nimport { widgetIcon, widgetStyles } from \"./widget-chrome\";\nimport { loadWidgetConfiguration } from \"./widget-config\";\nimport { createWidgetPanel } from \"./widget-panel\";\nimport {\n resolveWidgetPlacement,\n type OmniChatWidgetPlacement,\n} from \"./widget-placement\";\n\nexport type OmniChatWidgetOptions = OmniChatEmbedOptions &\n Partial<OmniChatWidgetPlacement> & {\n /** Desktop layout; both presentations fill the viewport on mobile. */\n presentation?: \"floating\" | \"sidebar\";\n launcherLabel?: string;\n position?: \"left\" | \"right\";\n launcherBackground?: string;\n launcherForeground?: string;\n panelBackground?: string;\n panelForeground?: string;\n };\nlet widgetSequence = 0;\n/** Loads saved appearance by deployment ID. Explicit options override saved appearance. */\nexport function createOmniChatWidget(\n container: HTMLElement,\n options: OmniChatWidgetOptions,\n) {\n const origin = new URL(getOmniChatEmbedUrl(options)).origin;\n const document = container.ownerDocument;\n const host = document.defaultView;\n if (!host) throw new Error(\"A browser document is required to mount chat.\");\n const controller = new AbortController();\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-omni-chat-widget\", \"\");\n const shadow = root.attachShadow({ mode: \"open\" });\n const style = document.createElement(\"style\");\n style.textContent = widgetStyles;\n const launcher = document.createElement(\"button\");\n const panel = document.createElement(\"dialog\");\n const close = document.createElement(\"button\");\n const frame = document.createElement(\"div\");\n let embed: OmniChatEmbed | undefined;\n let destroyed = false;\n let loaded = false;\n let openRequested = false;\n let appearance = options;\n Object.assign(root.style, {\n position: \"fixed\",\n zIndex: \"2147483000\",\n });\n launcher.type = close.type = \"button\";\n launcher.className = \"launcher\";\n const label = document.createElement(\"span\");\n label.className = \"label\";\n label.textContent = options.launcherLabel ?? \"Chat with us\";\n launcher.append(widgetIcon(document, \"chat\"), label);\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.hidden = true;\n panel.className = \"panel\";\n panel.setAttribute(\"aria-label\", options.title ?? \"Assistant chat\");\n panel.id = `omni-chat-widget-${++widgetSequence}`;\n launcher.setAttribute(\"aria-controls\", panel.id);\n frame.className = \"frame\";\n close.className = \"close\";\n close.setAttribute(\"aria-label\", \"Close chat\");\n close.title = \"Close chat\";\n close.append(widgetIcon(document, \"close\"));\n const closeChat = () => {\n if (destroyed) return;\n openRequested = false;\n panelController.close();\n launcher.hidden = false;\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.setAttribute(\"aria-label\", label.textContent!);\n launcher.querySelector(\"svg\")?.replaceWith(widgetIcon(document, \"chat\"));\n launcher.focus();\n };\n const panelController = createWidgetPanel(root, panel, closeChat);\n const openChat = () => {\n if (destroyed) return;\n if (!loaded) {\n openRequested = true;\n return;\n }\n embed ??= createOmniChatEmbed(frame, {\n ...appearance,\n onRequestClose: closeChat,\n });\n embed.iframe.style.minHeight = \"0\";\n panelController.open();\n launcher.hidden = appearance.presentation === \"sidebar\";\n launcher.setAttribute(\"aria-expanded\", \"true\");\n launcher.setAttribute(\"aria-label\", \"Close chat\");\n launcher\n .querySelector(\"svg\")\n ?.replaceWith(widgetIcon(document, \"collapse\"));\n embed.focus();\n };\n launcher.addEventListener(\"click\", () =>\n panel.hidden ? openChat() : closeChat(),\n );\n close.addEventListener(\"click\", closeChat);\n shadow.addEventListener(\"keydown\", (event) => {\n if ((event as KeyboardEvent).key === \"Escape\" && !panel.hidden) closeChat();\n });\n panel.append(close, frame);\n shadow.append(style, panel, launcher);\n const ready = loadWidgetConfiguration(\n host,\n origin,\n options.deploymentId,\n controller.signal,\n ).then((configuration) => {\n if (destroyed) return;\n appearance = Object.assign(\n configuration,\n Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined),\n ),\n );\n root.dataset.position = appearance.position ?? \"right\";\n root.dataset.presentation = appearance.presentation ?? \"floating\";\n const placement = resolveWidgetPlacement(appearance);\n root.style.setProperty(\n \"--omni-bottom-offset\",\n `${placement.bottomOffset}px`,\n );\n root.style.setProperty(\"--omni-side-offset\", `${placement.sideOffset}px`);\n root.style.setProperty(\n \"--omni-mobile-bottom-offset\",\n `${placement.mobileBottomOffset}px`,\n );\n root.style.setProperty(\n \"--omni-mobile-side-offset\",\n `${placement.mobileSideOffset}px`,\n );\n root.style.setProperty(\n \"--omni-launcher-bg\",\n appearance.launcherBackground!,\n );\n root.style.setProperty(\n \"--omni-launcher-fg\",\n appearance.launcherForeground!,\n );\n root.style.setProperty(\"--omni-panel-bg\", appearance.panelBackground!);\n root.style.setProperty(\"--omni-panel-fg\", appearance.panelForeground!);\n label.textContent = appearance.launcherLabel!;\n launcher.setAttribute(\"aria-label\", label.textContent);\n panel.setAttribute(\"aria-label\", appearance.title!);\n loaded = true;\n container.append(root);\n if (openRequested) openChat();\n });\n void ready.catch((error: unknown) => {\n if (!destroyed)\n options.onError?.(\n error instanceof Error ? error : new Error(\"Could not load chat.\"),\n );\n });\n return {\n /** Resolves once saved appearance is loaded and the launcher is mounted. */\n ready,\n open: openChat,\n close: closeChat,\n destroy() {\n destroyed = true;\n controller.abort();\n panelController.destroy();\n embed?.destroy();\n root.remove();\n },\n };\n}\n","import { getOmniChatEmbedUrl, type OmniChatEmbedOptions } from \"./embed\";\nimport type { OmniChatWidgetOptions } from \"./widget\";\n\ntype EmbedCodeOptions = Pick<\n OmniChatEmbedOptions,\n \"baseUrl\" | \"deploymentId\" | \"title\"\n> &\n Pick<\n OmniChatWidgetOptions,\n | \"presentation\"\n | \"launcherLabel\"\n | \"position\"\n | \"bottomOffset\"\n | \"sideOffset\"\n | \"mobileBottomOffset\"\n | \"mobileSideOffset\"\n | \"launcherBackground\"\n | \"launcherForeground\"\n | \"panelBackground\"\n | \"panelForeground\"\n >;\nconst scriptJson = (value: unknown) =>\n JSON.stringify(value, null, 2).replace(\n /[<>&\\u2028\\u2029]/g,\n (character) =>\n `\\\\u${character.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n\n/** Copyable integrations contain only public deployment configuration. */\nexport function getOmniChatEmbedCode(\n options: EmbedCodeOptions,\n mode: \"widget\" | \"inline\" = \"widget\",\n) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n const config = { ...options, baseUrl };\n const id = `omni-chat-${options.deploymentId}`;\n const mount =\n mode === \"widget\"\n ? `OmniCommerceChat.createOmniChatWidget(document.body, ${scriptJson(config)});`\n : `OmniCommerceChat.createOmniChatEmbed(document.getElementById(${scriptJson(id)}), ${scriptJson(config)});`;\n return `${mode === \"inline\" ? `<div id=\"${id}\" style=\"height:600px\"></div>\\n` : \"\"}<script src=\"${baseUrl}/sdk/embed.global.js\"></script>\\n<script>\\n ${mount.replace(/\\n/g, \"\\n \")}\\n</script>`;\n}\nexport function getOmniChatReactCode(options: EmbedCodeOptions) {\n const baseUrl = new URL(getOmniChatEmbedUrl(options)).origin;\n return `import { OmniProvider, OmniChat } from \"@omni-commerce/sdk/react\";\\n\\n<OmniProvider deploymentId={${scriptJson(options.deploymentId)}}\\n baseUrl={${scriptJson(baseUr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,MAAM,IAAIE,EACRD,EAAO,OAAS,mCAChBD,EAAS,MACX,EACF,OAAOC,CACT,CACF,CAAC,CACH","names":["embed_exports","__export","DEFAULT_WIDGET_OFFSET","MAX_WIDGET_OFFSET","createOmniApplicationChatEmbed","createOmniChatEmbed","createOmniChatWidget","getOmniApplicationChatUrl","getOmniChatEmbedCode","getOmniChatEmbedUrl","getOmniChatReactCode","boundedJson","value","maximum","encoded","createApplicationMessageHandler","input","calls","message","application","name","definition","toolCallId","args","signature","prior","result","error","matchesHostedChatScope","message","scope","ChatSessionError","message","status","__publicField","mountHostedChat","container","options","target","document","host","iframe","chatOrigin","destroyed","pending","previousToken","controller","applicationMessage","createApplicationMessageHandler","receive","event","matchesHostedChatScope","visitorId","session","error","failure","normalizeHostedChatOrigin","value","url","local","chatOrigin","baseUrl","normalizeHostedChatOrigin","getOmniApplicationChatUrl","options","parentOrigin","chatId","url","chatOrigin","parent","appId","key","value","createOmniApplicationChatEmbed","container","host","mountHostedChat","iconPaths","widgetIcon","document","name","svg","path","widgetMobileQuery","widgetStyles","DEFAULT_WIDGET_OFFSET","MAX_WIDGET_OFFSET","resolveWidgetPlacement","options","offset","value","loadWidgetConfiguration","host","origin","deploymentId","signal","response","result","design","color","value","resolveWidgetPlacement","scrollLocks","lockScroll","document","lock","styles","saved","style","index","value","priority","createWidgetPanel","root","panel","onRequestClose","host","mobile","widgetMobileQuery","viewport","modal","releaseScroll","viewportFrame","cancelViewportFrame","clearViewport","resize","height","shift","heightValue","scheduleResize","show","focused","cancel","event","close","widgetSequence","createOmniChatWidget","container","options","origin","getOmniChatEmbedUrl","document","host","controller","root","shadow","style","widgetStyles","launcher","panel","close","frame","embed","destroyed","loaded","openRequested","appearance","label","widgetIcon","closeChat","panelController","createWidgetPanel","openChat","createOmniChatEmbed","event","ready","loadWidgetConfiguration","configuration","value","placement","resolveWidgetPlacement","error","scriptJson","value","character","getOmniChatEmbedCode","options","mode","baseUrl","getOmniChatEmbedUrl","config","id","mount","getOmniChatReactCode","getOmniChatEmbedUrl","options","parentOrigin","base","chatOrigin","url","createOmniChatEmbed","container","host","mountHostedChat","previousToken","visitorId","signal","response","result","ChatSessionError"]}
package/dist/embed.js CHANGED
@@ -22,6 +22,7 @@ function createApplicationMessageHandler(input) {
22
22
  input.reply({
23
23
  type: "omni-chat:application-response",
24
24
  requestId: message.requestId,
25
+ ...input.assistant ? { assistant: boundedJson(input.assistant(), 65536) } : {},
25
26
  application: application ? boundedJson(
26
27
  {
27
28
  name: application.name,
@@ -123,6 +124,7 @@ function mountHostedChat(container, options, target) {
123
124
  const controller = new AbortController();
124
125
  const applicationMessage = createApplicationMessageHandler({
125
126
  options,
127
+ assistant: target.assistant,
126
128
  signal: controller.signal,
127
129
  reply: (message) => {
128
130
  if (!destroyed)
@@ -246,7 +248,11 @@ function createOmniApplicationChatEmbed(container, options) {
246
248
  const chatId = host.crypto.randomUUID();
247
249
  return mountHostedChat(container, options, {
248
250
  url: getOmniApplicationChatUrl(options, host.location.origin, chatId),
249
- scope: { chatId }
251
+ scope: { chatId },
252
+ assistant: () => ({
253
+ ...options.systemPrompt !== void 0 ? { systemPrompt: options.systemPrompt } : {},
254
+ ...options.tools !== void 0 ? { tools: options.tools } : {}
255
+ })
250
256
  });
251
257
  }
252
258