@kitn.ai/ui
Version:
Framework-agnostic, Shadow-DOM web components for building AI chat interfaces — works in React, Vue, Angular, Svelte, or plain HTML. Authored in SolidJS.
2 lines (1 loc) • 7.88 kB
JavaScript
import{f as J,g as K,p as T,o as Q,h as X}from"./chunks/define-CNSKFZCd.js";import{r as Y,e as Z}from"./chunks/card-routing-C986KuUA.js";const q="kitn-card";function M(n,e){return function(o){return{protocol:q,version:n,nonce:e,message:o}}}function ee(n,e){if(typeof n!="object"||n===null)return!1;const o=n,t=o.message;return o.protocol===q&&typeof o.version=="string"&&typeof o.nonce=="string"&&typeof t=="object"&&t!==null&&t.dir===e}function ne(n,e,o){const t=new URL(n).origin;if(e===o)throw new Error("[kai-remote] providerOrigin must be cross-origin to the host");if(t===o)throw new Error("[kai-remote] src must not be same-origin as the host");if(t!==e)throw new Error("[kai-remote] src origin must equal providerOrigin")}const te=new Set(["protocol","version","dir","kind","mode","locale","edge","code","acceptedVersion","supportedVersions","cardId","type","id","height","target"]),oe=new Set(["authToken","nonce"]);function O(n){if(Array.isArray(n))return n.map(O);if(n&&typeof n=="object"){const e={};for(const[o,t]of Object.entries(n))oe.has(o)?e[o]="[redacted]":typeof t=="object"&&t!==null?e[o]=O(t):e[o]=te.has(o)?t:"[redacted]";return e}return n}function re(n){return/^[0-9]+$/.test(n)}const ie=new Set(["__proto__","constructor","prototype"]);function R(n){if(Array.isArray(n))return n.some(R);if(n&&typeof n=="object"){for(const e of Object.keys(n))if(ie.has(e)||R(n[e]))return!0}return!1}const ce=new Set(["ready","submit","action","send-prompt","open","resize","state","dismiss","error"]);function ae(n){return typeof n=="string"&&ce.has(n)}const V=["1"],le="allow-scripts allow-forms allow-same-origin",de=5e3;function se(n){try{return new URL(n).host}catch{return n}}function ue(n){const{container:e,providerOrigin:o,src:t,policy:r,maxHeight:d}=n,s=typeof window<"u"?window.location.origin:"";ne(t,o,s);const g=n.handshakeTimeoutMs??de;let m=0,w=P(),k=M("1",w),l="connecting",b=pe(n.context),v=n.envelope,p=null,u=null,c=null,I,y=null;function $(i){try{console.warn("[kai-remote]",O(i))}catch{}}function x(i){const a=c?.contentWindow;if(a)try{a.postMessage(k(i),o)}catch{}}function S(){I!==void 0&&(clearTimeout(I),I=void 0)}function U(i){l==="open"?x({dir:"down",kind:"context",context:i}):l==="connecting"&&(p=i)}function _(i){l==="open"?x({dir:"down",kind:"render",envelope:i}):l==="connecting"&&(u=i)}function z(){p&&(x({dir:"down",kind:"context",context:p}),p=null),u&&(x({dir:"down",kind:"render",envelope:u}),u=null)}function D(i){const a=document.createElement("div");a.setAttribute("role","alert"),a.dataset.kaiRemoteFallback="";const E=document.createElement("p");E.textContent=i,a.appendChild(E);const h=document.createElement("button");h.type="button",h.textContent="Retry",h.addEventListener("click",()=>W()),a.appendChild(h),c&&c.parentNode===e?e.replaceChild(a,c):e.appendChild(a),c=null}function L(i){l!=="closed"&&(S(),l="error",p=null,u=null,D(i))}function j(){const i=m,a=document.createElement("iframe");a.setAttribute("sandbox",n.sandbox??le),a.setAttribute("referrerpolicy","no-referrer"),a.setAttribute("allow","");const E=v.title??v.type;a.setAttribute("title",`${E} \u2014 provided by ${se(o)}`),a.style.border="0",a.style.width="100%",a.addEventListener("load",()=>{m!==i||l!=="connecting"||(k=M("1",w),x({dir:"down",kind:"hello",supportedVersions:V}),S(),I=setTimeout(()=>{var h;m!==i||l!=="connecting"||(L("[timeout] The card took too long to load."),(h=r?.onError)==null||h.call(r,v.id,"[timeout] handshake timed out"))},g))}),y=h=>N(h,i),window.addEventListener("message",y),c=a,e.appendChild(a),a.setAttribute("src",t)}function W(){l==="error"&&(m+=1,w=P(),k=M("1",w),l="connecting",p=null,u=null,S(),y&&(window.removeEventListener("message",y),y=null),c&&(c.remove(),c=null),p=b,u=v,e.querySelectorAll("[data-kai-remote-fallback]").forEach(i=>i.remove()),j())}function F(i){if(!c)return;const a=Math.min(i,d??1/0);c.style.height=`${a}px`}function H(){if(c)try{c.blur()}catch{}}function N(i,a){var E,h;if(a!==m||l==="closed"||l==="error")return;const A=i.data;if(i.origin===o&&i.source===c?.contentWindow&&ee(A,"up")&&A.nonce===w)try{const C=A.message;switch(C.kind){case"ready":{if(l!=="connecting")return;const f=C.acceptedVersion;if(!re(f)||!V.includes(f)){L("[version-unsupported] This card needs a different host version."),(E=r?.onError)==null||E.call(r,v.id,"[version-unsupported] no compatible protocol version");return}k=M(f,w),S(),l="open",p||(p=b),u||(u=v),z();return}case"event":{if(l!=="open")return;const f=C.event;if(f.cardId!==v.id)return;if(f.kind==="resize"){F(f.height);return}if(!ae(f.kind)||R(f)){$(A);return}Y(r??{},f);return}case"focus-edge":{H();return}case"fault":{const f=C.code,G=C.message;L(`[${f}] The card reported a problem.`),(h=r?.onError)==null||h.call(r,v.id,`[${f}] ${G}`);return}default:return}}catch{$(A)}}const B={updateContext(i){l!=="closed"&&(b=fe(b,i),U(b))},update(i){l!=="closed"&&(v=i,_(i))},destroy(){l!=="closed"&&(m+=1,l==="open"&&x({dir:"down",kind:"teardown"}),l="closed",S(),y&&(window.removeEventListener("message",y),y=null),c&&(c.remove(),c=null),e.querySelectorAll("[data-kai-remote-fallback]").forEach(i=>i.remove()))},state(){return l}};return j(),B}function P(){const n=new Uint8Array(16);crypto.getRandomValues(n);let e="";for(const o of n)e+=o.toString(16).padStart(2,"0");return e}function pe(n){return{...n}}function fe(n,e){return{...n,...e}}function me(n){if(!n||n==="*"||n.includes(","))return!1;let e;try{e=new URL(n)}catch{return!1}return e.pathname!=="/"||e.search!==""||e.hash!==""?!1:e.protocol==="https:"?!0:e.protocol==="http:"?e.hostname==="localhost"||e.hostname==="127.0.0.1":!1}function he(n,e){function o(t){Z(n,t)}return{onSubmit(t,r){var d;o({kind:"submit",cardId:t,data:r}),(d=e?.onSubmit)==null||d.call(e,t,r)},onAction(t,r,d){var s;o({kind:"action",cardId:t,action:r,payload:d}),(s=e?.onAction)==null||s.call(e,t,r,d)},onSendPrompt(t,r){var d;o({kind:"send-prompt",cardId:"",text:t,mode:r.mode,context:r.context}),(d=e?.onSendPrompt)==null||d.call(e,t,r)},onOpen(t,r){var d;o({kind:"open",cardId:"",url:t,target:r}),(d=e?.onOpen)==null||d.call(e,t,r)},onState(t,r){var d;o({kind:"state",cardId:t,patch:r}),(d=e?.onState)==null||d.call(e,t,r)},onDismiss(t){var r;o({kind:"dismiss",cardId:t}),(r=e?.onDismiss)==null||r.call(e,t)},onReopen(t){var r;o({kind:"reopen",cardId:t}),(r=e?.onReopen)==null||r.call(e,t)},onError(t,r){var d;o({kind:"error",cardId:t,message:r}),(d=e?.onError)==null||d.call(e,t,r)},maxSendPromptMode:e?.maxSendPromptMode}}J("kai-remote",{src:void 0,providerOrigin:void 0,envelope:void 0,policy:void 0},(n,{element:e})=>{let o;const[t,r]=K(!1);if(typeof window<"u"&&typeof window.matchMedia=="function"){const s=window.matchMedia("(prefers-color-scheme: dark)");r(s.matches);const g=m=>r(m.matches);s.addEventListener("change",g),T(()=>s.removeEventListener("change",g))}const d=()=>{const s=n.theme??"auto";return s==="dark"||s==="auto"&&t()};return Q(()=>{const s=e.shadowRoot;if(!s)return;function g(u){const c=document.createElement("div");c.setAttribute("role","alert"),c.textContent=u,s.appendChild(c)}const m=n.providerOrigin;if(!me(m)){g(`[kai-remote] Invalid provider-origin "${m??""}". Must be an absolute https: origin, or http://localhost / http://127.0.0.1 for local dev.`);return}const w=n.src;if(!w){g('[kai-remote] Missing required "src" attribute.');return}const k=n.envelope;if(!k){g('[kai-remote] Missing required "envelope" property.');return}const l={theme:{mode:d()?"dark":"light"},locale:typeof navigator<"u"&&navigator.language||"en"},b=n.policy,v=he(e,b),p=document.createElement("div");s.appendChild(p);try{o=ue({container:p,providerOrigin:m,src:w,envelope:k,context:l,policy:v})}catch(u){const c=u instanceof Error?u.message:String(u);g(`[kai-remote] Mount failed: ${c}`),p.remove();return}T(()=>{o?.destroy(),o=void 0})}),X(()=>{const s=d()?"dark":"light";o?.updateContext({theme:{mode:s}})}),[]});