@magicx-eng/ai-autocomplete-vanilla 0.1.18 → 0.1.19

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.
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var J=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var He=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},Be=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ne(e))!Fe.call(n,r)&&r!==t&&J(n,r,{get:()=>e[r],enumerable:!(i=_e(e,r))||i.enumerable});return n};var Ke=n=>Be(J({},"__esModule",{value:!0}),n);var mt={};He(mt,{AIAutocomplete:()=>Y,createStore:()=>V});module.exports=Ke(mt);function v(n,e){let t=n,i={},r=[];for(let s of e){let o=(i[s.type]??0)+1;i[s.type]=o;let l=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,c=t.indexOf(s.text);c!==-1&&(t=t.slice(0,c)+l+t.slice(c+s.text.length)),r.push({...s,placeholder:l})}return{rawQuery:t,completedParams:r}}function A(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function oe(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function w(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function I(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var M=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function se(n,e){let t=[],i=0;for(let s of e){let o=n.indexOf(s.text,i);o!==-1&&(o>i&&t.push({type:"text",value:n.slice(i,o)}),t.push({type:"completed",value:s.text,param:s}),i=o+s.text.length)}let r=n.slice(i);return r&&t.push({type:"text",value:r}),t}function ae(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);o===-1?i.push(s):(t.push(s),r=o+s.text.length)}return{valid:t,invalid:i}}var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var Qe="https://api.ai-autocomplete.com",k=`${Qe}/api/suggest`,le=new WeakMap;function D(n){return n?.type==="accessToken"}function $e(n){if(!(!n||D(n)))return n}function R(n){let e=le.get(n.getAccessToken);return e||(e=new L(n),le.set(n.getAccessToken,e)),e}function _(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function N(n){let e=$e(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function Ue(n){return(n??k).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function qe(n){return D(n)?`Bearer ${await R(n).getToken()}`:N(n)}async function ce(n){try{let e=Ue(n.apiConfig?.endpoint),t=_(n.apiConfig),i=await qe(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var We="0.1.42",de=!1;function je(){return crypto.randomUUID()}function Ge(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Ve(n,e,t,i){let r=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(o=>Ge(o,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:je(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:We,session_id:i}}}async function ue(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function pe(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=Ve(n,e,r,t.sessionId),o=_(i),a=i?.endpoint??k,l=JSON.stringify(s);if(D(i)){let d=R(i),m=await d.getToken(),b=await ue(a,o,m,l,t.signal);if(b.status===401){let g=await d.getToken(!0);b=await ue(a,o,g,l,t.signal)}if(!b.ok)throw new Error(`API error: ${b.status} ${b.statusText}`);return b.json()}let c=N(i);!c&&!de&&(de=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let u=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}function me(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let s=new Set(r.map(a=>a.text)),o=(t.options??[]).filter(a=>!s.has(a.text));return{...t,options:[...r,...o]}}):n}var ze=100,Xe=300,Ye=2,F=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await pe(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let a=me(o.data.suggestions??[],this.getOptionOverrides()),l=o.data.input??[],c=l[l.length-1],u=this.store.get().text,d,m;if(c?.state==="in_progress"){m=!0;let f=u.toLowerCase().lastIndexOf(c.text.toLowerCase());d=f!==-1?f:s}else m=!1,d=s;let g=a.filter(f=>f.type!=="placeholder")[0],h=null;if(g){let f=E(u,d,m),p=I(g.options,f);p&&(h={id:crypto.randomUUID(),placeholder:"",type:g.type,text:p.text,kind:p.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:p.metadata},a=a.filter(x=>x!==g),this.callbacks.onAutoMatch?.({active:g,matched:p,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:m,...h?{completedParams:[...f.completedParams,h]}:{}}))}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let s=r.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),o=A(r.text,r.filterBase,s),a=E(r.text,o,r.filterInProgress),c=r.suggestions.filter(x=>x.type!=="placeholder")[0],d=(c?w(c.options,a):[]).filter(x=>x.is_tappable),m=c?I(c.options,a)!==null:!1,b=a.trim().length>0;if(d.length>0&&!m&&b||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:g,completedParams:h}=v(r.text,r.completedParams),f=g.length<r.lastRawQuery.length,p=Math.abs(g.length-r.lastRawQuery.length);return f||p>=i?(this.doFetch(g,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(Ye)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ze),this.slowDebounceTimer=setTimeout(()=>t(1),Xe)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var fe='[contenteditable="false"]',O;function Je(){if(O!==void 0)return O;let n=globalThis.Intl.Segmenter;if(!n)return O=null,null;try{O=new n(void 0,{granularity:"grapheme"})}catch{O=null}return O??null}function H(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(fe))return!0;t=t.parentNode}return!1}function B(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return H(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Z(n){let e=B(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function he(n){let e=B(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function C(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(H(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=xe(r.childNodes[o],n);return s+ge(r,n)}return t.nodeType!==Node.TEXT_NODE||H(t,n)?null:ge(t,n)+i}function xe(n,e){if(n.nodeType===Node.TEXT_NODE)return H(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(fe))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=xe(r,e);return i}function ge(n,e){let t=B(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,he(n))),s=B(n),o=0,a=null,l=0,c=s.nextNode(),u=null;for(;c;){let m=c.data.length;if(r<o+m){a=c,l=r-o;break}if(r===o+m){let b=s.nextNode();b?(a=b,l=0):(a=c,l=m);break}o+=m,u=c,c=s.nextNode()}let d=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?d.setStartBefore(m):l===a.data.length?d.setStartAfter(m):d.setStart(a,l):d.setStart(a,l)}else u?d.setStart(u,u.data.length):d.setStart(n,0);d.collapse(!0),i.removeAllRanges(),i.addRange(d)}function be(n){let e=C(n);return e==null?!1:e>=he(n)}function ye(n,e){if(e<=0)return 0;let t=Je();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}function Se(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?be(n):!1}function Ze(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?C(n):null}var K=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);switch(e.key){case"ArrowDown":{let l=Se(e.target),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:a[0]??0});break}if(a.length===0)return;let u=a.indexOf(t.activeDropdownIndex),d=u<a.length-1?u+1:0;this.store.set({activeDropdownIndex:a[d]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),c=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-1){let u=t.activeDropdownIndex+1;u<t.filteredOptions.length&&t.filteredOptions[u]?.is_tappable&&this.store.set({activeDropdownIndex:u})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),P(c,u);break}Se(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),P(l,c);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=Ze(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(o){let{rawQuery:l,completedParams:c}=v(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:c}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=!t.text&&!!t.placeholderText,c=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(l&&!c){e.preventDefault();let u=t.placeholderText;if(this.store.set(d=>({text:u,filterBase:u.length,suggestions:d.suggestions.filter(m=>m.type!=="placeholder")})),e.target instanceof HTMLElement){let d=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>P(d,u.length))}}else if(c)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let u=t.filteredOptions.findIndex(d=>d.is_tappable);u>=0&&(e.preventDefault(),this.clickOrSelect(u,t.filteredOptions,i))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),P(l,c)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}};var Q=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:r.text,otherPills:s.map(l=>l.text)})}this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function ve(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,o=n.text.replace(/\s+$/,"").length,a=n.caretOffset==null||n.caretOffset>=o;return(r||n.isLoading)&&s&&a}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function Pe(n,e){let t=se(n.text,n.completedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=A(n.text,Math.min(n.filterBase,n.text.length),o),c=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",u=r?s?s(c.trim()):r.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,m;if(d&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,h=n.completedParams.some(x=>x.id===g),f=n.caretOffset??n.editingAnchor,p=h?"":n.text.slice(n.editingAnchor,f);m=w(n.editingParam.options,p)}else m=w(u,c);e.showNonTappableOptions===!1&&(m=m.filter(g=>g.is_tappable));let b=ve({inEditMode:d,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur});return{segments:t,actionableSuggestions:i,filteredOptions:m,placeholderText:o,isDropdownOpen:b}}function $(n){return n.mode==="fresh"?et(n):tt(n)}function et(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),c=A(e,r,l),u=E(e,c,s),d=I(a.options,u);if(!d)return null;let m=d.text.toLowerCase(),b=e.toLowerCase().lastIndexOf(m),g=b>=0?b:Math.max(0,e.length-d.text.length),h=g+d.text.length,f=e.slice(g,h),x=h<e.length&&e[h]===" "?h+1:h,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:f,kind:d.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:d.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(S=>S!==a),filterBase:x,newParamId:y.id,caretOffset:x,activeDropdownIndex:-1},caretPos:x}}function tt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(y=>y.id===i.id))return null;let o=e.slice(r,s),a=I(i.options,o);if(!a)return null;let l=a.text.toLowerCase(),c=o.toLowerCase().lastIndexOf(l),u=r+Math.max(0,c),d=u+a.text.length,m=e.slice(u,d),g=d<e.length&&e[d]===" "?d+1:d,h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},f=t.length,p=0;for(let y=0;y<t.length;y++){let S=e.indexOf(t[y].text,p);if(S!==-1){if(S>=g){f=y;break}p=S+t[y].text.length}}let x=[...t];return x.splice(f,0,h),{patch:{text:e,completedParams:x,newParamId:h.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}var U=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(l=>l.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let o=t.text.slice(0,r),a=t.text.slice(s),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" ",u=c?`${l} `:l,d=o+u+a,m=r+u.length+(c?0:1),b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},g=t.completedParams.findIndex(p=>p.id===i.id),h=t.completedParams.filter(p=>p.id!==i.id),f=g>=0?Math.min(g,h.length):h.length;h.splice(f,0,b),this.deps.store.set({text:d,completedParams:h,newParamId:b.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=$({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Te="data-aia-key";function q(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Te);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=t.keyOf(a,o);r.add(l);let c=i.get(l);c||(c=t.create(a,o),c.setAttribute(Te,l)),t.update?.(c,a,o),n.children[o]!==c&&n.insertBefore(c,n.children[o]??null),s.push(c)}for(let[o,a]of i)r.has(o)||a.remove();return s}var Ce=[125,69];function Ee(n){return n===0?.4:n===1?.3:.15}function W(n,e,t,i,r=!1,s=!1){let o=n.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",n.appendChild(o)),s&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let a=0;a<Ce.length;a++){let l=Ce[a],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(Ee(a)),o.appendChild(c)}return}s?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let a of o.querySelectorAll("[data-aia-pill-skeleton]"))a.remove();q(o,e,{keyOf:a=>`${a.type}-${a.text}`,create:a=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=a.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(a,l,c)=>{let u=a,d=["magicx-aia-pill"];r&&d.push("magicx-aia-pill--rounded"),c===t&&!s&&d.push("magicx-aia-pill--active"),s&&d.push("magicx-aia-pill--skeleton"),u.className=d.join(" "),u.style.width="",u.style.opacity=String(Ee(c)),s?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(c))}})}function ee(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var nt=[159,119,164];function j(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function G(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:s,pills:o,showPills:a,onSelect:l,onHighlight:c,onPillClick:u}=e,d=a&&o.length>0,m=t.length>0;r&&(m||d||s)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let g=d||s&&a,h=n.querySelector(".magicx-aia-pill-bar");g?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),n.insertBefore(h,n.firstChild)),W(h,o,0,u,!0,s)):h&&h.remove();let f=n.querySelector(".magicx-aia-grid");m?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),it(f,t,i,l,c,e.listboxId,s)):f&&f.remove();let p=n.querySelector(".magicx-aia-skeleton-bars");if(s&&!m){if(!p){p=document.createElement("div"),p.className="magicx-aia-skeleton-bars",p.setAttribute("data-aia-skeleton-bars","");for(let x of nt){let y=document.createElement("span");y.className="magicx-aia-skeleton-bar",y.style.width=`${x}px`,p.appendChild(y)}n.appendChild(p)}}else p&&p.remove()}function it(n,e,t,i,r,s,o){let a=o?"1":"0";q(n,e,{keyOf:l=>`${l.text}\0${a}`,create:l=>rt(l,o),update:(l,c,u)=>{let d=u===t&&!o;l.id=`${s}-option-${u}`,l.dataset.aiaIndex=String(u),l.setAttribute("aria-selected",String(d)),l.classList.toggle("magicx-aia-option--highlighted",d),!o&&c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(c),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let m=Number.parseInt(l.dataset.aiaIndex??"-1",10);m>=0&&r(m)}):(l.onclick=null,l.onmouseenter=null)}})}function rt(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");if(o.className="magicx-aia-option-content",o.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let a=document.createElement("span");a.className="magicx-aia-option-tag",a.textContent=n.tag,o.appendChild(a)}return t.appendChild(o),t}function we(n,e){let t=j(e.listboxId);return n.appendChild(t),{dropdown:t}}function te(n,e,t){G(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function Ae(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let l=t.map(f=>`${f.type}:${f.value}`).join("\0"),c=e.dataset.segKey??"",u=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(l===c&&(i??"")===u&&(r??"")===d)return;let m=o?C(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let b=e.ownerDocument??document,g=b.createDocumentFragment(),h=0;for(let f of t)if(h+=f.value.length,f.type==="completed"){let p=b.createElement("strong");p.dataset.seg="completed",p.dataset.paramId=f.param.id;let x=f.param.id===i,y=f.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];x&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&S.push("magicx-aia-segment--editing"),p.className=S.join(" "),p.textContent=f.value,g.appendChild(p)}else g.appendChild(b.createTextNode(f.value));e.replaceChildren(g),e.dataset.aiaTextLength=String(h),m!=null&&P(e,Math.max(0,Math.min(m,h)))}var ot='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function st(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Ie(n,e){let{listboxId:t}=e,i=j(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",st()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=ot,r.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),r.appendChild(c));let u=new AbortController,{signal:d}=u,m=!1,b=0,g=()=>{let p=Z(o),y=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(y)},h=()=>{let p=(o.ownerDocument??document).getSelection();if(!p||p.rangeCount===0)return null;let x=p.anchorNode;return!x||!o.contains(x)?null:(x.nodeType===Node.ELEMENT_NODE?x:x.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||o.focus()},{signal:d}),o.addEventListener("input",()=>{m||(b=performance.now(),g(),e.handleCaretAfterInput(C(o)))},{signal:d});let f=o.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let p=f.getSelection();if(!p||p.rangeCount===0||!o.contains(p.anchorNode))return;let x=h(),y=e.store.get().editingParam?.id??null;if(x&&x!==y){e.startEditingParam(x);return}performance.now()-b<50||e.handleCaretMove(C(o))},{signal:d}),o.addEventListener("compositionstart",()=>{m=!0},{signal:d}),o.addEventListener("compositionend",()=>{m=!1,g()},{signal:d}),o.addEventListener("beforeinput",p=>{let x=p,y=x.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){p.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let S=y.startsWith("delete")?"":x.data??"";e.replaceEditingRange(S)&&p.preventDefault()}},{signal:d}),o.addEventListener("paste",p=>{p.preventDefault();let x=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!x)return;let y=o.ownerDocument??document,S=y.getSelection();if(!S||S.rangeCount===0)return;let T=S.getRangeAt(0);if(!o.contains(T.startContainer))return;T.deleteContents();let re=y.createTextNode(x);T.insertNode(re),T.setStartAfter(re),T.collapse(!0),S.removeAllRanges(),S.addRange(T),g()},{signal:d}),o.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:d}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),c&&c.addEventListener("click",p=>{let x=e.store.get();if(!(!!x.text||x.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation();let{rawQuery:S,completedParams:T}=v(x.text,x.completedParams);e.onSubmit({query:x.text.trim(),raw_query:S,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1&&o.focus(),{input:o,inlinePillContainer:a,dropdown:i,submitButton:l,abort:u}}function ne(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:u}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?i.setAttribute("aria-activedescendant",d):i.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let m=i.dataset.newParamId??"",b=e.newParamId!==null&&e.newParamId!==m;if(Ae({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?W(r,e.actionableSuggestions,0,l,!1,f):ee(r)}else ee(r);b?(i.focus(),P(i,e.caretOffset??e.text.length)):e.isFocused&&Z(i)!==e.text&&P(i,e.text.length);let g=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,h=g??e.actionableSuggestions[0];G(s,{suggestions:h?[{...h,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:g?[g]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:c,onHighlight:f=>u.set({activeDropdownIndex:f}),onPillClick:l})}function Oe(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=oe(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",c=`${r}${l?" ":""}${e.text} `,u=(s||o)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,d=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=d>=0?u.slice(d,d+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},g=n.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...n.completedParams,b],newParamId:b.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:g>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)},consumedSuggestion:t,remainingActionable:g}}function V(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,s={...e,...r},o=e;e=s;for(let a of t)a(s,o)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function De(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},subscribe:s=>n.subscribe((o,a)=>{let l={...a,...r(a)},c={...o,...r(o)};s(c,l)})}}var ie=!1;function Me(){if(ie||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){ie=!0;return}ie=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=at,document.head.appendChild(n)}var at=`@layer layout {
1
+ "use strict";var J=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var Be=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},Ke=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Fe(e))!He.call(n,r)&&r!==t&&J(n,r,{get:()=>e[r],enumerable:!(i=Ne(e,r))||i.enumerable});return n};var Qe=n=>Ke(J({},"__esModule",{value:!0}),n);var gt={};Be(gt,{AIAutocomplete:()=>Y,createStore:()=>V});module.exports=Qe(gt);function v(n,e){let t=n,i={},r=[];for(let s of e){let o=(i[s.type]??0)+1;i[s.type]=o;let l=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,c=t.indexOf(s.text);c!==-1&&(t=t.slice(0,c)+l+t.slice(c+s.text.length)),r.push({...s,placeholder:l})}return{rawQuery:t,completedParams:r}}function A(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function oe(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function w(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function I(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var M=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function se(n,e){let t=[],i=0;for(let s of e){let o=n.indexOf(s.text,i);o!==-1&&(o>i&&t.push({type:"text",value:n.slice(i,o)}),t.push({type:"completed",value:s.text,param:s}),i=o+s.text.length)}let r=n.slice(i);return r&&t.push({type:"text",value:r}),t}function ae(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);o===-1?i.push(s):(t.push(s),r=o+s.text.length)}return{valid:t,invalid:i}}var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var $e="https://api.ai-autocomplete.com",k=`${$e}/api/suggest`,le=new WeakMap;function D(n){return n?.type==="accessToken"}function Ue(n){if(!(!n||D(n)))return n}function R(n){let e=le.get(n.getAccessToken);return e||(e=new L(n),le.set(n.getAccessToken,e)),e}function _(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function N(n){let e=Ue(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function qe(n){return(n??k).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function We(n){return D(n)?`Bearer ${await R(n).getToken()}`:N(n)}async function ce(n){try{let e=qe(n.apiConfig?.endpoint),t=_(n.apiConfig),i=await We(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var je="0.1.43",de=!1;function Ge(){return crypto.randomUUID()}function Ve(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function ze(n,e,t,i){let r=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(o=>Ve(o,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:Ge(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:je,session_id:i}}}async function pe(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function ue(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=ze(n,e,r,t.sessionId),o=_(i),a=i?.endpoint??k,l=JSON.stringify(s);if(D(i)){let d=R(i),m=await d.getToken(),b=await pe(a,o,m,l,t.signal);if(b.status===401){let g=await d.getToken(!0);b=await pe(a,o,g,l,t.signal)}if(!b.ok)throw new Error(`API error: ${b.status} ${b.statusText}`);return b.json()}let c=N(i);!c&&!de&&(de=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let p=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function me(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let s=new Set(r.map(a=>a.text)),o=(t.options??[]).filter(a=>!s.has(a.text));return{...t,options:[...r,...o]}}):n}var Xe=100,Ye=300,Je=2,F=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await ue(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let a=me(o.data.suggestions??[],this.getOptionOverrides()),l=o.data.input??[],c=l[l.length-1],p=this.store.get().text,d,m;if(c?.state==="in_progress"){m=!0;let f=p.toLowerCase().lastIndexOf(c.text.toLowerCase());d=f!==-1?f:s}else m=!1,d=s;let g=a.filter(f=>f.type!=="placeholder")[0],h=null;if(g){let f=E(p,d,m),u=I(g.options,f);u&&(h={id:crypto.randomUUID(),placeholder:"",type:g.type,text:u.text,kind:u.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:u.metadata},a=a.filter(x=>x!==g),this.callbacks.onAutoMatch?.({active:g,matched:u,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:m,...h?{completedParams:[...f.completedParams,h]}:{}}))}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let s=r.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),o=A(r.text,r.filterBase,s),a=E(r.text,o,r.filterInProgress),c=r.suggestions.filter(x=>x.type!=="placeholder")[0],d=(c?w(c.options,a):[]).filter(x=>x.is_tappable),m=c?I(c.options,a)!==null:!1,b=a.trim().length>0;if(d.length>0&&!m&&b||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:g,completedParams:h}=v(r.text,r.completedParams),f=g.length<r.lastRawQuery.length,u=Math.abs(g.length-r.lastRawQuery.length);return f||u>=i?(this.doFetch(g,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(Je)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Xe),this.slowDebounceTimer=setTimeout(()=>t(1),Ye)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var fe='[contenteditable="false"]',O;function Ze(){if(O!==void 0)return O;let n=globalThis.Intl.Segmenter;if(!n)return O=null,null;try{O=new n(void 0,{granularity:"grapheme"})}catch{O=null}return O??null}function H(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(fe))return!0;t=t.parentNode}return!1}function B(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return H(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Z(n){let e=B(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function he(n){let e=B(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function C(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(H(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=xe(r.childNodes[o],n);return s+ge(r,n)}return t.nodeType!==Node.TEXT_NODE||H(t,n)?null:ge(t,n)+i}function xe(n,e){if(n.nodeType===Node.TEXT_NODE)return H(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(fe))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=xe(r,e);return i}function ge(n,e){let t=B(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,he(n))),s=B(n),o=0,a=null,l=0,c=s.nextNode(),p=null;for(;c;){let m=c.data.length;if(r<o+m){a=c,l=r-o;break}if(r===o+m){let b=s.nextNode();b?(a=b,l=0):(a=c,l=m);break}o+=m,p=c,c=s.nextNode()}let d=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?d.setStartBefore(m):l===a.data.length?d.setStartAfter(m):d.setStart(a,l):d.setStart(a,l)}else p?d.setStart(p,p.data.length):d.setStart(n,0);d.collapse(!0),i.removeAllRanges(),i.addRange(d)}function be(n){let e=C(n);return e==null?!1:e>=he(n)}function ye(n,e){if(e<=0)return 0;let t=Ze();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}function Se(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?be(n):!1}function et(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?C(n):null}var K=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);if(!((e.shiftKey||e.metaKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight")))switch(e.key){case"ArrowDown":{let l=Se(e.target),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:a[0]??0});break}if(a.length===0)return;let p=a.indexOf(t.activeDropdownIndex),d=p<a.length-1?p+1:0;this.store.set({activeDropdownIndex:a[d]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),c=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),P(c,p);break}Se(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),P(l,c);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=et(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(o){let{rawQuery:l,completedParams:c}=v(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:c}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=!t.text&&!!t.placeholderText,c=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(l&&!c){e.preventDefault();let p=t.placeholderText;if(this.store.set(d=>({text:p,filterBase:p.length,suggestions:d.suggestions.filter(m=>m.type!=="placeholder")})),e.target instanceof HTMLElement){let d=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>P(d,p.length))}}else if(c)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(d=>d.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,i))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),P(l,c)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}};var Q=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:r.text,otherPills:s.map(l=>l.text)})}this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function ve(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,o=n.text.replace(/\s+$/,"").length,a=n.caretOffset==null||n.caretOffset>=o;return(r||n.isLoading)&&s&&a}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function Pe(n,e){let t=se(n.text,n.completedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=A(n.text,Math.min(n.filterBase,n.text.length),o),c=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",p=r?s?s(c.trim()):r.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,m;if(d&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,h=n.completedParams.some(x=>x.id===g),f=n.caretOffset??n.editingAnchor,u=h?"":n.text.slice(n.editingAnchor,f);m=w(n.editingParam.options,u)}else m=w(p,c);e.showNonTappableOptions===!1&&(m=m.filter(g=>g.is_tappable));let b=ve({inEditMode:d,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur});return{segments:t,actionableSuggestions:i,filteredOptions:m,placeholderText:o,isDropdownOpen:b}}function $(n){return n.mode==="fresh"?tt(n):nt(n)}function tt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),c=A(e,r,l),p=E(e,c,s),d=I(a.options,p);if(!d)return null;let m=d.text.toLowerCase(),b=e.toLowerCase().lastIndexOf(m),g=b>=0?b:Math.max(0,e.length-d.text.length),h=g+d.text.length,f=e.slice(g,h),x=h<e.length&&e[h]===" "?h+1:h,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:f,kind:d.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:d.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(S=>S!==a),filterBase:x,newParamId:y.id,caretOffset:x,activeDropdownIndex:-1},caretPos:x}}function nt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(y=>y.id===i.id))return null;let o=e.slice(r,s),a=I(i.options,o);if(!a)return null;let l=a.text.toLowerCase(),c=o.toLowerCase().lastIndexOf(l),p=r+Math.max(0,c),d=p+a.text.length,m=e.slice(p,d),g=d<e.length&&e[d]===" "?d+1:d,h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},f=t.length,u=0;for(let y=0;y<t.length;y++){let S=e.indexOf(t[y].text,u);if(S!==-1){if(S>=g){f=y;break}u=S+t[y].text.length}}let x=[...t];return x.splice(f,0,h),{patch:{text:e,completedParams:x,newParamId:h.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}var U=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(l=>l.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(u=>u.text!==e.text).map(u=>u.text)});let o=t.text.slice(0,r),a=t.text.slice(s),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" ",p=c?`${l} `:l,d=o+p+a,m=r+p.length+(c?0:1),b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},g=t.completedParams.findIndex(u=>u.id===i.id),h=t.completedParams.filter(u=>u.id!==i.id),f=g>=0?Math.min(g,h.length):h.length;h.splice(f,0,b),this.deps.store.set({text:d,completedParams:h,newParamId:b.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=$({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Te="data-aia-key";function q(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Te);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=t.keyOf(a,o);r.add(l);let c=i.get(l);c||(c=t.create(a,o),c.setAttribute(Te,l)),t.update?.(c,a,o),n.children[o]!==c&&n.insertBefore(c,n.children[o]??null),s.push(c)}for(let[o,a]of i)r.has(o)||a.remove();return s}var Ce=[125,69];function Ee(n){return n===0?.4:n===1?.3:.15}function W(n,e,t,i,r=!1,s=!1){let o=n.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",n.appendChild(o)),s&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let a=0;a<Ce.length;a++){let l=Ce[a],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(Ee(a)),o.appendChild(c)}return}s?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let a of o.querySelectorAll("[data-aia-pill-skeleton]"))a.remove();q(o,e,{keyOf:a=>`${a.type}-${a.text}`,create:a=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=a.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(a,l,c)=>{let p=a,d=["magicx-aia-pill"];r&&d.push("magicx-aia-pill--rounded"),c===t&&!s&&d.push("magicx-aia-pill--active"),s&&d.push("magicx-aia-pill--skeleton"),p.className=d.join(" "),p.style.width="",p.style.opacity=String(Ee(c)),s?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>i(c))}})}function ee(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var it=[159,119,164];function j(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function G(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:s,pills:o,showPills:a,onSelect:l,onHighlight:c,onPillClick:p}=e,d=a&&o.length>0,m=t.length>0;r&&(m||d||s)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let g=d||s&&a,h=n.querySelector(".magicx-aia-pill-bar");g?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),n.insertBefore(h,n.firstChild)),W(h,o,0,p,!0,s)):h&&h.remove();let f=n.querySelector(".magicx-aia-grid");m?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),rt(f,t,i,l,c,e.listboxId,s)):f&&f.remove();let u=n.querySelector(".magicx-aia-skeleton-bars");if(s&&!m){if(!u){u=document.createElement("div"),u.className="magicx-aia-skeleton-bars",u.setAttribute("data-aia-skeleton-bars","");for(let x of it){let y=document.createElement("span");y.className="magicx-aia-skeleton-bar",y.style.width=`${x}px`,u.appendChild(y)}n.appendChild(u)}}else u&&u.remove()}function rt(n,e,t,i,r,s,o){let a=o?"1":"0";q(n,e,{keyOf:l=>`${l.text}\0${a}`,create:l=>ot(l,o),update:(l,c,p)=>{let d=p===t&&!o;l.id=`${s}-option-${p}`,l.dataset.aiaIndex=String(p),l.setAttribute("aria-selected",String(d)),l.classList.toggle("magicx-aia-option--highlighted",d),!o&&c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(c),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let m=Number.parseInt(l.dataset.aiaIndex??"-1",10);m>=0&&r(m)}):(l.onclick=null,l.onmouseenter=null)}})}function ot(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");o.className="magicx-aia-option-content";let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=n.icon?`${n.icon} ${n.text}`:n.text,o.appendChild(a),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,o.appendChild(l)}return t.appendChild(o),t}function we(n,e){let t=j(e.listboxId);return n.appendChild(t),{dropdown:t}}function te(n,e,t){G(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function Ae(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let l=t.map(f=>`${f.type}:${f.value}`).join("\0"),c=e.dataset.segKey??"",p=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(l===c&&(i??"")===p&&(r??"")===d)return;let m=o?C(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let b=e.ownerDocument??document,g=b.createDocumentFragment(),h=0;for(let f of t)if(h+=f.value.length,f.type==="completed"){let u=b.createElement("strong");u.dataset.seg="completed",u.dataset.paramId=f.param.id;let x=f.param.id===i,y=f.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];x&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&S.push("magicx-aia-segment--editing"),u.className=S.join(" "),u.textContent=f.value,g.appendChild(u)}else g.appendChild(b.createTextNode(f.value));e.replaceChildren(g),e.dataset.aiaTextLength=String(h),m!=null&&P(e,Math.max(0,Math.min(m,h)))}var st='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function at(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Ie(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}if(n.dataset.aiaEmpty==="true"){e.setAttribute("data-aia-pill-wrapped","");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Oe(n,e){let{listboxId:t}=e,i=j(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",at()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=st,r.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),r.appendChild(c));let p=new AbortController,{signal:d}=p,m=!1,b=0,g=()=>{let u=Z(o),y=u.length>0&&u[0]!==u[0].toUpperCase()?u[0].toUpperCase()+u.slice(1):u;e.handleChange(y)},h=()=>{let u=(o.ownerDocument??document).getSelection();if(!u||u.rangeCount===0)return null;let x=u.anchorNode;return!x||!o.contains(x)?null:(x.nodeType===Node.ELEMENT_NODE?x:x.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",u=>{u.target?.closest("[data-aia-pill]")||o.focus()},{signal:d}),o.addEventListener("input",()=>{m||(b=performance.now(),g(),e.handleCaretAfterInput(C(o)))},{signal:d});let f=o.ownerDocument??document;if(f.addEventListener("selectionchange",()=>{let u=f.getSelection();if(!u||u.rangeCount===0||!o.contains(u.anchorNode))return;let x=h(),y=e.store.get().editingParam?.id??null;if(x&&x!==y){e.startEditingParam(x);return}performance.now()-b<50||e.handleCaretMove(C(o))},{signal:d}),o.addEventListener("compositionstart",()=>{m=!0},{signal:d}),o.addEventListener("compositionend",()=>{m=!1,g()},{signal:d}),o.addEventListener("beforeinput",u=>{let x=u,y=x.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){u.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let S=y.startsWith("delete")?"":x.data??"";e.replaceEditingRange(S)&&u.preventDefault()}},{signal:d}),o.addEventListener("paste",u=>{u.preventDefault();let x=(u.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!x)return;let y=o.ownerDocument??document,S=y.getSelection();if(!S||S.rangeCount===0)return;let T=S.getRangeAt(0);if(!o.contains(T.startContainer))return;T.deleteContents();let re=y.createTextNode(x);T.insertNode(re),T.setStartAfter(re),T.collapse(!0),S.removeAllRanges(),S.addRange(T),g()},{signal:d}),o.addEventListener("keydown",u=>e.handleKeyDown(u),{signal:d}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),c&&c.addEventListener("click",u=>{let x=e.store.get();if(!(!!x.text||x.completedParams.length>0)||!e.onSubmit)return;u.stopPropagation();let{rawQuery:S,completedParams:T}=v(x.text,x.completedParams);e.onSubmit({query:x.text.trim(),raw_query:S,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1&&o.focus(),typeof ResizeObserver<"u"){let u=new ResizeObserver(()=>Ie(o,a));u.observe(o),p.signal.addEventListener("abort",()=>u.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:i,submitButton:l,abort:p}}function ne(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?i.setAttribute("aria-activedescendant",d):i.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let m=i.dataset.newParamId??"",b=e.newParamId!==null&&e.newParamId!==m;if(Ae({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?W(r,e.actionableSuggestions,0,l,!1,f):ee(r)}else ee(r);Ie(i,r),b?(i.focus(),P(i,e.caretOffset??e.text.length)):e.isFocused&&Z(i)!==e.text&&P(i,e.text.length);let g=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,h=g??e.actionableSuggestions[0];G(s,{suggestions:h?[{...h,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:g?[g]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:c,onHighlight:f=>p.set({activeDropdownIndex:f}),onPillClick:l})}function De(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=oe(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",c=`${r}${l?" ":""}${e.text} `,p=(s||o)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,d=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=d>=0?p.slice(d,d+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},g=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,b],newParamId:b.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:g>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)},consumedSuggestion:t,remainingActionable:g}}function V(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,s={...e,...r},o=e;e=s;for(let a of t)a(s,o)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function Me(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},subscribe:s=>n.subscribe((o,a)=>{let l={...a,...r(a)},c={...o,...r(o)};s(c,l)})}}var ie=!1;function Le(){if(ie||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){ie=!0;return}ie=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=lt,document.head.appendChild(n)}var lt=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -94,8 +94,8 @@
94
94
  position: relative;
95
95
  flex: 1;
96
96
  min-width: 0;
97
- min-height: 38px;
98
- line-height: 38px;
97
+ min-height: 26.6px;
98
+ line-height: 26.6px;
99
99
  font-family: inherit;
100
100
  font-size: var(--aia-written-text-font-size, 19px);
101
101
  white-space: pre-wrap;
@@ -113,7 +113,10 @@
113
113
  --aia-caret-color,
114
114
  var(--aia-written-text-color, var(--aia-color-text-default, #fff))
115
115
  );
116
- font-weight: 200;
116
+ font-weight: 250;
117
+ /* Align the text's inline box with the pill list (also vertical-align: middle)
118
+ so they share a vertical center when pills stretch the line box to ~36px. */
119
+ vertical-align: middle;
117
120
  }
118
121
 
119
122
  /* Empty inline contentEditables don't have an inline box, so the browser has
@@ -132,14 +135,24 @@
132
135
  letter-spacing: -0.01em;
133
136
  }
134
137
 
135
- /* Re-edit highlight \u2014 applied to the bold param being re-edited. The DOM
136
- keeps a Selection range over the strong so the browser still handles
137
- typing / backspace as a range replacement; we hide the native selection
138
- paint and the caret so the only visual cue is this outline. */
138
+ /* Re-edit highlight \u2014 applied to the bold param being re-edited. A 20% fill
139
+ marks the selection; the native selection paint and caret are hidden so the
140
+ only visual cue is this fill. */
139
141
  :where(.magicx-aia-input) strong.magicx-aia-segment--editing {
140
- outline: 1.5px solid var(--aia-edit-outline, currentColor);
141
- outline-offset: 1px;
142
- border-radius: 4px;
142
+ background-color: color-mix(in srgb, var(--aia-edit-outline, currentColor) 20%, transparent);
143
+ border-radius: 6px;
144
+ padding: 2px 3px;
145
+ /* Pull surrounding inline text back so the wider/taller fill doesn't shove
146
+ the rest of the line \u2014 only the visible background grows. */
147
+ margin: 0 -1.5px;
148
+ caret-color: transparent;
149
+ }
150
+
151
+ /* In re-edit mode the caret is parked just *before* the bold strong, which
152
+ means it sits in the parent .magicx-aia-input, not inside the strong, so the
153
+ rule above doesn't hide it. Use :has() to hide the caret on the whole
154
+ editor while any completed param is selected. */
155
+ .magicx-aia-input:has(strong.magicx-aia-segment--editing) {
143
156
  caret-color: transparent;
144
157
  }
145
158
 
@@ -169,8 +182,12 @@
169
182
  }
170
183
 
171
184
  /* Hide the leading margin when there are no pills so an empty container
172
- doesn't bias the cursor's resting position to the right. */
173
- .magicx-aia-pill-list-container:empty {
185
+ doesn't bias the cursor's resting position to the right. Also drop it when
186
+ the JS-side wrap detector has flagged the pill list as wrapped to its own
187
+ line \u2014 the 8px would render as a stray left indent at the start of the
188
+ wrapped line. */
189
+ .magicx-aia-pill-list-container:empty,
190
+ .magicx-aia-pill-list-container[data-aia-pill-wrapped] {
174
191
  margin-left: 0;
175
192
  }
176
193
 
@@ -277,10 +294,17 @@
277
294
  animation: magicx-aia-option-skeleton-pulse 1.4s ease-in-out infinite;
278
295
  }
279
296
 
280
- .magicx-aia-option[data-aia-loading] .magicx-aia-option-content {
297
+ /* Skeleton fill is on the inner text span (a true inline element) so multi-
298
+ line options wrap into one skeleton bar per line. The outer .content is a
299
+ flex item \u2014 blockified by spec \u2014 so painting the background there would
300
+ collapse all lines into one tall rectangle. \`box-decoration-break: clone\`
301
+ makes the radius render cleanly on each line bar. */
302
+ .magicx-aia-option[data-aia-loading] .magicx-aia-option-text {
281
303
  color: transparent;
282
304
  background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
283
305
  border-radius: 999px;
306
+ -webkit-box-decoration-break: clone;
307
+ box-decoration-break: clone;
284
308
  }
285
309
 
286
310
  .magicx-aia-option[data-aia-loading] .magicx-aia-option-tag {
@@ -442,11 +466,11 @@
442
466
  align-items: flex-start;
443
467
  font-family: inherit;
444
468
  font-size: var(--aia-option-font-size, 19px);
469
+ font-weight: 250;
445
470
  line-height: 24px;
446
471
  color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
447
472
  white-space: normal;
448
473
  word-break: break-word;
449
- opacity: 0.4;
450
474
  border-radius: 12px;
451
475
  padding: 13px 13px;
452
476
  animation: magicx-aia-optionFadeIn 500ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
@@ -473,13 +497,11 @@
473
497
 
474
498
  .magicx-aia-option--non-tappable {
475
499
  cursor: default;
476
- opacity: 0.3;
477
500
  }
478
501
 
479
502
  .magicx-aia-option--highlighted {
480
503
  color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
481
504
  background: var(--aia-option-bg, transparent);
482
- opacity: 0.5;
483
505
  }
484
506
 
485
507
  .magicx-aia-option-tag {
@@ -804,7 +826,7 @@
804
826
  --aia-pill-font-size: 19px;
805
827
 
806
828
  --aia-option-bg: transparent;
807
- --aia-option-color: #000000;
829
+ --aia-option-color: #4f4f4f;
808
830
  --aia-option-color-selected: #000000;
809
831
  --aia-option-font-size: 19px;
810
832
 
@@ -830,7 +852,7 @@
830
852
  --aia-pill-font-size: 19px;
831
853
 
832
854
  --aia-option-bg: transparent;
833
- --aia-option-color: #ffffff;
855
+ --aia-option-color: #b0b0b0;
834
856
  --aia-option-color-selected: #ffffff;
835
857
  --aia-option-font-size: 19px;
836
858
 
@@ -869,5 +891,5 @@
869
891
  animation-duration: 0s !important;
870
892
  transition-duration: 0s !important;
871
893
  }
872
- `;var z=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var X=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var lt="newParam",Le="suggestionRemoval",ct="selectionAnimation",dt=650,ut=0;function pt(){return`:ac-${++ut}:`}var ke=500;function Re(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Y=class{constructor(e,t={}){this.inputStore=V(Re());this._listboxId=pt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new X;this.emitter=new z;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=De(this.inputStore,i=>Pe(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Q(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new U({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new F(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new K(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(Me(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){this.store.set({...Re(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],l=i.indexOf(a.text,s);if(l===-1)continue;let c=l,u=l+a.text.length;if(e>c&&e<=u){let d=ye(i,e),m=i.slice(0,d)+i.slice(e),b=r.filter((g,h)=>h!==o);return this.store.set(g=>({text:m,filterBase:Math.min(g.filterBase,m.length),completedParams:b,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}s=u}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),P(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Oe(t,e);if(i&&(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Le),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Le,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},ke)}}startSelectionAnimationTimer(){this.timers.schedule(ct,()=>this.store.set({inSelectionAnimation:!1}),ke)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");ce({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Ie(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&ne(this.domRefs,this.store.get(),t)}),ne(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=we(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&te(this.dropdownRefs,this.store.get(),e)}),te(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(lt,()=>this.store.set({newParamId:null}),dt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=ae(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(w(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=v(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=$({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,createStore});
894
+ `;var z=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var X=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ct="newParam",ke="suggestionRemoval",dt="selectionAnimation",pt=650,ut=0;function mt(){return`:ac-${++ut}:`}var Re=500;function _e(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Y=class{constructor(e,t={}){this.inputStore=V(_e());this._listboxId=mt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new X;this.emitter=new z;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Me(this.inputStore,i=>Pe(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Q(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new U({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new F(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new K(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(Le(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){this.store.set({..._e(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],l=i.indexOf(a.text,s);if(l===-1)continue;let c=l,p=l+a.text.length;if(e>c&&e<=p){let d=ye(i,e),m=i.slice(0,d)+i.slice(e),b=r.filter((g,h)=>h!==o);return this.store.set(g=>({text:m,filterBase:Math.min(g.filterBase,m.length),completedParams:b,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}s=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),P(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=De(t,e);if(i&&(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(ke),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(ke,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},Re)}}startSelectionAnimationTimer(){this.timers.schedule(dt,()=>this.store.set({inSelectionAnimation:!1}),Re)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");ce({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Oe(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&ne(this.domRefs,this.store.get(),t)}),ne(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=we(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&te(this.dropdownRefs,this.store.get(),e)}),te(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(ct,()=>this.store.set({newParamId:null}),pt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=ae(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(w(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=v(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=$({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,createStore});
873
895
  //# sourceMappingURL=index.js.map