auto-webmcp 0.3.5 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var AutoWebMCP=(()=>{var O=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var K=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})},Ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ce(t))!ke.call(e,i)&&i!==n&&O(e,i,{get:()=>t[i],enumerable:!(r=Ae(t,i))||r.enumerable});return e};var Fe=e=>Ie(O({},"__esModule",{value:!0}),e);var pe={};K(pe,{getAllRegisteredTools:()=>D,getRegisteredToolName:()=>et,isWebMCPSupported:()=>T,registerFormTool:()=>N,unregisterAll:()=>B,unregisterFormTool:()=>x});function T(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function N(e,t,n){if(!T())return;h.get(e)&&await x(e);let i={name:t.name,description:t.description,inputSchema:t.inputSchema,execute:n};t.annotations&&Object.keys(t.annotations).length>0&&(i.annotations=t.annotations);try{await navigator.modelContext.registerTool(i)}catch{try{await navigator.modelContext.unregisterTool(t.name),await navigator.modelContext.registerTool(i)}catch{}}h.set(e,t.name)}async function x(e){if(!T())return;let t=h.get(e);if(t){try{await navigator.modelContext.unregisterTool(t)}catch{}h.delete(e)}}function et(e){return h.get(e)}function D(){return Array.from(h.entries()).map(([e,t])=>({form:e,name:t}))}async function B(){let e=Array.from(h.entries());await Promise.all(e.map(([t])=>x(t)))}var h,A=Re(()=>{"use strict";h=new Map});var Et={};K(Et,{autoWebMCP:()=>ve});function Y(e){return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,overrides:e?.overrides??{},debug:e?.debug??!1}}var H=["textbox","combobox","checkbox","radio","switch","spinbutton","searchbox","slider"];function _(e){return e instanceof HTMLInputElement?Oe(e):e instanceof HTMLTextAreaElement?{type:"string"}:e instanceof HTMLSelectElement?_e(e):null}function Oe(e){switch(e.type.toLowerCase()){case"text":case"search":case"tel":return P(e);case"email":return{...P(e),format:"email"};case"url":return{...P(e),format:"uri"};case"number":case"range":{let n={type:"number"};return e.min!==""&&(n.minimum=parseFloat(e.min)),e.max!==""&&(n.maximum=parseFloat(e.max)),n}case"date":return{type:"string",format:"date"};case"datetime-local":return{type:"string",format:"date-time"};case"time":return{type:"string",format:"time"};case"month":return{type:"string",pattern:"^\\d{4}-\\d{2}$"};case"week":return{type:"string",pattern:"^\\d{4}-W\\d{2}$"};case"color":return{type:"string",pattern:"^#[0-9a-fA-F]{6}$"};case"checkbox":return{type:"boolean"};case"radio":return{type:"string"};case"file":case"hidden":case"submit":case"reset":case"button":case"image":return null;case"password":return null;default:return{type:"string"}}}function P(e){let t={type:"string"};e.minLength>0&&(t.minLength=e.minLength),e.maxLength>0&&e.maxLength!==524288&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern);let n=e.getAttribute("list");if(n){let r=e.ownerDocument.getElementById(n);if(r instanceof HTMLDataListElement){let i=Array.from(r.options).filter(s=>!s.disabled&&s.value.trim()!=="");i.length>0&&(t.enum=i.map(s=>s.value.trim()),t.oneOf=i.map(s=>({const:s.value.trim(),title:s.textContent?.trim()||s.value.trim()})))}}return t}var Pe=/^(select|choose|pick)\b|^--+|---/i;function X(e){return e.disabled?!0:e.value!==""?!1:Pe.test(e.text.trim())}function _e(e){let t=[],n=[];for(let r of Array.from(e.children))if(r instanceof HTMLOptGroupElement){if(r.disabled)continue;let i=r.label?.trim()??"";for(let s of Array.from(r.children)){if(!(s instanceof HTMLOptionElement)||X(s))continue;t.push(s.value);let o={const:s.value,title:s.text.trim()||s.value};i&&(o.group=i),n.push(o)}}else if(r instanceof HTMLOptionElement){if(X(r))continue;t.push(r.value),n.push({const:r.value,title:r.text.trim()||r.value})}return t.length===0?{type:"string"}:e.multiple?{type:"array",items:{type:"string",enum:t}}:{type:"string",enum:t,oneOf:n}}function Q(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!==""&&n!=="on")}function Z(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(r=>r.value).filter(r=>r!=="")}function ee(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).filter(r=>r.value!=="").map(r=>{let i=$e(r);return{const:r.value,title:i||r.value}})}function te(e,t){switch(t){case"checkbox":case"switch":return{type:"boolean"};case"spinbutton":case"slider":{let n={type:"number"},r=e.getAttribute("aria-valuemin"),i=e.getAttribute("aria-valuemax");return r!==null&&(n.minimum=parseFloat(r)),i!==null&&(n.maximum=parseFloat(i)),n}case"combobox":{let n=e.getAttribute("aria-owns")??e.getAttribute("aria-controls");if(n){let r=document.getElementById(n);if(r){let i=Array.from(r.querySelectorAll('[role="option"]')).filter(s=>s.getAttribute("aria-disabled")!=="true");if(i.length>0){let s=i.map(l=>(l.getAttribute("data-value")??l.textContent??"").trim()).filter(Boolean),o=i.map(l=>({const:(l.getAttribute("data-value")??l.textContent??"").trim(),title:(l.textContent??"").trim()}));return{type:"string",enum:s,oneOf:o}}}}return{type:"string"}}case"textbox":case"searchbox":case"radio":default:return{type:"string"}}}function $e(e){let t=e.closest("label");if(t){let n=t.cloneNode(!0);n.querySelectorAll("input, select, textarea, button").forEach(i=>i.remove());let r=n.textContent?.trim()??"";if(r)return r}if(e.id){let n=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(n){let r=n.textContent?.trim()??"";if(r)return r}}return""}var ie=0;function oe(e,t){let n=t?.name??qe(e),r=t?.description??De(e),{schema:i,fieldElements:s}=Ue(e),o=je(e);return{name:n,description:r,inputSchema:i,annotations:o,fieldElements:s}}function qe(e){let t=e.getAttribute("toolname");if(t)return E(t);let n=e.dataset.webmcpName;if(n)return E(n);let r=$(e);if(r)return E(r);let i=se(e);if(i)return E(i);if(e.id)return E(e.id);if(e.name)return E(e.name);if(e.action){let s=Ne(e.action);if(s)return E(s)}return`form_${++ie}`}function E(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"form"}function $(e){let t=[...Array.from(e.querySelectorAll('button[type="submit"], button:not([type])')),...Array.from(e.querySelectorAll('input[type="submit"]'))];for(let n of t){let r=n instanceof HTMLInputElement?n.value.trim():n.textContent?.trim()??"";if(r&&r.length>0&&r.length<80)return r}return""}function se(e){let t=e;for(;t;){let n=t.previousElementSibling;for(;n;){if(/^H[1-3]$/i.test(n.tagName)){let r=n.textContent?.trim()??"";if(r)return r}n=n.previousElementSibling}if(t=t.parentElement,!t||t===document.body)break}return""}function Ne(e){try{let n=new URL(e,window.location.href).pathname.split("/").filter(Boolean);return n[n.length-1]??""}catch{return""}}function De(e){let t=e.getAttribute("tooldescription");if(t)return t.trim();let n=e.dataset.webmcpDescription;if(n)return n.trim();let r=e.querySelector("legend");if(r?.textContent?.trim())return r.textContent.trim();let i=e.getAttribute("aria-label");if(i?.trim())return i.trim();let s=e.getAttribute("aria-describedby");if(s){let a=document.getElementById(s);if(a?.textContent?.trim())return a.textContent.trim()}let o=se(e),l=document.title?.trim();return o&&l?`${o}: ${l}`:o||l||"Submit form"}var Be=/^(search|find|look|filter|browse|view|show|check|preview|get|fetch|retrieve|load)\b/i,We=/^(delete|remove|cancel|terminate|destroy|purge|revoke|unsubscribe|deactivate)\b/i,Je=/\/(delete|remove|cancel|destroy)\b/i;function je(e){let t={};if(e.dataset.webmcpReadonly!==void 0&&(t.readOnlyHint=e.dataset.webmcpReadonly!=="false"),e.dataset.webmcpDestructive!==void 0&&(t.destructiveHint=e.dataset.webmcpDestructive!=="false"),e.dataset.webmcpIdempotent!==void 0&&(t.idempotentHint=e.dataset.webmcpIdempotent!=="false"),e.dataset.webmcpOpenworld!==void 0&&(t.openWorldHint=e.dataset.webmcpOpenworld!=="false"),t.readOnlyHint===void 0){let r=e.method.toLowerCase()==="get",i=$(e),s=i?Be.test(i.trim()):!1;(r||s)&&(t.readOnlyHint=!0)}if(t.destructiveHint===void 0){let r=$(e),i=r?We.test(r.trim()):!1,s=e.action?Je.test(e.action):!1;(i||s)&&(t.destructiveHint=!0)}return t.idempotentHint===void 0&&(t.readOnlyHint===!0||e.method.toLowerCase()==="get")&&(t.idempotentHint=!0),t.openWorldHint===void 0&&(t.openWorldHint=t.readOnlyHint!==!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function Ve(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"?e.checked?!0:void 0:t==="radio"?void 0:t==="number"||t==="range"?e.value!==""?parseFloat(e.value):void 0:e.value!==""?e.value:void 0}if(e instanceof HTMLTextAreaElement)return e.value!==""?e.value:void 0;if(e instanceof HTMLSelectElement){if(e.multiple){let t=Array.from(e.options).filter(n=>n.selected).map(n=>n.value);return t.length>0?t:void 0}return e.value!==""?e.value:void 0}}function ae(e,t=new Set){if(t.has(e))return[];t.add(e);let n=[];for(let r of Array.from(e.querySelectorAll("*")))r.shadowRoot&&n.push(...Array.from(r.shadowRoot.querySelectorAll("input, textarea, select")),...ae(r.shadowRoot,t));return n}function Ue(e){let t={},n=[],r=new Map,i=new Set,s=new Set,o=[...Array.from(e.querySelectorAll("input, textarea, select")),...ae(e)];for(let c of o){let f=c.name,m=f||le(c);if(!m)continue;if(c instanceof HTMLInputElement&&c.type==="radio"){if(i.has(m))continue;i.add(m)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){if(s.has(m))continue;s.add(m)}let d=_(c);if(!d||!me(c))continue;d.title=ce(c);let p=ue(c);p&&(d.description=p);let u=Ve(c);if(u!==void 0&&(d.default=u),c instanceof HTMLInputElement&&c.type==="radio"){d.enum=Z(e,m);let g=ee(e,m);g.length>0&&(d.oneOf=g);let b=e.querySelector(`input[type="radio"][name="${CSS.escape(m)}"]:checked`);b?.value&&(d.default=b.value)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){let g=Q(e,m);if(g.length>1){let b={type:"array",items:{type:"string",enum:g},title:d.title};d.description&&(b.description=d.description);let G=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(m)}"]:checked`)).map(we=>we.value);G.length>0&&(b.default=G),t[m]=b,c.required&&n.push(m);continue}}t[m]=d,f||r.set(m,c),c.required&&n.push(m)}let l=ze(e),a=new Set;for(let{el:c,role:f,key:m,enumValues:d,enumOneOf:p}of l){if(t[m])continue;if(f==="radio"){if(a.has(m))continue;a.add(m)}let u=te(c,f);d&&d.length>0&&(u.enum=d,p&&p.length>0&&(u.oneOf=p)),u.title=Ge(c);let g=Ke(c);g&&(u.description=g),t[m]=u,r.set(m,c),c.getAttribute("aria-required")==="true"&&n.push(m)}return{schema:{type:"object",properties:t,required:n},fieldElements:r}}function le(e){let t=e;if(t.dataset.webmcpName)return E(t.dataset.webmcpName);if(e.id)return E(e.id);let n=e.getAttribute("aria-label");return n?E(n):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?E(e.placeholder.trim()):e instanceof HTMLInputElement&&e.type!=="text"?e.type:null}function ze(e){let t=H.map(a=>`[role="${a}"]`).join(", "),n=[];for(let a of Array.from(e.querySelectorAll(t))){if(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement||a.getAttribute("aria-hidden")==="true"||a.hidden)continue;let c=a.getAttribute("role"),f=ne(a);f&&n.push({el:a,role:c,key:f})}let r=n.filter(a=>a.role==="radio"),i=n.filter(a=>a.role!=="radio"),s=new Map,o=[];for(let a of r){let c=a.el.closest('[role="radiogroup"]');c?(s.has(c)||s.set(c,[]),s.get(c).push(a.el)):o.push(a)}let l=[];for(let[a,c]of s){let f=ne(a);if(!f)continue;let m=c.map(p=>(p.getAttribute("data-value")??p.getAttribute("aria-label")??p.textContent??"").trim()).filter(Boolean),d=c.map(p=>{let u=(p.getAttribute("data-value")??p.getAttribute("aria-label")??p.textContent??"").trim(),g=(p.getAttribute("aria-label")??p.textContent??"").trim();return{const:u,title:g||u}}).filter(p=>p.const!=="");m.length>0&&l.push({el:a,role:"radio",key:f,enumValues:m,enumOneOf:d})}return[...i,...l,...o]}function ne(e){let t=e;if(t.dataset?.webmcpName)return E(t.dataset.webmcpName);if(e.id)return E(e.id);let n=e.getAttribute("aria-label");if(n)return E(n);let r=e.getAttribute("aria-labelledby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return E(i)}return null}function Ge(e){let t=e;if(t.dataset?.webmcpTitle)return t.dataset.webmcpTitle;let n=e.getAttribute("aria-label");if(n)return n.trim();let r=e.getAttribute("aria-labelledby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return i}return e.id?q(e.id):""}function Ke(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let n=e;if(n.dataset?.webmcpDescription)return n.dataset.webmcpDescription;let r=e.getAttribute("aria-description");if(r)return r;let i=e.getAttribute("aria-describedby");if(i){let o=document.getElementById(i)?.textContent?.trim();if(o)return o}let s=e.getAttribute("placeholder")??e.dataset?.placeholder;return s?s.trim():""}function ce(e){if("dataset"in e&&e.dataset.webmcpTitle)return e.dataset.webmcpTitle;let t=Ye(e);return t||(e.name?q(e.name):e.id?q(e.id):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?e.placeholder.trim():"")}function ue(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let n=e;if(n.dataset.webmcpDescription)return n.dataset.webmcpDescription;let r=e.getAttribute("aria-description");if(r)return r;let i=e.getAttribute("aria-describedby");if(i){let s=document.getElementById(i);if(s?.textContent?.trim())return s.textContent.trim()}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){let s=e.placeholder?.trim();if(s&&s.length>0)return s}return""}function Ye(e){if(e.id){let n=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(n){let r=re(n);if(r)return r}}let t=e.closest("label");if(t){let n=re(t);if(n)return n}return""}function re(e){let t=e.cloneNode(!0);return t.querySelectorAll("input, select, textarea, button").forEach(n=>n.remove()),t.textContent?.trim()??""}function q(e){return e.replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().replace(/\b\w/g,t=>t.toUpperCase())}function me(e){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||e.offsetParent===null&&t.position!=="fixed")return!1;let n=e;for(;n&&n!==document.body;){if(n.getAttribute("aria-hidden")==="true")return!1;n=n.parentElement}return!e.closest("fieldset")?.disabled}function de(e,t,n){let r=Xe(e,n),i=Qe(e),{schema:s,fieldElements:o}=Ze(t);return{name:r,description:i,inputSchema:s,fieldElements:o}}function Xe(e,t){if(t){let i=t instanceof HTMLInputElement?t.value.trim():t.textContent?.trim()??"";if(i&&i.length>0&&i.length<80)return E(i)}let n=fe(e);if(n)return E(n);let r=document.title?.trim();return r?E(r):`form_${++ie}`}function Qe(e){let t=fe(e),n=document.title?.trim();return t&&n&&t!==n?`${t} on ${n}`:t||n||"Submit form"}function fe(e){let t=e.querySelector("h1, h2, h3");if(t?.textContent?.trim())return t.textContent.trim();let n=e;for(;n;){let r=n.previousElementSibling;for(;r;){if(/^H[1-3]$/i.test(r.tagName)){let i=r.textContent?.trim()??"";if(i)return i}r=r.previousElementSibling}if(n=n.parentElement,!n||n===document.body)break}return""}function Ze(e){let t={},n=[],r=new Map,i=new Set,s=new Set;for(let o of e){let l=o.name,a=l||le(o);if(!a)continue;if(o instanceof HTMLInputElement&&o.type==="radio"){if(i.has(a))continue;i.add(a)}if(o instanceof HTMLInputElement&&o.type==="checkbox"){if(s.has(a))continue;s.add(a)}let c=_(o);if(!c||!me(o))continue;c.title=ce(o);let f=ue(o);if(f&&(c.description=f),o instanceof HTMLInputElement&&o.type==="checkbox"){let m=e.filter(d=>d instanceof HTMLInputElement&&d.type==="checkbox"&&d.name===a).map(d=>d.value).filter(d=>d!==""&&d!=="on");if(m.length>1){let d={type:"array",items:{type:"string",enum:m},title:c.title};c.description&&(d.description=c.description),t[a]=d,o.required&&n.push(a);continue}}t[a]=c,l||r.set(a,o),o.required&&n.push(a)}return{schema:{type:"object",properties:t,required:n},fieldElements:r}}A();var C=new WeakMap,Te=new WeakMap,k=new WeakMap,y=new WeakMap,L=new WeakMap,R=new WeakMap,tt=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,nt=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,M=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function ye(e,t,n,r){return r?.fieldElements&&k.set(e,r.fieldElements),ge(e,n),async i=>{L.set(e,[]),y.delete(e),W(e,i);let s=ot(r,i);return s.length>0&&y.set(e,s),window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:n}})),new Promise((o,l)=>{C.set(e,{resolve:o,reject:l}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&be(e).then(async()=>{try{W(e,i);for(let c=0;c<2&&it(e,i,k.get(e)).length!==0;c++)W(e,i),await be(e,400,100);let a=e;if(!e.isConnected){let f=document.querySelector('button[type="submit"]:not([disabled]), input[type="submit"]:not([disabled])')?.closest("form");f&&(a=f,C.set(a,{resolve:o,reject:l}),ge(a,n))}a!==e&&y.has(e)&&(y.set(a,y.get(e)),y.delete(e)),a.requestSubmit()}catch(a){l(a instanceof Error?a:new Error(String(a)))}})})}}function ge(e,t){e.__awmcp_intercepted||(e.__awmcp_intercepted=!0,e.addEventListener("submit",n=>{let r=C.get(e);if(!r)return;let{resolve:i}=r;C.delete(e);let s=rt(e,Te.get(e),k.get(e));R.delete(e);let o=y.get(e)??[];y.delete(e);let l=L.get(e)??[];L.delete(e);let a=l.filter(u=>u.type==="not_filled").map(u=>u.field),c={status:o.length>0||a.length>0?"partial":"success",filled_fields:s,skipped_fields:a,missing_required:o,warnings:[...o.map(u=>({field:u,type:"missing_required",message:`required field "${u}" was not provided`})),...l]},f=[...o.length?[`required fields were not filled: ${o.join(", ")}`]:[],...l.map(u=>u.message)],m=f.length?` Note: ${f.join("; ")}.`:"",p={content:[{type:"text",text:`Form submitted. Fields: ${JSON.stringify(s)}${m}`},{type:"text",text:JSON.stringify(c)}]};n.agentInvoked&&typeof n.respondWith=="function"&&(n.preventDefault(),n.respondWith(Promise.resolve(p))),i(p)}),e.addEventListener("reset",()=>{R.delete(e),window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:t}}))}))}function S(e,t){if(e.focus(),e.select?.(),document.execCommand("insertText",!1,t)&&e.value===t)return;let n=e instanceof HTMLTextAreaElement?nt:tt;n?n.call(e,t):e.value=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function J(e,t){M?M.call(e,t):e.checked=t,e.dispatchEvent(new Event("change",{bubbles:!0}))}function I(e,t){for(let n of Array.from(e.querySelectorAll("*"))){let r=n.shadowRoot;if(!r)continue;let i=r.querySelector(t);if(i)return i;let s=I(r,t);if(s)return s}return null}function V(e,t){let n=CSS.escape(t),r=e.querySelector(`[name="${n}"]`)??e.querySelector(`input#${n}, textarea#${n}, select#${n}`);return r||(I(document,`[name="${n}"]`)??I(document,`input#${n}, textarea#${n}, select#${n}`))}function W(e,t){Te.set(e,t);let n=k.get(e),r={};for(let[i,s]of Object.entries(t)){let o=V(e,i);if(o){if(o instanceof HTMLInputElement)if(Ee(o,e,i,s),o.type==="checkbox")if(Array.isArray(s)){let a=CSS.escape(i);r[i]=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${a}"]`)).filter(c=>c.checked).map(c=>c.value)}else r[i]=o.checked;else r[i]=o.value;else o instanceof HTMLTextAreaElement?(S(o,String(s??"")),r[i]=o.value):o instanceof HTMLSelectElement&&(j(o,s,e,i),r[i]=o.multiple?Array.from(o.options).filter(a=>a.selected).map(a=>a.value):o.value);continue}let l=n?.get(i);if(l){let a=l;if(!l.isConnected){let c=l.id;if(c){let f=document.getElementById(c)??I(document,`#${CSS.escape(c)}`);f&&(a=f)}}a instanceof HTMLInputElement?(Ee(a,e,i,s),r[i]=a.type==="checkbox"?a.checked:a.value):a instanceof HTMLTextAreaElement?(S(a,String(s??"")),r[i]=a.value):a instanceof HTMLSelectElement?(j(a,s,e,i),r[i]=a.multiple?Array.from(a.options).filter(c=>c.selected).map(c=>c.value):a.value):(he(a,s),r[i]=s)}}R.set(e,r),window.__lastFillWarnings=L.get(e)??[]}function Ee(e,t,n,r){let i=e.type.toLowerCase();if(i==="checkbox"){if(Array.isArray(r)){let s=CSS.escape(n),o=t.querySelectorAll(`input[type="checkbox"][name="${s}"]`);for(let l of o)J(l,r.map(String).includes(l.value));return}J(e,!!r);return}if(i==="number"||i==="range"){let s=String(r??""),o=Number(s);if(s===""||isNaN(o)){L.get(t)?.push({field:n,type:"type_mismatch",message:`"${n}" expects a number, got: ${JSON.stringify(r)}`,original:r});return}let l=e.min!==""?parseFloat(e.min):-1/0,a=e.max!==""?parseFloat(e.max):1/0;if(o<l||o>a){let c=Math.min(Math.max(o,l),a);L.get(t)?.push({field:n,type:"clamped",message:`"${n}" value ${o} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${c}`,original:o,actual:c}),e.value=String(c)}else e.value=String(o);e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:String(o)})),e.dispatchEvent(new Event("change",{bubbles:!0}));return}if(i==="radio"){let s=CSS.escape(n),o=t.querySelectorAll(`input[type="radio"][name="${s}"]`);for(let l of o)if(l.value===String(r)){M?M.call(l,!0):l.checked=!0,l.dispatchEvent(new Event("change",{bubbles:!0}));break}return}S(e,String(r??""))}function j(e,t,n,r){if(e.multiple){let s=Array.isArray(t)?t.map(String):[String(t??"")];for(let o of Array.from(e.options))o.selected=s.includes(o.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}let i=String(t??"");if(e.value=i,e.value!==i){let s=i.toLowerCase(),o=Array.from(e.options).find(l=>l.text.trim().toLowerCase()===s||l.label.trim().toLowerCase()===s);o?e.value=o.value:n&&r&&L.get(n)?.push({field:r,type:"not_filled",message:`"${r}" value "${i}" did not match any option in the select`,original:i})}e.dispatchEvent(new Event("change",{bubbles:!0}))}function he(e,t){let n=e.getAttribute("role");if(n==="checkbox"||n==="switch"){e.setAttribute("aria-checked",String(!!t)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(n==="radio"){e.setAttribute("aria-checked","true"),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(n==="radiogroup"){let i=Array.from(e.querySelectorAll('[role="radio"]'));for(let s of i)if((s.getAttribute("data-value")??s.getAttribute("aria-label")??s.textContent??"").trim()===String(t)){s.setAttribute("aria-checked","true"),s.dispatchEvent(new MouseEvent("click",{bubbles:!0}));for(let l of i)l!==s&&l.setAttribute("aria-checked","false");break}return}let r=e;r.isContentEditable&&(r.textContent=String(t??"")),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function rt(e,t,n){let r={},i=new FormData(e),s=R.get(e);for(let[o,l]of i.entries())if(r[o]!==void 0){let a=r[o];Array.isArray(a)?a.push(l):r[o]=[a,l]}else r[o]=l;if(t)for(let o of Object.keys(t)){if(o in r)continue;if(s&&o in s){r[o]=s[o];continue}let l=V(e,o)??n?.get(o)??null;if(l)if(l instanceof HTMLInputElement&&l.type==="checkbox")r[o]=l.checked;else if(l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)r[o]=l.value;else{let a=l.getAttribute("role");a==="checkbox"||a==="switch"?r[o]=l.getAttribute("aria-checked")==="true":r[o]=l.textContent?.trim()??""}}return r}function Le(e,t){if(e instanceof HTMLInputElement){let n=e.type.toLowerCase();n==="checkbox"?J(e,!!t):n==="radio"?e.value===String(t)&&(M?M.call(e,!0):e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):S(e,String(t??""))}else e instanceof HTMLTextAreaElement?S(e,String(t??"")):e instanceof HTMLSelectElement?j(e,t):he(e,t)}function be(e,t=800,n=150){return new Promise(r=>{let i=!1,s=null,o=()=>{i||(i=!0,l.disconnect(),s!==null&&clearTimeout(s),r())},l=new MutationObserver(()=>{s!==null&&clearTimeout(s),s=setTimeout(o,n)});l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(o,t),s=setTimeout(o,n)})}function it(e,t,n){let r=[];for(let[i,s]of Object.entries(t)){let o=V(e,i)??n?.get(i)??null;o&&(o instanceof HTMLInputElement&&o.type==="checkbox"?o.checked!==!!s&&r.push(i):(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement)&&o.value!==String(s??"")&&r.push(i))}return r}function ot(e,t){return e?.inputSchema?.required?.length?e.inputSchema.required.filter(n=>!(n in t)):[]}function Me(e,t,n){window.dispatchEvent(new CustomEvent(e,{detail:{form:t,toolName:n}}))}function st(e,t){if(e.dataset.noWebmcp!==void 0)return!0;for(let n of t.exclude)try{if(e.matches(n))return!0}catch{}return!1}async function F(e,t){if(st(e,t))return;let n;for(let[s,o]of Object.entries(t.overrides))try{if(e.matches(s)){n=o;break}}catch{}let r=oe(e,n);t.debug&&gt(r.name,r.description);let i=ye(e,t,r.name,r);await N(e,r,i),z.add(e),He++,t.debug&&console.debug(`[auto-webmcp] Registered: ${r.name}`,r),Me("form:registered",e,r.name)}async function at(e,t){let{getRegisteredToolName:n}=await Promise.resolve().then(()=>(A(),pe)),r=n(e);r&&(await x(e),z.delete(e),t.debug&&console.debug(`[auto-webmcp] Unregistered: ${r}`),Me("form:unregistered",e,r))}var w=null,z=new WeakSet,He=0,U=new Map,lt=300;function ct(e){let t=e.tagName.toLowerCase();if(t==="input"||t==="textarea"||t==="select")return!0;let n=e.getAttribute("role");if(n&&H.includes(n)||e.querySelector("input, textarea, select"))return!0;for(let r of H)if(e.querySelector(`[role="${r}"]`))return!0;return!1}function ut(e,t){let n=U.get(e);n&&clearTimeout(n),U.set(e,setTimeout(()=>{U.delete(e),F(e,t)},lt))}function mt(e){w||(w=new MutationObserver(t=>{for(let n of t){for(let r of n.addedNodes){if(!(r instanceof Element))continue;if(r instanceof HTMLFormElement){F(r,e);continue}let i=r.closest("form");i instanceof HTMLFormElement&&z.has(i)&&ct(r)&&ut(i,e);for(let s of Array.from(r.querySelectorAll("form")))F(s,e)}for(let r of n.removedNodes){if(!(r instanceof Element))continue;let i=r instanceof HTMLFormElement?[r]:Array.from(r.querySelectorAll("form"));for(let s of i)at(s,e)}}}),w.observe(document.body,{childList:!0,subtree:!0}))}function dt(e){window.addEventListener("hashchange",()=>v(e));let t={pushState:history.pushState.bind(history),replaceState:history.replaceState.bind(history)};history.pushState=function(...n){t.pushState(...n),v(e)},history.replaceState=function(...n){t.replaceState(...n),v(e)},window.addEventListener("popstate",()=>v(e))}async function v(e){let t=Array.from(document.querySelectorAll("form"));await Promise.allSettled(t.map(n=>F(n,e)))}var ft=new Set(["password","hidden","file","submit","reset","button","image"]);async function pt(e){if(!T())return;let t='[type="submit"]:not([disabled]), button:not([type]):not([disabled])',n=/subscribe|submit|sign[\s-]?up|send|join|go|search/i,r=Array.from(document.querySelectorAll("input:not(form input), textarea:not(form textarea), select:not(form select)")).filter(s=>{if(s instanceof HTMLInputElement&&ft.has(s.type.toLowerCase()))return!1;let o=s.getBoundingClientRect();return o.width>0&&o.height>0});if(r.length===0)return;let i=new Map;for(let s of r){let o=s.parentElement,l=s.parentElement??document.body;for(;o&&o!==document.body;){if(o.querySelector(t)!==null||Array.from(o.querySelectorAll("button")).some(c=>n.test(c.textContent??""))){l=o;break}o=o.parentElement}i.has(l)||i.set(l,[]),i.get(l).push(s)}for(let[s,o]of i){let l=Array.from(s.querySelectorAll(t)).filter(u=>{let g=u.getBoundingClientRect();return g.width>0&&g.height>0}),a=l[l.length-1]??null;if(!a){let u=Array.from(document.querySelectorAll("button")).filter(g=>{let b=g.getBoundingClientRect();return b.width>0&&b.height>0&&n.test(g.textContent??"")});a=u[u.length-1]??null}let c=de(s,o,a),f=[],m=c.inputSchema.properties;for(let u of o){let g=u.name||u.dataset.webmcpName||u.id||u.getAttribute("aria-label")||null,b=g?g.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64):null;b&&m[b]&&f.push({key:b,el:u})}let d=c.name,p=async u=>{for(let{key:g,el:b}of f)u[g]!==void 0&&Le(b,u[g]);return window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:d}})),{content:[{type:"text",text:"Fields filled. Ready to submit."}]}};try{await navigator.modelContext.registerTool({name:c.name,description:c.description,inputSchema:c.inputSchema,execute:p}),e.debug&&console.debug(`[auto-webmcp] Orphan tool registered: ${c.name}`,c)}catch{}}}function gt(e,t){/^form_\d+$|^submit$|^form$/.test(e)&&console.warn(`[auto-webmcp] Tool "${e}" has a generic name. Consider adding a toolname or data-webmcp-name attribute.`),(!t||t==="Submit form")&&console.warn(`[auto-webmcp] Tool "${e}" has no meaningful description.`),/don'?t|do not|never|avoid|not for/i.test(t)&&console.warn(`[auto-webmcp] Tool "${e}" description contains negative instructions. Per spec best practices, prefer positive descriptions.`)}async function xe(e){document.readyState==="loading"&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),He=0,mt(e),dt(e),await v(e),await pt(e)}function Se(){w?.disconnect(),w=null}A();async function ve(e){let t=Y(e);return t.debug&&console.debug("[auto-webmcp] Initializing",{webmcpSupported:T(),config:t}),await xe(t),{destroy:async()=>{Se(),await B()},getTools:D,isSupported:T()}}typeof window<"u"&&!window.__AUTO_WEBMCP_NO_AUTOINIT&&ve();return Fe(Et);})();
1
+ "use strict";var AutoWebMCP=(()=>{var P=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var ke=(e,t)=>()=>(e&&(t=e(e=0)),t);var K=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},Ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ce(t))!Re.call(e,i)&&i!==n&&P(e,i,{get:()=>t[i],enumerable:!(r=Ae(t,i))||r.enumerable});return e};var Fe=e=>Ie(P({},"__esModule",{value:!0}),e);var pe={};K(pe,{getAllRegisteredTools:()=>B,getRegisteredToolName:()=>et,isWebMCPSupported:()=>y,registerFormTool:()=>D,unregisterAll:()=>W,unregisterFormTool:()=>S});function y(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function D(e,t,n){if(!y())return;L.get(e)&&await S(e);let i={name:t.name,description:t.description,inputSchema:t.inputSchema,execute:n};t.annotations&&Object.keys(t.annotations).length>0&&(i.annotations=t.annotations);try{await navigator.modelContext.registerTool(i)}catch{try{await navigator.modelContext.unregisterTool(t.name),await navigator.modelContext.registerTool(i)}catch{}}L.set(e,t.name)}async function S(e){if(!y())return;let t=L.get(e);if(t){try{await navigator.modelContext.unregisterTool(t)}catch{}L.delete(e)}}function et(e){return L.get(e)}function B(){return Array.from(L.entries()).map(([e,t])=>({form:e,name:t}))}async function W(){let e=Array.from(L.entries());await Promise.all(e.map(([t])=>S(t)))}var L,C=ke(()=>{"use strict";L=new Map});var Et={};K(Et,{autoWebMCP:()=>ve});function Y(e){return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,overrides:e?.overrides??{},debug:e?.debug??!1}}var x=["textbox","combobox","checkbox","radio","switch","spinbutton","searchbox","slider"];function $(e){return e instanceof HTMLInputElement?Oe(e):e instanceof HTMLTextAreaElement?{type:"string"}:e instanceof HTMLSelectElement?_e(e):null}function Oe(e){switch(e.type.toLowerCase()){case"text":case"search":case"tel":return _(e);case"email":return{..._(e),format:"email"};case"url":return{..._(e),format:"uri"};case"number":case"range":{let n={type:"number"};return e.min!==""&&(n.minimum=parseFloat(e.min)),e.max!==""&&(n.maximum=parseFloat(e.max)),n}case"date":return{type:"string",format:"date"};case"datetime-local":return{type:"string",format:"date-time"};case"time":return{type:"string",format:"time"};case"month":return{type:"string",pattern:"^\\d{4}-\\d{2}$"};case"week":return{type:"string",pattern:"^\\d{4}-W\\d{2}$"};case"color":return{type:"string",pattern:"^#[0-9a-fA-F]{6}$"};case"checkbox":return{type:"boolean"};case"radio":return{type:"string"};case"file":case"hidden":case"submit":case"reset":case"button":case"image":return null;case"password":return null;default:return{type:"string"}}}function _(e){let t={type:"string"};e.minLength>0&&(t.minLength=e.minLength),e.maxLength>0&&e.maxLength!==524288&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern);let n=e.getAttribute("list");if(n){let r=e.ownerDocument.getElementById(n);if(r instanceof HTMLDataListElement){let i=Array.from(r.options).filter(s=>!s.disabled&&s.value.trim()!=="");i.length>0&&(t.enum=i.map(s=>s.value.trim()),t.oneOf=i.map(s=>({const:s.value.trim(),title:s.textContent?.trim()||s.value.trim()})))}}return t}var Pe=/^(select|choose|pick)\b|^--+|---/i;function X(e){return e.disabled?!0:e.value!==""?!1:Pe.test(e.text.trim())}function _e(e){let t=[],n=[];for(let r of Array.from(e.children))if(r instanceof HTMLOptGroupElement){if(r.disabled)continue;let i=r.label?.trim()??"";for(let s of Array.from(r.children)){if(!(s instanceof HTMLOptionElement)||X(s))continue;t.push(s.value);let o={const:s.value,title:s.text.trim()||s.value};i&&(o.group=i),n.push(o)}}else if(r instanceof HTMLOptionElement){if(X(r))continue;t.push(r.value),n.push({const:r.value,title:r.text.trim()||r.value})}return t.length===0?{type:"string"}:e.multiple?{type:"array",items:{type:"string",enum:t}}:{type:"string",enum:t,oneOf:n}}function Q(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!==""&&n!=="on")}function Z(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(r=>r.value).filter(r=>r!=="")}function ee(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).filter(r=>r.value!=="").map(r=>{let i=$e(r);return{const:r.value,title:i||r.value}})}function te(e,t){switch(t){case"checkbox":case"switch":return{type:"boolean"};case"spinbutton":case"slider":{let n={type:"number"},r=e.getAttribute("aria-valuemin"),i=e.getAttribute("aria-valuemax");return r!==null&&(n.minimum=parseFloat(r)),i!==null&&(n.maximum=parseFloat(i)),n}case"combobox":{let n=e.getAttribute("aria-owns")??e.getAttribute("aria-controls");if(n){let r=document.getElementById(n);if(r){let i=Array.from(r.querySelectorAll('[role="option"]')).filter(s=>s.getAttribute("aria-disabled")!=="true");if(i.length>0){let s=i.map(l=>(l.getAttribute("data-value")??l.textContent??"").trim()).filter(Boolean),o=i.map(l=>({const:(l.getAttribute("data-value")??l.textContent??"").trim(),title:(l.textContent??"").trim()}));return{type:"string",enum:s,oneOf:o}}}}return{type:"string"}}case"textbox":case"searchbox":case"radio":default:return{type:"string"}}}function $e(e){let t=e.closest("label");if(t){let n=t.cloneNode(!0);n.querySelectorAll("input, select, textarea, button").forEach(i=>i.remove());let r=n.textContent?.trim()??"";if(r)return r}if(e.id){let n=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(n){let r=n.textContent?.trim()??"";if(r)return r}}return""}var ie=0;function oe(e,t){let n=t?.name??qe(e),r=t?.description??De(e),{schema:i,fieldElements:s}=Ve(e),o=je(e);return{name:n,description:r,inputSchema:i,annotations:o,fieldElements:s}}function qe(e){let t=e.getAttribute("toolname");if(t)return b(t);let n=e.dataset.webmcpName;if(n)return b(n);let r=q(e);if(r)return b(r);let i=se(e);if(i)return b(i);if(e.id)return b(e.id);if(e.name)return b(e.name);if(e.action){let s=Ne(e.action);if(s)return b(s)}return`form_${++ie}`}function b(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"form"}function q(e){let t=[...Array.from(e.querySelectorAll('button[type="submit"], button:not([type])')),...Array.from(e.querySelectorAll('input[type="submit"]'))];for(let n of t){let r=n instanceof HTMLInputElement?n.value.trim():n.textContent?.trim()??"";if(r&&r.length>0&&r.length<80)return r}return""}function se(e){let t=e;for(;t;){let n=t.previousElementSibling;for(;n;){if(/^H[1-3]$/i.test(n.tagName)){let r=n.textContent?.trim()??"";if(r)return r}n=n.previousElementSibling}if(t=t.parentElement,!t||t===document.body)break}return""}function Ne(e){try{let n=new URL(e,window.location.href).pathname.split("/").filter(Boolean);return n[n.length-1]??""}catch{return""}}function De(e){let t=e.getAttribute("tooldescription");if(t)return t.trim();let n=e.dataset.webmcpDescription;if(n)return n.trim();let r=e.querySelector("legend");if(r?.textContent?.trim())return r.textContent.trim();let i=e.getAttribute("aria-label");if(i?.trim())return i.trim();let s=e.getAttribute("aria-describedby");if(s){let a=document.getElementById(s);if(a?.textContent?.trim())return a.textContent.trim()}let o=se(e),l=document.title?.trim();return o&&l?`${o}: ${l}`:o||l||"Submit form"}var Be=/^(search|find|look|filter|browse|view|show|check|preview|get|fetch|retrieve|load)\b/i,We=/^(delete|remove|cancel|terminate|destroy|purge|revoke|unsubscribe|deactivate)\b/i,Je=/\/(delete|remove|cancel|destroy)\b/i;function je(e){let t={};if(e.dataset.webmcpReadonly!==void 0&&(t.readOnlyHint=e.dataset.webmcpReadonly!=="false"),e.dataset.webmcpDestructive!==void 0&&(t.destructiveHint=e.dataset.webmcpDestructive!=="false"),e.dataset.webmcpIdempotent!==void 0&&(t.idempotentHint=e.dataset.webmcpIdempotent!=="false"),e.dataset.webmcpOpenworld!==void 0&&(t.openWorldHint=e.dataset.webmcpOpenworld!=="false"),t.readOnlyHint===void 0){let r=e.method.toLowerCase()==="get",i=q(e),s=i?Be.test(i.trim()):!1;(r||s)&&(t.readOnlyHint=!0)}if(t.destructiveHint===void 0){let r=q(e),i=r?We.test(r.trim()):!1,s=e.action?Je.test(e.action):!1;(i||s)&&(t.destructiveHint=!0)}return t.idempotentHint===void 0&&(t.readOnlyHint===!0||e.method.toLowerCase()==="get")&&(t.idempotentHint=!0),t.openWorldHint===void 0&&(t.openWorldHint=t.readOnlyHint!==!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function Ue(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"?e.checked?!0:void 0:t==="radio"?void 0:t==="number"||t==="range"?e.value!==""?parseFloat(e.value):void 0:e.value!==""?e.value:void 0}if(e instanceof HTMLTextAreaElement)return e.value!==""?e.value:void 0;if(e instanceof HTMLSelectElement){if(e.multiple){let t=Array.from(e.options).filter(n=>n.selected).map(n=>n.value);return t.length>0?t:void 0}return e.value!==""?e.value:void 0}}function ae(e,t=new Set){if(t.has(e))return[];t.add(e);let n=[];for(let r of Array.from(e.querySelectorAll("*")))r.shadowRoot&&n.push(...Array.from(r.shadowRoot.querySelectorAll("input, textarea, select")),...ae(r.shadowRoot,t));return n}function Ve(e){let t={},n=[],r=new Map,i=new Set,s=new Set,o=[...Array.from(e.querySelectorAll("input, textarea, select")),...ae(e)];for(let c of o){let u=c.name,m=u||le(c);if(!m)continue;if(c instanceof HTMLInputElement&&c.type==="radio"){if(i.has(m))continue;i.add(m)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){if(s.has(m))continue;s.add(m)}let d=$(c);if(!d||!me(c))continue;d.title=ce(c);let p=ue(c);p&&(d.description=p);let g=Ue(c);if(g!==void 0&&(d.default=g),c instanceof HTMLInputElement&&c.type==="radio"){d.enum=Z(e,m);let f=ee(e,m);f.length>0&&(d.oneOf=f);let E=e.querySelector(`input[type="radio"][name="${CSS.escape(m)}"]:checked`);E?.value&&(d.default=E.value)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){let f=Q(e,m);if(f.length>1){let E={type:"array",items:{type:"string",enum:f},title:d.title};d.description&&(E.description=d.description);let T=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(m)}"]:checked`)).map(we=>we.value);T.length>0&&(E.default=T),t[m]=E,c.required&&n.push(m);continue}}t[m]=d,u||r.set(m,c),c.required&&n.push(m)}let l=ze(e),a=new Set;for(let{el:c,role:u,key:m,enumValues:d,enumOneOf:p}of l){if(t[m])continue;if(u==="radio"){if(a.has(m))continue;a.add(m)}let g=te(c,u);d&&d.length>0&&(g.enum=d,p&&p.length>0&&(g.oneOf=p)),g.title=Ge(c);let f=Ke(c);f&&(g.description=f),t[m]=g,r.set(m,c),c.getAttribute("aria-required")==="true"&&n.push(m)}return{schema:{type:"object",properties:t,required:n},fieldElements:r}}function le(e){let t=e;if(t.dataset.webmcpName)return b(t.dataset.webmcpName);if(e.id)return b(e.id);let n=e.getAttribute("aria-label");return n?b(n):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?b(e.placeholder.trim()):e instanceof HTMLInputElement&&e.type!=="text"?e.type:null}function ze(e){let t=x.map(a=>`[role="${a}"]`).join(", "),n=[];for(let a of Array.from(e.querySelectorAll(t))){if(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement||a.getAttribute("aria-hidden")==="true"||a.hidden)continue;let c=a.getAttribute("role"),u=ne(a);u&&n.push({el:a,role:c,key:u})}let r=n.filter(a=>a.role==="radio"),i=n.filter(a=>a.role!=="radio"),s=new Map,o=[];for(let a of r){let c=a.el.closest('[role="radiogroup"]');c?(s.has(c)||s.set(c,[]),s.get(c).push(a.el)):o.push(a)}let l=[];for(let[a,c]of s){let u=ne(a);if(!u)continue;let m=c.map(p=>(p.getAttribute("data-value")??p.getAttribute("aria-label")??p.textContent??"").trim()).filter(Boolean),d=c.map(p=>{let g=(p.getAttribute("data-value")??p.getAttribute("aria-label")??p.textContent??"").trim(),f=(p.getAttribute("aria-label")??p.textContent??"").trim();return{const:g,title:f||g}}).filter(p=>p.const!=="");m.length>0&&l.push({el:a,role:"radio",key:u,enumValues:m,enumOneOf:d})}return[...i,...l,...o]}function ne(e){let t=e;if(t.dataset?.webmcpName)return b(t.dataset.webmcpName);if(e.id)return b(e.id);let n=e.getAttribute("aria-label");if(n)return b(n);let r=e.getAttribute("aria-labelledby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return b(i)}return null}function Ge(e){let t=e;if(t.dataset?.webmcpTitle)return t.dataset.webmcpTitle;let n=e.getAttribute("aria-label");if(n)return n.trim();let r=e.getAttribute("aria-labelledby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return i}return e.id?N(e.id):""}function Ke(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let n=e;if(n.dataset?.webmcpDescription)return n.dataset.webmcpDescription;let r=e.getAttribute("aria-description");if(r)return r;let i=e.getAttribute("aria-describedby");if(i){let o=document.getElementById(i)?.textContent?.trim();if(o)return o}let s=e.getAttribute("placeholder")??e.dataset?.placeholder;return s?s.trim():""}function ce(e){if("dataset"in e&&e.dataset.webmcpTitle)return e.dataset.webmcpTitle;let t=Ye(e);return t||(e.name?N(e.name):e.id?N(e.id):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?e.placeholder.trim():"")}function ue(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let n=e;if(n.dataset.webmcpDescription)return n.dataset.webmcpDescription;let r=e.getAttribute("aria-description");if(r)return r;let i=e.getAttribute("aria-describedby");if(i){let s=document.getElementById(i);if(s?.textContent?.trim())return s.textContent.trim()}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){let s=e.placeholder?.trim();if(s&&s.length>0)return s}return""}function Ye(e){if(e.id){let n=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(n){let r=re(n);if(r)return r}}let t=e.closest("label");if(t){let n=re(t);if(n)return n}return""}function re(e){let t=e.cloneNode(!0);return t.querySelectorAll("input, select, textarea, button").forEach(n=>n.remove()),t.textContent?.trim()??""}function N(e){return e.replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().replace(/\b\w/g,t=>t.toUpperCase())}function me(e){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||e.offsetParent===null&&t.position!=="fixed")return!1;let n=e;for(;n&&n!==document.body;){if(n.getAttribute("aria-hidden")==="true")return!1;n=n.parentElement}return!e.closest("fieldset")?.disabled}function de(e,t,n){let r=Xe(e,n),i=Qe(e),{schema:s,fieldElements:o}=Ze(t);return{name:r,description:i,inputSchema:s,fieldElements:o}}function Xe(e,t){if(t){let i=t instanceof HTMLInputElement?t.value.trim():t.textContent?.trim()??"";if(i&&i.length>0&&i.length<80)return b(i)}let n=fe(e);if(n)return b(n);let r=document.title?.trim();return r?b(r):`form_${++ie}`}function Qe(e){let t=fe(e),n=document.title?.trim();return t&&n&&t!==n?`${t} on ${n}`:t||n||"Submit form"}function fe(e){let t=e.querySelector("h1, h2, h3");if(t?.textContent?.trim())return t.textContent.trim();let n=e;for(;n;){let r=n.previousElementSibling;for(;r;){if(/^H[1-3]$/i.test(r.tagName)){let i=r.textContent?.trim()??"";if(i)return i}r=r.previousElementSibling}if(n=n.parentElement,!n||n===document.body)break}return""}function Ze(e){let t={},n=[],r=new Map,i=new Set,s=new Set;for(let o of e){let l=o.name,a=l||le(o);if(!a)continue;if(o instanceof HTMLInputElement&&o.type==="radio"){if(i.has(a))continue;i.add(a)}if(o instanceof HTMLInputElement&&o.type==="checkbox"){if(s.has(a))continue;s.add(a)}let c=$(o);if(!c||!me(o))continue;c.title=ce(o);let u=ue(o);if(u&&(c.description=u),o instanceof HTMLInputElement&&o.type==="checkbox"){let m=e.filter(d=>d instanceof HTMLInputElement&&d.type==="checkbox"&&d.name===a).map(d=>d.value).filter(d=>d!==""&&d!=="on");if(m.length>1){let d={type:"array",items:{type:"string",enum:m},title:c.title};c.description&&(d.description=c.description),t[a]=d,o.required&&n.push(a);continue}}t[a]=c,l||r.set(a,o),o.required&&n.push(a)}return{schema:{type:"object",properties:t,required:n},fieldElements:r}}C();var R=new WeakMap,Te=new WeakMap,k=new WeakMap,h=new WeakMap,M=new WeakMap,I=new WeakMap,tt=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,nt=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,H=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function ye(e,t,n,r){return r?.fieldElements&&k.set(e,r.fieldElements),ge(e,n),async i=>{M.set(e,[]),h.delete(e),J(e,i);let s=ot(r,i);return s.length>0&&h.set(e,s),window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:n}})),new Promise((o,l)=>{R.set(e,{resolve:o,reject:l}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&be(e).then(async()=>{try{J(e,i);for(let c=0;c<2&&it(e,i,k.get(e)).length!==0;c++)J(e,i),await be(e,400,100);let a=e;if(!e.isConnected){let u=document.querySelector('button[type="submit"]:not([disabled]), input[type="submit"]:not([disabled])')?.closest("form");u&&(a=u,R.set(a,{resolve:o,reject:l}),ge(a,n))}a!==e&&h.has(e)&&(h.set(a,h.get(e)),h.delete(e)),a.requestSubmit()}catch(a){l(a instanceof Error?a:new Error(String(a)))}})})}}function ge(e,t){e.__awmcp_intercepted||(e.__awmcp_intercepted=!0,e.addEventListener("submit",n=>{let r=R.get(e);if(!r)return;let{resolve:i}=r;R.delete(e);let s=rt(e,Te.get(e),k.get(e));I.delete(e);let o=h.get(e)??[];h.delete(e);let l=M.get(e)??[];M.delete(e);let a=l.filter(g=>g.type==="not_filled").map(g=>g.field),c={status:o.length>0||a.length>0?"partial":"success",filled_fields:s,skipped_fields:a,missing_required:o,warnings:[...o.map(g=>({field:g,type:"missing_required",message:`required field "${g}" was not provided`})),...l]},u=[...o.length?[`required fields were not filled: ${o.join(", ")}`]:[],...l.map(g=>g.message)],m=u.length?` Note: ${u.join("; ")}.`:"",p={content:[{type:"text",text:`Form submitted. Fields: ${JSON.stringify(s)}${m}`},{type:"text",text:JSON.stringify(c)}]};n.agentInvoked&&typeof n.respondWith=="function"&&(n.preventDefault(),n.respondWith(Promise.resolve(p))),i(p)}),e.addEventListener("reset",()=>{I.delete(e),window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:t}}))}))}function v(e,t){if(e.focus(),e.select?.(),document.execCommand("insertText",!1,t)&&e.value===t)return;let n=e instanceof HTMLTextAreaElement?nt:tt;n?n.call(e,t):e.value=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function j(e,t){H?H.call(e,t):e.checked=t,e.dispatchEvent(new Event("change",{bubbles:!0}))}function F(e,t){for(let n of Array.from(e.querySelectorAll("*"))){let r=n.shadowRoot;if(!r)continue;let i=r.querySelector(t);if(i)return i;let s=F(r,t);if(s)return s}return null}function V(e,t){let n=CSS.escape(t),r=e.querySelector(`[name="${n}"]`)??e.querySelector(`input#${n}, textarea#${n}, select#${n}`);return r||(F(document,`[name="${n}"]`)??F(document,`input#${n}, textarea#${n}, select#${n}`))}function J(e,t){Te.set(e,t);let n=k.get(e),r={};for(let[i,s]of Object.entries(t)){let o=V(e,i);if(o){if(o instanceof HTMLInputElement)if(Ee(o,e,i,s),o.type==="checkbox")if(Array.isArray(s)){let a=CSS.escape(i);r[i]=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${a}"]`)).filter(c=>c.checked).map(c=>c.value)}else r[i]=o.checked;else r[i]=o.value;else o instanceof HTMLTextAreaElement?(v(o,String(s??"")),r[i]=o.value):o instanceof HTMLSelectElement&&(U(o,s,e,i),r[i]=o.multiple?Array.from(o.options).filter(a=>a.selected).map(a=>a.value):o.value);continue}let l=n?.get(i);if(l){let a=l;if(!l.isConnected){let c=l.id;if(c){let u=document.getElementById(c)??F(document,`#${CSS.escape(c)}`);u&&(a=u)}}a instanceof HTMLInputElement?(Ee(a,e,i,s),r[i]=a.type==="checkbox"?a.checked:a.value):a instanceof HTMLTextAreaElement?(v(a,String(s??"")),r[i]=a.value):a instanceof HTMLSelectElement?(U(a,s,e,i),r[i]=a.multiple?Array.from(a.options).filter(c=>c.selected).map(c=>c.value):a.value):(he(a,s),r[i]=s)}}I.set(e,r),window.__lastFillWarnings=M.get(e)??[]}function Ee(e,t,n,r){let i=e.type.toLowerCase();if(i==="checkbox"){if(Array.isArray(r)){let s=CSS.escape(n),o=t.querySelectorAll(`input[type="checkbox"][name="${s}"]`);for(let l of o)j(l,r.map(String).includes(l.value));return}j(e,!!r);return}if(i==="number"||i==="range"){let s=String(r??""),o=Number(s);if(s===""||isNaN(o)){M.get(t)?.push({field:n,type:"type_mismatch",message:`"${n}" expects a number, got: ${JSON.stringify(r)}`,original:r});return}let l=e.min!==""?parseFloat(e.min):-1/0,a=e.max!==""?parseFloat(e.max):1/0;if(o<l||o>a){let c=Math.min(Math.max(o,l),a);M.get(t)?.push({field:n,type:"clamped",message:`"${n}" value ${o} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${c}`,original:o,actual:c}),e.value=String(c)}else e.value=String(o);e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:String(o)})),e.dispatchEvent(new Event("change",{bubbles:!0}));return}if(i==="radio"){let s=CSS.escape(n),o=t.querySelectorAll(`input[type="radio"][name="${s}"]`);for(let l of o)if(l.value===String(r)){H?H.call(l,!0):l.checked=!0,l.dispatchEvent(new Event("change",{bubbles:!0}));break}return}v(e,String(r??""))}function U(e,t,n,r){if(e.multiple){let s=Array.isArray(t)?t.map(String):[String(t??"")];for(let o of Array.from(e.options))o.selected=s.includes(o.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}let i=String(t??"");if(e.value=i,e.value!==i){let s=i.toLowerCase(),o=Array.from(e.options).find(l=>l.text.trim().toLowerCase()===s||l.label.trim().toLowerCase()===s);o?e.value=o.value:n&&r&&M.get(n)?.push({field:r,type:"not_filled",message:`"${r}" value "${i}" did not match any option in the select`,original:i})}e.dispatchEvent(new Event("change",{bubbles:!0}))}function he(e,t){let n=e.getAttribute("role");if(n==="checkbox"||n==="switch"){e.setAttribute("aria-checked",String(!!t)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(n==="radio"){e.setAttribute("aria-checked","true"),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(n==="radiogroup"){let i=Array.from(e.querySelectorAll('[role="radio"]'));for(let s of i)if((s.getAttribute("data-value")??s.getAttribute("aria-label")??s.textContent??"").trim()===String(t)){s.setAttribute("aria-checked","true"),s.dispatchEvent(new MouseEvent("click",{bubbles:!0}));for(let l of i)l!==s&&l.setAttribute("aria-checked","false");break}return}let r=e;r.isContentEditable&&(r.textContent=String(t??"")),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function rt(e,t,n){let r={},i=new FormData(e),s=I.get(e);for(let[o,l]of i.entries())if(r[o]!==void 0){let a=r[o];Array.isArray(a)?a.push(l):r[o]=[a,l]}else r[o]=l;if(t)for(let o of Object.keys(t)){if(o in r)continue;if(s&&o in s){r[o]=s[o];continue}let l=V(e,o)??n?.get(o)??null;if(l)if(l instanceof HTMLInputElement&&l.type==="checkbox")r[o]=l.checked;else if(l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)r[o]=l.value;else{let a=l.getAttribute("role");a==="checkbox"||a==="switch"?r[o]=l.getAttribute("aria-checked")==="true":r[o]=l.textContent?.trim()??""}}return r}function Le(e,t){if(e instanceof HTMLInputElement){let n=e.type.toLowerCase();n==="checkbox"?j(e,!!t):n==="radio"?e.value===String(t)&&(H?H.call(e,!0):e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):v(e,String(t??""))}else e instanceof HTMLTextAreaElement?v(e,String(t??"")):e instanceof HTMLSelectElement?U(e,t):he(e,t)}function be(e,t=800,n=150){return new Promise(r=>{let i=!1,s=null,o=()=>{i||(i=!0,l.disconnect(),s!==null&&clearTimeout(s),r())},l=new MutationObserver(()=>{s!==null&&clearTimeout(s),s=setTimeout(o,n)});l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(o,t),s=setTimeout(o,n)})}function it(e,t,n){let r=[];for(let[i,s]of Object.entries(t)){let o=V(e,i)??n?.get(i)??null;o&&(o instanceof HTMLInputElement&&o.type==="checkbox"?o.checked!==!!s&&r.push(i):(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement)&&o.value!==String(s??"")&&r.push(i))}return r}function ot(e,t){return e?.inputSchema?.required?.length?e.inputSchema.required.filter(n=>!(n in t)):[]}function Me(e,t,n){window.dispatchEvent(new CustomEvent(e,{detail:{form:t,toolName:n}}))}function st(e,t){if(e.dataset.noWebmcp!==void 0)return!0;for(let n of t.exclude)try{if(e.matches(n))return!0}catch{}return!1}async function O(e,t){if(st(e,t))return;let n;for(let[s,o]of Object.entries(t.overrides))try{if(e.matches(s)){n=o;break}}catch{}let r=oe(e,n);t.debug&&gt(r.name,r.description);let i=ye(e,t,r.name,r);await D(e,r,i),G.add(e),He++,t.debug&&console.debug(`[auto-webmcp] Registered: ${r.name}`,r),Me("form:registered",e,r.name)}async function at(e,t){let{getRegisteredToolName:n}=await Promise.resolve().then(()=>(C(),pe)),r=n(e);r&&(await S(e),G.delete(e),t.debug&&console.debug(`[auto-webmcp] Unregistered: ${r}`),Me("form:unregistered",e,r))}var A=null,G=new WeakSet,He=0,z=new Map,lt=300;function ct(e){let t=e.tagName.toLowerCase();if(t==="input"||t==="textarea"||t==="select")return!0;let n=e.getAttribute("role");if(n&&x.includes(n)||e.querySelector("input, textarea, select"))return!0;for(let r of x)if(e.querySelector(`[role="${r}"]`))return!0;return!1}function ut(e,t){let n=z.get(e);n&&clearTimeout(n),z.set(e,setTimeout(()=>{z.delete(e),O(e,t)},lt))}function mt(e){A||(A=new MutationObserver(t=>{for(let n of t){for(let r of n.addedNodes){if(!(r instanceof Element))continue;if(r instanceof HTMLFormElement){O(r,e);continue}let i=r.closest("form");i instanceof HTMLFormElement&&G.has(i)&&ct(r)&&ut(i,e);for(let s of Array.from(r.querySelectorAll("form")))O(s,e)}for(let r of n.removedNodes){if(!(r instanceof Element))continue;let i=r instanceof HTMLFormElement?[r]:Array.from(r.querySelectorAll("form"));for(let s of i)at(s,e)}}}),A.observe(document.body,{childList:!0,subtree:!0}))}function dt(e){window.addEventListener("hashchange",()=>w(e));let t={pushState:history.pushState.bind(history),replaceState:history.replaceState.bind(history)};history.pushState=function(...n){t.pushState(...n),w(e)},history.replaceState=function(...n){t.replaceState(...n),w(e)},window.addEventListener("popstate",()=>w(e))}async function w(e){let t=Array.from(document.querySelectorAll("form"));await Promise.allSettled(t.map(n=>O(n,e)))}var ft=new Set(["password","hidden","file","submit","reset","button","image"]);async function pt(e){if(!y())return;let t='[type="submit"]:not([disabled]), button:not([type]):not([disabled])',n='[type="submit"], button:not([type])',r=/subscribe|submit|sign[\s-]?up|send|join|go|search/i,i=Array.from(document.querySelectorAll("input:not(form input), textarea:not(form textarea), select:not(form select)")).filter(o=>{if(o instanceof HTMLInputElement&&ft.has(o.type.toLowerCase()))return!1;let l=o.getBoundingClientRect();return l.width>0&&l.height>0});if(i.length===0)return;let s=new Map;for(let o of i){let l=o.parentElement,a=o.parentElement??document.body;for(;l&&l!==document.body;){if(l.querySelector(n)!==null||Array.from(l.querySelectorAll("button")).some(u=>r.test(u.textContent??""))){a=l;break}l=l.parentElement}s.has(a)||s.set(a,[]),s.get(a).push(o)}for(let[o,l]of s){let a=Array.from(o.querySelectorAll(t)).filter(f=>{let E=f.getBoundingClientRect();return E.width>0&&E.height>0}),c=a[a.length-1]??null;if(!c){let f=Array.from(document.querySelectorAll("button")).filter(E=>{let T=E.getBoundingClientRect();return T.width>0&&T.height>0&&r.test(E.textContent??"")});c=f[f.length-1]??null}let u=de(o,l,c),m=[],d=u.inputSchema.properties;for(let f of l){let E=f.name||f.dataset.webmcpName||f.id||f.getAttribute("aria-label")||null,T=E?E.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64):null;T&&d[T]&&m.push({key:T,el:f})}let p=u.name,g=async f=>{for(let{key:E,el:T}of m)f[E]!==void 0&&Le(T,f[E]);return window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:p}})),{content:[{type:"text",text:"Fields filled. Ready to submit."}]}};try{await navigator.modelContext.registerTool({name:u.name,description:u.description,inputSchema:u.inputSchema,execute:g}),e.debug&&console.debug(`[auto-webmcp] Orphan tool registered: ${u.name}`,u)}catch{}}}function gt(e,t){/^form_\d+$|^submit$|^form$/.test(e)&&console.warn(`[auto-webmcp] Tool "${e}" has a generic name. Consider adding a toolname or data-webmcp-name attribute.`),(!t||t==="Submit form")&&console.warn(`[auto-webmcp] Tool "${e}" has no meaningful description.`),/don'?t|do not|never|avoid|not for/i.test(t)&&console.warn(`[auto-webmcp] Tool "${e}" description contains negative instructions. Per spec best practices, prefer positive descriptions.`)}async function xe(e){document.readyState==="loading"&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),He=0,mt(e),dt(e),await w(e),await pt(e)}function Se(){A?.disconnect(),A=null}C();async function ve(e){let t=Y(e);return t.debug&&console.debug("[auto-webmcp] Initializing",{webmcpSupported:y(),config:t}),await xe(t),{destroy:async()=>{Se(),await W()},getTools:B,isSupported:y()}}typeof window<"u"&&!window.__AUTO_WEBMCP_NO_AUTOINIT&&ve();return Fe(Et);})();
2
2
  //# sourceMappingURL=auto-webmcp.iife.js.map