auto-webmcp 0.3.14 → 0.3.15
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/dist/analyzer.d.ts.map +1 -1
- package/dist/auto-webmcp.cjs.js +186 -24
- package/dist/auto-webmcp.cjs.js.map +2 -2
- package/dist/auto-webmcp.esm.js +186 -24
- package/dist/auto-webmcp.esm.js.map +2 -2
- package/dist/auto-webmcp.iife.js +1 -1
- package/dist/auto-webmcp.iife.js.map +3 -3
- package/dist/discovery.d.ts.map +1 -1
- package/dist/interceptor.d.ts +10 -0
- package/dist/interceptor.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/auto-webmcp.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var AutoWebMCP=(()=>{var q=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var Ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ne=(e,t)=>{for(var n in t)q(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of _e(t))!Be.call(e,r)&&r!==n&&q(e,r,{get:()=>t[r],enumerable:!(o=Pe(t,r))||o.enumerable});return e};var De=e=>qe(q({},"__esModule",{value:!0}),e);var Me={};ne(Me,{getAllRegisteredTools:()=>V,getRegisteredToolName:()=>lt,isWebMCPSupported:()=>M,registerFormTool:()=>z,unregisterAll:()=>G,unregisterFormTool:()=>k});function M(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function z(e,t,n){if(!M())return;w.get(e)&&await k(e);let r={name:t.name,description:t.description,inputSchema:t.inputSchema,execute:n};t.annotations&&Object.keys(t.annotations).length>0&&(r.annotations=t.annotations);try{await navigator.modelContext.registerTool(r)}catch{try{await navigator.modelContext.unregisterTool(t.name),await navigator.modelContext.registerTool(r)}catch{}}w.set(e,t.name)}async function k(e){if(!M())return;let t=w.get(e);if(t){try{await navigator.modelContext.unregisterTool(t)}catch{}w.delete(e)}}function lt(e){return w.get(e)}function V(){return Array.from(w.entries()).map(([e,t])=>({form:e,name:t}))}async function G(){let e=Array.from(w.entries());await Promise.all(e.map(([t])=>k(t)))}var w,$=Ne(()=>{"use strict";w=new Map});var Ht={};ne(Ht,{autoWebMCP:()=>Oe});function oe(e){return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,overrides:e?.overrides??{},debug:e?.debug??!1}}var C=["textbox","combobox","checkbox","radio","switch","spinbutton","searchbox","slider"];function W(e){return e instanceof HTMLInputElement?We(e):e instanceof HTMLTextAreaElement?{type:"string"}:e instanceof HTMLSelectElement?je(e):null}function We(e){switch(e.type.toLowerCase()){case"text":case"search":case"tel":return D(e);case"email":return{...D(e),format:"email"};case"url":return{...D(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 D(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 o=e.ownerDocument.getElementById(n);if(o instanceof HTMLDataListElement){let r=Array.from(o.options).filter(s=>!s.disabled&&s.value.trim()!=="");r.length>0&&(t.enum=r.map(s=>s.value.trim()),t.oneOf=r.map(s=>({const:s.value.trim(),title:s.textContent?.trim()||s.value.trim()})))}}return t}var Je=/^(select|choose|pick)\b|^--+|---/i;function ie(e){return e.disabled?!0:e.value!==""?!1:Je.test(e.text.trim())}function je(e){let t=[],n=[];for(let o of Array.from(e.children))if(o instanceof HTMLOptGroupElement){if(o.disabled)continue;let r=o.label?.trim()??"";for(let s of Array.from(o.children)){if(!(s instanceof HTMLOptionElement)||ie(s))continue;t.push(s.value);let i={const:s.value,title:s.text.trim()||s.value};r&&(i.group=r),n.push(i)}}else if(o instanceof HTMLOptionElement){if(ie(o))continue;t.push(o.value),n.push({const:o.value,title:o.text.trim()||o.value})}return t.length===0?{type:"string"}:e.multiple?{type:"array",items:{type:"string",enum:t}}:{type:"string",enum:t,oneOf:n}}function re(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!==""&&n!=="on")}function se(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(o=>o.value).filter(o=>o!=="")}function ae(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).filter(o=>o.value!=="").map(o=>{let r=Ue(o);return{const:o.value,title:r||o.value}})}function le(e,t){switch(t){case"checkbox":case"switch":return{type:"boolean"};case"spinbutton":case"slider":{let n={type:"number"},o=e.getAttribute("aria-valuemin"),r=e.getAttribute("aria-valuemax");return o!==null&&(n.minimum=parseFloat(o)),r!==null&&(n.maximum=parseFloat(r)),n}case"combobox":{let n=e.getAttribute("aria-owns")??e.getAttribute("aria-controls");if(n){let o=document.getElementById(n);if(o){let r=Array.from(o.querySelectorAll('[role="option"]')).filter(s=>s.getAttribute("aria-disabled")!=="true");if(r.length>0){let s=r.map(l=>(l.getAttribute("data-value")??l.textContent??"").trim()).filter(Boolean),i=r.map(l=>({const:(l.getAttribute("data-value")??l.textContent??"").trim(),title:(l.textContent??"").trim()}));return{type:"string",enum:s,oneOf:i}}}}return{type:"string"}}case"textbox":case"searchbox":case"radio":default:return{type:"string"}}}function Ue(e){let t=e.closest("label");if(t){let n=t.cloneNode(!0);n.querySelectorAll("input, select, textarea, button").forEach(r=>r.remove());let o=n.textContent?.trim()??"";if(o)return o}if(e.id){let n=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(n){let o=n.textContent?.trim()??"";if(o)return o}}return""}var me=0;function de(e,t){let n=t?.name??ze(e),o=t?.description??Ge(e),{schema:r,fieldElements:s}=Qe(e),i=Ye(e);return{name:n,description:o,inputSchema:r,annotations:i,fieldElements:s}}function ze(e){let t=e.getAttribute("toolname");if(t)return E(t);let n=e.dataset.webmcpName;if(n)return E(n);let o=J(e);if(o)return E(o);let r=pe(e);if(r)return E(r);if(e.id)return E(e.id);if(e.name)return E(e.name);if(e.action){let s=Ve(e.action);if(s)return E(s)}return`form_${++me}`}function E(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"form"}function J(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 o=n instanceof HTMLInputElement?n.value.trim():n.textContent?.trim()??"";if(o&&o.length>0&&o.length<80)return o}return""}function pe(e){let t=e;for(;t;){let n=t.previousElementSibling;for(;n;){if(/^H[1-3]$/i.test(n.tagName)){let o=n.textContent?.trim()??"";if(o)return o}n=n.previousElementSibling}if(t=t.parentElement,!t||t===document.body)break}return""}function Ve(e){try{let n=new URL(e,window.location.href).pathname.split("/").filter(Boolean);return n[n.length-1]??""}catch{return""}}function Ge(e){let t=e.getAttribute("tooldescription");if(t)return t.trim();let n=e.dataset.webmcpDescription;if(n)return n.trim();let o=e.querySelector("legend");if(o?.textContent?.trim())return o.textContent.trim();let r=e.getAttribute("aria-label");if(r?.trim())return r.trim();let s=e.getAttribute("aria-describedby");if(s){let a=document.getElementById(s);if(a?.textContent?.trim())return a.textContent.trim()}let i=pe(e),l=document.title?.trim();return i&&l?`${i}: ${l}`:i||l||"Submit form"}var fe=/^(search|find|look|filter|browse|view|show|check|preview|get|fetch|retrieve|load)\b/i,ge=/^(delete|remove|cancel|terminate|destroy|purge|revoke|unsubscribe|deactivate)\b/i,Ke=/\/(delete|remove|cancel|destroy)\b/i;function Ye(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 o=e.method.toLowerCase()==="get",r=J(e),s=r?fe.test(r.trim()):!1;(o||s)&&(t.readOnlyHint=!0)}if(t.destructiveHint===void 0){let o=J(e),r=o?ge.test(o.trim()):!1,s=e.action?Ke.test(e.action):!1;(r||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 Xe(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 be(e,t=new Set){if(t.has(e))return[];t.add(e);let n=[];for(let o of Array.from(e.querySelectorAll("*")))o.shadowRoot&&n.push(...Array.from(o.shadowRoot.querySelectorAll("input, textarea, select")),...be(o.shadowRoot,t));return n}function Qe(e){let t={},n=[],o=new Map,r=new Set,s=new Set,i=[...Array.from(e.querySelectorAll("input, textarea, select")),...be(e)];for(let c of i){let m=c.name,u=m||he(c);if(!u)continue;if(c instanceof HTMLInputElement&&c.type==="radio"){if(r.has(u))continue;r.add(u)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){if(s.has(u))continue;s.add(u)}let p=W(c);if(!p||!U(c))continue;p.title=Te(c);let f=ye(c);f&&(p.description=f);let b=Xe(c);if(b!==void 0&&(p.default=b),c instanceof HTMLInputElement&&c.type==="radio"){p.enum=se(e,u);let L=ae(e,u);L.length>0&&(p.oneOf=L);let d=e.querySelector(`input[type="radio"][name="${CSS.escape(u)}"]:checked`);d?.value&&(p.default=d.value)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){let L=re(e,u);if(L.length>1){let d={type:"array",items:{type:"string",enum:L},title:p.title};p.description&&(d.description=p.description);let g=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(u)}"]:checked`)).map(h=>h.value);g.length>0&&(d.default=g),t[u]=d,c.required&&n.push(u);continue}}t[u]=p,m||o.set(u,c),c.required&&n.push(u)}let l=et(e),a=new Set;for(let{el:c,role:m,key:u,enumValues:p,enumOneOf:f}of l){if(t[u])continue;if(m==="radio"){if(a.has(u))continue;a.add(u)}let b=le(c,m);p&&p.length>0&&(b.enum=p,f&&f.length>0&&(b.oneOf=f)),b.title=tt(c);let L=nt(c);L&&(b.description=L),t[u]=b,o.set(u,c),c.getAttribute("aria-required")==="true"&&n.push(u)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:n},fieldElements:o}}var Ee=/^_r_[0-9a-z]+_$|^:[a-z0-9]+:$/i;function he(e){let t=e;if(t.dataset.webmcpName)return E(t.dataset.webmcpName);if(e.id&&!Ee.test(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){if(e.dataset.webmcpName)return E(e.dataset.webmcpName);if(e.id&&!Ee.test(e.id))return E(e.id);let t=e.getAttribute("aria-label");if(t)return E(t);let n=e.getAttribute("placeholder");return n?E(n):null}function et(e){let t=C.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"),m=ce(a);m&&n.push({el:a,role:c,key:m})}let o=n.filter(a=>a.role==="radio"),r=n.filter(a=>a.role!=="radio"),s=new Map,i=[];for(let a of o){let c=a.el.closest('[role="radiogroup"]');c?(s.has(c)||s.set(c,[]),s.get(c).push(a.el)):i.push(a)}let l=[];for(let[a,c]of s){let m=ce(a);if(!m)continue;let u=c.map(f=>(f.getAttribute("data-value")??f.getAttribute("aria-label")??f.textContent??"").trim()).filter(Boolean),p=c.map(f=>{let b=(f.getAttribute("data-value")??f.getAttribute("aria-label")??f.textContent??"").trim(),L=(f.getAttribute("aria-label")??f.textContent??"").trim();return{const:b,title:L||b}}).filter(f=>f.const!=="");u.length>0&&l.push({el:a,role:"radio",key:m,enumValues:u,enumOneOf:p})}return[...r,...l,...i]}function ce(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 o=e.getAttribute("aria-labelledby");if(o){let r=document.getElementById(o)?.textContent?.trim();if(r)return E(r)}return null}function tt(e){let t=e;if(t.dataset?.webmcpTitle)return t.dataset.webmcpTitle;let n=e.getAttribute("aria-label");if(n)return n.trim();let o=e.getAttribute("aria-labelledby");if(o){let r=document.getElementById(o)?.textContent?.trim();if(r)return r}return e.id?j(e.id):""}function nt(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let n=e;if(n.dataset?.webmcpDescription)return n.dataset.webmcpDescription;let o=e.getAttribute("aria-description");if(o)return o;let r=e.getAttribute("aria-describedby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return i}let s=e.getAttribute("placeholder")??e.dataset?.placeholder;return s?s.trim():""}function Te(e){if("dataset"in e&&e.dataset.webmcpTitle)return e.dataset.webmcpTitle;let t=ot(e);return t||(e.name?j(e.name):e.id?j(e.id):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?e.placeholder.trim():"")}function ye(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let n=e;if(n.dataset.webmcpDescription)return n.dataset.webmcpDescription;let o=e.getAttribute("aria-description");if(o)return o;let r=e.getAttribute("aria-describedby");if(r){let s=document.getElementById(r);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 ot(e){if(e.id){let n=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(n){let o=ue(n);if(o)return o}}let t=e.closest("label");if(t){let n=ue(t);if(n)return n}return""}function ue(e){let t=e.cloneNode(!0);return t.querySelectorAll("input, select, textarea, button").forEach(n=>n.remove()),t.textContent?.trim()??""}function j(e){return e.replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().replace(/\b\w/g,t=>t.toUpperCase())}function U(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 Le(e,t,n){let o=rt(e,n),r=st(e),{schema:s,fieldElements:i}=at(t),l=it(n);return{name:o,description:r,inputSchema:s,annotations:l,fieldElements:i}}function it(e){let t={},n=e instanceof HTMLInputElement?e.value.trim():e?.textContent?.trim()??"";return fe.test(n)&&(t.readOnlyHint=!0,t.idempotentHint=!0),ge.test(n)&&(t.destructiveHint=!0),t.readOnlyHint!==!0&&(t.openWorldHint=!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function rt(e,t){if(t){let r=t instanceof HTMLInputElement?t.value.trim():t.textContent?.trim()??"";if(r&&r.length>0&&r.length<80)return E(r)}let n=xe(e);if(n)return E(n);let o=document.title?.trim();return o?E(o):`form_${++me}`}function st(e){let t=xe(e),n=document.title?.trim();return t&&n&&t!==n?`${t} on ${n}`:t||n||"Submit form"}function xe(e){let t=e.querySelector("h1, h2, h3");if(t?.textContent?.trim())return t.textContent.trim();let n=e;for(;n;){let o=n.previousElementSibling;for(;o;){if(/^H[1-3]$/i.test(o.tagName)){let r=o.textContent?.trim()??"";if(r)return r}o=o.previousElementSibling}if(n=n.parentElement,!n||n===document.body)break}return""}function at(e){let t={},n=[],o=new Map,r=new Set,s=new Set;for(let i of e){if(!(i instanceof HTMLInputElement)&&!(i instanceof HTMLTextAreaElement)&&!(i instanceof HTMLSelectElement)){let u=Ze(i);if(!u||!U(i))continue;let p={type:"string"};p.title=i.getAttribute("aria-label")??u;let f=(i.getAttribute("aria-description")??i.getAttribute("aria-describedby"),null);f&&(p.description=f),t[u]=p,o.set(u,i),n.push(u);continue}let l=i.name,a=(l?E(l):null)||he(i);if(!a)continue;if(i instanceof HTMLInputElement&&i.type==="radio"){if(r.has(a))continue;r.add(a)}if(i instanceof HTMLInputElement&&i.type==="checkbox"){if(s.has(a))continue;s.add(a)}let c=W(i);if(!c||!U(i))continue;c.title=Te(i);let m=ye(i);if(m&&(c.description=m),i instanceof HTMLInputElement&&i.type==="checkbox"){let u=e.filter(p=>p instanceof HTMLInputElement&&p.type==="checkbox"&&p.name===a).map(p=>p.value).filter(p=>p!==""&&p!=="on");if(u.length>1){let p={type:"array",items:{type:"string",enum:u},title:c.title};c.description&&(p.description=c.description),t[a]=p,i.required&&n.push(a);continue}}t[a]=c,l||o.set(a,i),i.required&&n.push(a)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:n},fieldElements:o}}$();var O=new WeakMap,Se=new WeakMap,P=new WeakMap,H=new WeakMap,A=new WeakMap,_=new WeakMap,ct=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,ut=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,v=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function ve(e,t,n,o){return o?.fieldElements&&P.set(e,o.fieldElements),He(e,n),async r=>{A.set(e,[]),H.delete(e),K(e,r);let s=pt(o,r);return s.length>0&&H.set(e,s),window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:n}})),new Promise((i,l)=>{O.set(e,{resolve:i,reject:l}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&Ae(e).then(async()=>{try{K(e,r);for(let c=0;c<2&&dt(e,r,P.get(e)).length!==0;c++)K(e,r),await Ae(e,400,100);let a=e;if(!e.isConnected){let m=document.querySelector('button[type="submit"]:not([disabled]), input[type="submit"]:not([disabled])')?.closest("form");m&&(a=m,O.set(a,{resolve:i,reject:l}),He(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 He(e,t){e.__awmcp_intercepted||(e.__awmcp_intercepted=!0,e.addEventListener("submit",n=>{let o=O.get(e);if(!o)return;let{resolve:r}=o;O.delete(e);let s=mt(e,Se.get(e),P.get(e));_.delete(e);let i=H.get(e)??[];H.delete(e);let l=A.get(e)??[];A.delete(e);let a=l.filter(b=>b.type==="not_filled").map(b=>b.field),c={status:i.length>0||a.length>0?"partial":"success",filled_fields:s,skipped_fields:a,missing_required:i,warnings:[...i.map(b=>({field:b,type:"missing_required",message:`required field "${b}" was not provided`})),...l]},m=[...i.length?[`required fields were not filled: ${i.join(", ")}`]:[],...l.map(b=>b.message)],u=m.length?` Note: ${m.join("; ")}.`:"",f={content:[{type:"text",text:`Form submitted. Fields: ${JSON.stringify(s)}${u}`},{type:"text",text:JSON.stringify(c)}]};n.agentInvoked&&typeof n.respondWith=="function"&&(n.preventDefault(),n.respondWith(Promise.resolve(f))),r(f)}),e.addEventListener("reset",()=>{_.delete(e),window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:t}}))}))}function R(e,t){if(e.focus(),e.select?.(),document.execCommand("insertText",!1,t)&&e.value===t)return;let n=e instanceof HTMLTextAreaElement?ut:ct;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 Y(e,t){v?v.call(e,t):e.checked=t,e.dispatchEvent(new Event("change",{bubbles:!0}))}function B(e,t){for(let n of Array.from(e.querySelectorAll("*"))){let o=n.shadowRoot;if(!o)continue;let r=o.querySelector(t);if(r)return r;let s=B(o,t);if(s)return s}return null}function Q(e,t){let n=CSS.escape(t),o=e.querySelector(`[name="${n}"]`)??e.querySelector(`input#${n}, textarea#${n}, select#${n}`);return o||(B(document,`[name="${n}"]`)??B(document,`input#${n}, textarea#${n}, select#${n}`))}function K(e,t){Se.set(e,t);let n=P.get(e),o={};for(let[r,s]of Object.entries(t)){let i=Q(e,r);if(i){if(i instanceof HTMLInputElement)if(we(i,e,r,s),i.type==="checkbox")if(Array.isArray(s)){let a=CSS.escape(r);o[r]=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${a}"]`)).filter(c=>c.checked).map(c=>c.value)}else o[r]=i.checked;else o[r]=i.value;else i instanceof HTMLTextAreaElement?(R(i,String(s??"")),o[r]=i.value):i instanceof HTMLSelectElement&&(X(i,s,e,r),o[r]=i.multiple?Array.from(i.options).filter(a=>a.selected).map(a=>a.value):i.value);continue}let l=n?.get(r);if(l){let a=l;if(!l.isConnected){let c=l.id;if(c){let m=document.getElementById(c)??B(document,`#${CSS.escape(c)}`);m&&(a=m)}}a instanceof HTMLInputElement?(we(a,e,r,s),o[r]=a.type==="checkbox"?a.checked:a.value):a instanceof HTMLTextAreaElement?(R(a,String(s??"")),o[r]=a.value):a instanceof HTMLSelectElement?(X(a,s,e,r),o[r]=a.multiple?Array.from(a.options).filter(c=>c.selected).map(c=>c.value):a.value):(Ce(a,s),o[r]=s)}}_.set(e,o),window.__lastFillWarnings=A.get(e)??[]}function we(e,t,n,o){let r=e.type.toLowerCase();if(r==="checkbox"){if(Array.isArray(o)){let s=CSS.escape(n),i=t.querySelectorAll(`input[type="checkbox"][name="${s}"]`);for(let l of i)Y(l,o.map(String).includes(l.value));return}Y(e,!!o);return}if(r==="number"||r==="range"){let s=String(o??""),i=Number(s);if(s===""||isNaN(i)){A.get(t)?.push({field:n,type:"type_mismatch",message:`"${n}" expects a number, got: ${JSON.stringify(o)}`,original:o});return}let l=e.min!==""?parseFloat(e.min):-1/0,a=e.max!==""?parseFloat(e.max):1/0;if(i<l||i>a){let c=Math.min(Math.max(i,l),a);A.get(t)?.push({field:n,type:"clamped",message:`"${n}" value ${i} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${c}`,original:i,actual:c}),e.value=String(c)}else e.value=String(i);e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:String(i)})),e.dispatchEvent(new Event("change",{bubbles:!0}));return}if(r==="radio"){let s=CSS.escape(n),i=t.querySelectorAll(`input[type="radio"][name="${s}"]`);for(let l of i)if(l.value===String(o)){v?v.call(l,!0):l.checked=!0,l.dispatchEvent(new Event("change",{bubbles:!0}));break}return}R(e,String(o??""))}function X(e,t,n,o){if(e.multiple){let s=Array.isArray(t)?t.map(String):[String(t??"")];for(let i of Array.from(e.options))i.selected=s.includes(i.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}let r=String(t??"");if(e.value=r,e.value!==r){let s=r.toLowerCase(),i=Array.from(e.options).find(l=>l.text.trim().toLowerCase()===s||l.label.trim().toLowerCase()===s);i?e.value=i.value:n&&o&&A.get(n)?.push({field:o,type:"not_filled",message:`"${o}" value "${r}" did not match any option in the select`,original:r})}e.dispatchEvent(new Event("change",{bubbles:!0}))}function Ce(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 r=Array.from(e.querySelectorAll('[role="radio"]'));for(let s of r)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 r)l!==s&&l.setAttribute("aria-checked","false");break}return}let o=e;if(console.log("[auto-webmcp] fillAriaField",{tag:e.tagName,role:n,isContentEditable:o.isContentEditable,id:e.id,ariaLabel:e.getAttribute("aria-label"),textContentBefore:(o.textContent??"").slice(0,80)}),o.isContentEditable){o.focus();let r=document.createRange();r.selectNodeContents(o);let s=window.getSelection();s?.removeAllRanges(),s?.addRange(r);let i=String(t??"");console.log("[auto-webmcp] fillAriaField: text to insert:",JSON.stringify(i));let l=!1;try{let a=new DataTransfer;a.setData("text/plain",i),o.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,composed:!0,clipboardData:a})),l=(o.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S1 paste result:",l,JSON.stringify((o.textContent??"").slice(0,80)))}catch(a){console.log("[auto-webmcp] fillAriaField: S1 paste threw:",a)}if(!l){let a=document.execCommand("insertText",!1,i);l=(o.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S2 execCommand result:",a,"inserted:",l,JSON.stringify((o.textContent??"").slice(0,80)))}if(!l)try{o.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,composed:!0,inputType:"insertText",data:i})),l=(o.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S3 beforeinput result:",l,JSON.stringify((o.textContent??"").slice(0,80)))}catch(a){console.log("[auto-webmcp] fillAriaField: S3 beforeinput threw:",a)}if(!l){o.textContent=i;let a=document.createRange();a.selectNodeContents(o),a.collapse(!1),s?.removeAllRanges(),s?.addRange(a),console.log("[auto-webmcp] fillAriaField: S4 textContent assignment done, textContent:",JSON.stringify((o.textContent??"").slice(0,80)))}o.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:i})),console.log("[auto-webmcp] fillAriaField: done, final textContent:",JSON.stringify((o.textContent??"").slice(0,80)))}else console.log("[auto-webmcp] fillAriaField: not contentEditable, dispatching input/change only"),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function mt(e,t,n){let o={},r=new FormData(e),s=_.get(e);for(let[i,l]of r.entries())if(o[i]!==void 0){let a=o[i];Array.isArray(a)?a.push(l):o[i]=[a,l]}else o[i]=l;if(t)for(let i of Object.keys(t)){if(i in o)continue;if(s&&i in s){o[i]=s[i];continue}let l=Q(e,i)??n?.get(i)??null;if(l)if(l instanceof HTMLInputElement&&l.type==="checkbox")o[i]=l.checked;else if(l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)o[i]=l.value;else{let a=l.getAttribute("role");a==="checkbox"||a==="switch"?o[i]=l.getAttribute("aria-checked")==="true":o[i]=l.textContent?.trim()??""}}return o}function ke(e,t){if(e instanceof HTMLInputElement){let n=e.type.toLowerCase();n==="checkbox"?Y(e,!!t):n==="radio"?e.value===String(t)&&(v?v.call(e,!0):e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):R(e,String(t??""))}else e instanceof HTMLTextAreaElement?R(e,String(t??"")):e instanceof HTMLSelectElement?X(e,t):Ce(e,t)}function Ae(e,t=800,n=150){return new Promise(o=>{let r=!1,s=null,i=()=>{r||(r=!0,l.disconnect(),s!==null&&clearTimeout(s),o())},l=new MutationObserver(()=>{s!==null&&clearTimeout(s),s=setTimeout(i,n)});l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(i,t),s=setTimeout(i,n)})}function dt(e,t,n){let o=[];for(let[r,s]of Object.entries(t)){let i=Q(e,r)??n?.get(r)??null;i&&(i instanceof HTMLInputElement&&i.type==="checkbox"?i.checked!==!!s&&o.push(r):(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&i.value!==String(s??"")&&o.push(r))}return o}function pt(e,t){return e?.inputSchema?.required?.length?e.inputSchema.required.filter(n=>!(n in t)):[]}function Re(e,t,n){window.dispatchEvent(new CustomEvent(e,{detail:{form:t,toolName:n}}))}function ft(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 N(e,t){if(ft(e,t))return;let n;for(let[l,a]of Object.entries(t.overrides))try{if(e.matches(l)){n=a;break}}catch{}let o=de(e,n);t.debug&&Mt(o.name,o.description);let r=ve(e,t,o.name,o);await z(e,o,r),ee.add(e),Ie++;let s=e.querySelector('[type="submit"], button[data-variant="primary"], button:not([type])')??null,i=window.__pendingSubmitBtns??={};i[o.name]=s,t.debug&&console.log(`[auto-webmcp] Registered: ${o.name}`,o),Re("form:registered",e,o.name)}async function gt(e,t){let{getRegisteredToolName:n}=await Promise.resolve().then(()=>($(),Me)),o=n(e);o&&(await k(e),ee.delete(e),t.debug&&console.log(`[auto-webmcp] Unregistered: ${o}`),Re("form:unregistered",e,o))}var F=null,ee=new WeakSet,Ie=0,Z=new Map,bt=300;function Et(e){let t=e.tagName.toLowerCase();if(t==="input"||t==="textarea"||t==="select")return!0;let n=e.getAttribute("role");if(n&&C.includes(n)||e.querySelector("input, textarea, select"))return!0;for(let o of C)if(e.querySelector(`[role="${o}"]`))return!0;return!1}function ht(e,t){let n=Z.get(e);n&&clearTimeout(n),Z.set(e,setTimeout(()=>{Z.delete(e),N(e,t)},bt))}function Tt(e){F||(F=new MutationObserver(t=>{for(let n of t){for(let o of n.addedNodes){if(!(o instanceof Element))continue;if(o instanceof HTMLFormElement){N(o,e);continue}let r=o.closest("form");r instanceof HTMLFormElement&&ee.has(r)&&Et(o)&&ht(r,e);for(let s of Array.from(o.querySelectorAll("form")))N(s,e)}for(let o of n.removedNodes){if(!(o instanceof Element))continue;let r=o instanceof HTMLFormElement?[o]:Array.from(o.querySelectorAll("form"));for(let s of r)gt(s,e)}}}),F.observe(document.body,{childList:!0,subtree:!0}))}function yt(e){window.addEventListener("hashchange",()=>I(e));let t={pushState:history.pushState.bind(history),replaceState:history.replaceState.bind(history)};history.pushState=function(...n){t.pushState(...n),I(e)},history.replaceState=function(...n){t.replaceState(...n),I(e)},window.addEventListener("popstate",()=>I(e))}async function I(e){let t=Array.from(document.querySelectorAll("form"));await Promise.allSettled(t.map(n=>N(n,e)))}var Lt=new Set(["password","hidden","file","submit","reset","button","image"]);async function xt(e){if(!M())return;let t='[type="submit"]:not([disabled]), button[data-variant="primary"]:not([disabled])',n='[type="submit"], button[data-variant="primary"]',o=/subscribe|submit|sign[\s-]?up|send|join|go|search|post|tweet|publish/i,r=Array.from(document.querySelectorAll('input:not(form input), textarea:not(form textarea), select:not(form select), [role="textbox"]:not(form [role="textbox"]):not(input):not(textarea), [role="searchbox"]:not(form [role="searchbox"]):not(input):not(textarea), [contenteditable="true"]:not(form [contenteditable="true"]):not(input):not(textarea)')).filter(i=>{if(i instanceof HTMLInputElement&&Lt.has(i.type.toLowerCase()))return console.log(`[auto-webmcp] orphan: skipping excluded type "${i.type}" (name="${i.name}" id="${i.id}")`),!1;let l=i.getBoundingClientRect();return l.width===0||l.height===0?(console.log(`[auto-webmcp] orphan: skipping invisible input (name="${i.name}" id="${i.id}")`),!1):!0});if(console.log(`[auto-webmcp] orphan: found ${r.length} visible orphan input(s)`),r.length===0)return;let s=new Map;for(let i of r){let l=i.parentElement,a=i.parentElement??document.body;for(;l&&l!==document.body;){if(l.querySelector(n)!==null||Array.from(l.querySelectorAll("button")).some(m=>o.test(m.textContent??""))){a=l;break}l=l.parentElement}console.log(`[auto-webmcp] orphan: input (name="${i.name}" id="${i.id}") grouped into container`,a),s.has(a)||s.set(a,[]),s.get(a).push(i)}console.log(`[auto-webmcp] orphan: ${s.size} group(s) found`);for(let[i,l]of s){let a=Array.from(i.querySelectorAll(t)).filter(d=>{let g=d.getBoundingClientRect();return g.width>0&&g.height>0}),c=a[a.length-1]??null;if(!c){let d=Array.from(i.querySelectorAll(n)).filter(g=>{let h=g.getBoundingClientRect();return h.width>0&&h.height>0&&g.disabled});c=d[d.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using disabled submit button as reference: "${c.textContent?.trim()}"`)}if(!c){let d=Array.from(i.querySelectorAll('button, [role="button"]')).filter(g=>{let h=g.getBoundingClientRect();return h.width>0&&h.height>0&&!g.disabled&&g.getAttribute("aria-disabled")!=="true"&&o.test(g.textContent??"")});c=d[d.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using text-matched button in container: "${c.textContent?.trim()}"`)}if(!c){let d=i.closest('[role="dialog"], [aria-modal="true"]');if(d){let g=Array.from(d.querySelectorAll('button, [role="button"]')).filter(T=>{let S=T.getBoundingClientRect();return S.width>0&&S.height>0&&o.test(T.textContent??"")});console.log("[auto-webmcp] orphan: dialog buttons matching submit text:",g.map(T=>`"${T.textContent?.trim().slice(0,30)}" disabled=${T.disabled} aria-disabled=${T.getAttribute("aria-disabled")}`));let h=g.filter(T=>T.disabled||T.getAttribute("aria-disabled")==="true"),x=g.filter(T=>!T.disabled&&T.getAttribute("aria-disabled")!=="true"),y=h.length>0?h:x;c=y[y.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using text-matched button in dialog: "${c.textContent?.trim().slice(0,40)}" disabled=${c.disabled} aria-disabled=${c.getAttribute("aria-disabled")}`)}}if(!c){let d=Array.from(document.querySelectorAll('button, [role="button"]')).filter(g=>{let h=g.getBoundingClientRect();return h.width>0&&h.height>0&&g.getAttribute("aria-disabled")!=="true"&&o.test(g.textContent??"")});c=d[d.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using page-wide fallback submit button: "${c.textContent?.trim()}"`)}console.log("[auto-webmcp] orphan: submit button for group:",c?`"${c.textContent?.trim()}" disabled=${c.disabled}`:"none");let m=Le(i,l,c);console.log(`[auto-webmcp] orphan: tool="${m.name}" schema keys:`,Object.keys(m.inputSchema.properties));let u=[],p=m.inputSchema.properties,f=/^_r_[0-9a-z]+_$/i;for(let d of l){let g=d.id&&!f.test(d.id)?d.id:null,h=d.name||d.getAttribute("name")||d.dataset.webmcpName||g||d.getAttribute("aria-label")||d.getAttribute("placeholder")||null,x=h?h.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64):null,y=!!(x&&p[x]);console.log(`[auto-webmcp] orphan: field (name="${d.name??""}" id="${d.id}") rawKey="${h}" safeKey="${x}" matched=${y}`),y&&u.push({key:x,el:d})}if(console.log(`[auto-webmcp] orphan: ${u.length}/${l.length} input(s) mapped to schema keys`),u.length===0){console.log(`[auto-webmcp] orphan: skipping group "${m.name}" \u2014 no inputs mapped to schema keys`);continue}let b=m.name,L=async d=>{console.log(`[auto-webmcp] orphan execute: tool="${b}" params=`,d),console.log("[auto-webmcp] orphan execute: inputPairs=",u.map(y=>y.key));for(let{key:y,el:T}of u)d[y]!==void 0?(console.log(`[auto-webmcp] orphan execute: filling key="${y}" value=`,d[y],"element=",T),ke(T,d[y]),console.log("[auto-webmcp] orphan execute: after fill, element value=",T.value)):console.log(`[auto-webmcp] orphan execute: key="${y}" not in params, skipping`);if(window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:b}})),!(e.autoSubmit||!!c?.hasAttribute("toolautosubmit")||c instanceof HTMLElement&&c.dataset.webmcpAutosubmit!==void 0||i.hasAttribute("toolautosubmit")||i instanceof HTMLElement&&i.dataset.webmcpAutosubmit!==void 0))return console.log("[auto-webmcp] orphan execute: autoSubmit=false, returning without clicking submit"),{content:[{type:"text",text:"Fields filled. Ready to submit."}]};console.log("[auto-webmcp] orphan execute: polling for enabled submit button (up to 2s)...");let h=null,x=Date.now()+2e3;for(;Date.now()<x;){let y=Array.from(i.querySelectorAll(t)).filter(S=>{let te=S.getBoundingClientRect();return te.width>0&&te.height>0}),T=y[y.length-1]??null;if(T){h=T;break}await new Promise(S=>setTimeout(S,100))}return h?(console.log(`[auto-webmcp] orphan execute: clicking submit button "${h.textContent?.trim()}"`),h.click(),{content:[{type:"text",text:"Fields filled and form submitted."}]}):(console.warn("[auto-webmcp] orphan execute: submit button still disabled after 2s"),{content:[{type:"text",text:"Fields filled but the submit button is still disabled. The page may require additional input before submitting."}]})};try{let d={name:m.name,description:m.description,inputSchema:m.inputSchema,execute:L};m.annotations&&Object.keys(m.annotations).length>0&&(d.annotations=m.annotations),await navigator.modelContext.registerTool(d);let g=window.__pendingSubmitBtns??={};g[m.name]=c,e.debug&&console.log(`[auto-webmcp] Orphan tool registered: ${m.name}`,m)}catch{}}}function Mt(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 Fe(e){document.readyState==="loading"&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),Ie=0,Tt(e),yt(e),await I(e),await xt(e)}function $e(){F?.disconnect(),F=null}$();async function Oe(e){let t=oe(e);return t.debug&&console.debug("[auto-webmcp] Initializing",{webmcpSupported:M(),config:t}),await Fe(t),{destroy:async()=>{$e(),await G()},getTools:V,isSupported:M()}}typeof window<"u"&&!window.__AUTO_WEBMCP_NO_AUTOINIT&&Oe();return De(Ht);})();
|
|
1
|
+
"use strict";var AutoWebMCP=(()=>{var W=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Je=Object.prototype.hasOwnProperty;var je=(e,t)=>()=>(e&&(t=e(e=0)),t);var re=(e,t)=>{for(var o in t)W(e,o,{get:t[o],enumerable:!0})},Ue=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of We(t))!Je.call(e,r)&&r!==o&&W(e,r,{get:()=>t[r],enumerable:!(n=De(t,r))||n.enumerable});return e};var Ve=e=>Ue(W({},"__esModule",{value:!0}),e);var He={};re(He,{getAllRegisteredTools:()=>K,getRegisteredToolName:()=>ft,isWebMCPSupported:()=>L,registerFormTool:()=>G,unregisterAll:()=>Y,unregisterFormTool:()=>k});function L(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function G(e,t,o){if(!L())return;H.get(e)&&await k(e);let r={name:t.name,description:t.description,inputSchema:t.inputSchema,execute:o};t.annotations&&Object.keys(t.annotations).length>0&&(r.annotations=t.annotations);try{await navigator.modelContext.registerTool(r)}catch{try{await navigator.modelContext.unregisterTool(t.name),await navigator.modelContext.registerTool(r)}catch{}}H.set(e,t.name)}async function k(e){if(!L())return;let t=H.get(e);if(t){try{await navigator.modelContext.unregisterTool(t)}catch{}H.delete(e)}}function ft(e){return H.get(e)}function K(){return Array.from(H.entries()).map(([e,t])=>({form:e,name:t}))}async function Y(){let e=Array.from(H.entries());await Promise.all(e.map(([t])=>k(t)))}var H,O=je(()=>{"use strict";H=new Map});var kt={};re(kt,{autoWebMCP:()=>qe});function ae(e){return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,overrides:e?.overrides??{},debug:e?.debug??!1}}var C=["textbox","combobox","checkbox","radio","switch","spinbutton","searchbox","slider"];function j(e){return e instanceof HTMLInputElement?ze(e):e instanceof HTMLTextAreaElement?{type:"string"}:e instanceof HTMLSelectElement?Ke(e):null}function ze(e){switch(e.type.toLowerCase()){case"text":case"search":case"tel":return J(e);case"email":return{...J(e),format:"email"};case"url":return{...J(e),format:"uri"};case"number":case"range":{let o={type:"number"};return e.min!==""&&(o.minimum=parseFloat(e.min)),e.max!==""&&(o.maximum=parseFloat(e.max)),o}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 J(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 o=e.getAttribute("list");if(o){let n=e.ownerDocument.getElementById(o);if(n instanceof HTMLDataListElement){let r=Array.from(n.options).filter(a=>!a.disabled&&a.value.trim()!=="");r.length>0&&(t.enum=r.map(a=>a.value.trim()),t.oneOf=r.map(a=>({const:a.value.trim(),title:a.textContent?.trim()||a.value.trim()})))}}return t}var Ge=/^(select|choose|pick)\b|^--+|---/i;function se(e){return e.disabled?!0:e.value!==""?!1:Ge.test(e.text.trim())}function Ke(e){let t=[],o=[];for(let n of Array.from(e.children))if(n instanceof HTMLOptGroupElement){if(n.disabled)continue;let r=n.label?.trim()??"";for(let a of Array.from(n.children)){if(!(a instanceof HTMLOptionElement)||se(a))continue;t.push(a.value);let i={const:a.value,title:a.text.trim()||a.value};r&&(i.group=r),o.push(i)}}else if(n instanceof HTMLOptionElement){if(se(n))continue;t.push(n.value),o.push({const:n.value,title:n.text.trim()||n.value})}return t.length===0?{type:"string"}:e.multiple?{type:"array",items:{type:"string",enum:t}}:{type:"string",enum:t,oneOf:o}}function le(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(o=>o.value).filter(o=>o!==""&&o!=="on")}function ce(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!=="")}function ue(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).filter(n=>n.value!=="").map(n=>{let r=Ye(n);return{const:n.value,title:r||n.value}})}function me(e,t){switch(t){case"checkbox":case"switch":return{type:"boolean"};case"spinbutton":case"slider":{let o={type:"number"},n=e.getAttribute("aria-valuemin"),r=e.getAttribute("aria-valuemax");return n!==null&&(o.minimum=parseFloat(n)),r!==null&&(o.maximum=parseFloat(r)),o}case"combobox":{let o=e.getAttribute("aria-owns")??e.getAttribute("aria-controls");if(o){let n=document.getElementById(o);if(n){let r=Array.from(n.querySelectorAll('[role="option"]')).filter(a=>a.getAttribute("aria-disabled")!=="true");if(r.length>0){let a=r.map(l=>(l.getAttribute("data-value")??l.textContent??"").trim()).filter(Boolean),i=r.map(l=>({const:(l.getAttribute("data-value")??l.textContent??"").trim(),title:(l.textContent??"").trim()}));return{type:"string",enum:a,oneOf:i}}}}return{type:"string"}}case"textbox":case"searchbox":case"radio":default:return{type:"string"}}}function Ye(e){let t=e.closest("label");if(t){let o=t.cloneNode(!0);o.querySelectorAll("input, select, textarea, button").forEach(r=>r.remove());let n=o.textContent?.trim()??"";if(n)return n}if(e.id){let o=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(o){let n=o.textContent?.trim()??"";if(n)return n}}return""}var pe=0;function fe(e,t){let o=t?.name??Xe(e),n=t?.description??Ze(e),{schema:r,fieldElements:a}=ot(e),i=tt(e);return{name:o,description:n,inputSchema:r,annotations:i,fieldElements:a}}function Xe(e){let t=e.getAttribute("toolname");if(t)return h(t);let o=e.dataset.webmcpName;if(o)return h(o);let n=U(e);if(n)return h(n);let r=ge(e);if(r)return h(r);if(e.id)return h(e.id);if(e.name)return h(e.name);if(e.action){let a=Qe(e.action);if(a)return h(a)}return`form_${++pe}`}function h(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"form"}function U(e){let t=[...Array.from(e.querySelectorAll('button[type="submit"], button:not([type])')),...Array.from(e.querySelectorAll('input[type="submit"]'))];for(let o of t){let n=o instanceof HTMLInputElement?o.value.trim():o.textContent?.trim()??"";if(n&&n.length>0&&n.length<80)return n}return""}function ge(e){let t=e;for(;t;){let o=t.previousElementSibling;for(;o;){if(/^H[1-3]$/i.test(o.tagName)){let n=o.textContent?.trim()??"";if(n)return n}o=o.previousElementSibling}if(t=t.parentElement,!t||t===document.body)break}return""}function Qe(e){try{let o=new URL(e,window.location.href).pathname.split("/").filter(Boolean);return o[o.length-1]??""}catch{return""}}function Ze(e){let t=e.getAttribute("tooldescription");if(t)return t.trim();let o=e.dataset.webmcpDescription;if(o)return o.trim();let n=e.querySelector("legend");if(n?.textContent?.trim())return n.textContent.trim();let r=e.getAttribute("aria-label");if(r?.trim())return r.trim();let a=e.getAttribute("aria-describedby");if(a){let s=document.getElementById(a);if(s?.textContent?.trim())return s.textContent.trim()}let i=ge(e),l=document.title?.trim();return i&&l?`${i}: ${l}`:i||l||"Submit form"}var be=/^(search|find|look|filter|browse|view|show|check|preview|get|fetch|retrieve|load)\b/i,he=/^(delete|remove|cancel|terminate|destroy|purge|revoke|unsubscribe|deactivate)\b/i,et=/\/(delete|remove|cancel|destroy)\b/i;function tt(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 n=e.method.toLowerCase()==="get",r=U(e),a=r?be.test(r.trim()):!1;(n||a)&&(t.readOnlyHint=!0)}if(t.destructiveHint===void 0){let n=U(e),r=n?he.test(n.trim()):!1,a=e.action?et.test(e.action):!1;(r||a)&&(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 nt(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(o=>o.selected).map(o=>o.value);return t.length>0?t:void 0}return e.value!==""?e.value:void 0}}function Ee(e,t=new Set){if(t.has(e))return[];t.add(e);let o=[];for(let n of Array.from(e.querySelectorAll("*")))if(n.shadowRoot){let r=Array.from(n.shadowRoot.querySelectorAll("input, textarea, select"));r.length>0&&console.log(`[auto-webmcp] shadow: found ${r.length} control(s) in ${n.tagName.toLowerCase()} shadow root:`,r.map(a=>`${a.tagName.toLowerCase()}[type=${a.type??"?"}][name="${a.name}"][id="${a.id}"]`)),o.push(...r,...Ee(n.shadowRoot,t))}return o}function ot(e){let t={},o=[],n=new Map,r=new Set,a=new Set,i=[...Array.from(e.querySelectorAll("input, textarea, select")),...Ee(e)];for(let c of i){let u=c.name,d=u||ye(c);if(!d)continue;if(c instanceof HTMLInputElement&&c.type==="radio"){if(r.has(d))continue;r.add(d)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){if(a.has(d))continue;a.add(d)}let p=j(c);if(!p||!z(c))continue;p.title=xe(c);let b=we(c);b&&(p.description=b);let T=nt(c);if(T!==void 0&&(p.default=T),c instanceof HTMLInputElement&&c.type==="radio"){p.enum=ce(e,d);let m=ue(e,d);m.length>0&&(p.oneOf=m);let g=e.querySelector(`input[type="radio"][name="${CSS.escape(d)}"]:checked`);g?.value&&(p.default=g.value)}if(c instanceof HTMLInputElement&&c.type==="checkbox"){let m=le(e,d);if(m.length>1){let g={type:"array",items:{type:"string",enum:m},title:p.title};p.description&&(g.description=p.description);let f=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(d)}"]:checked`)).map(E=>E.value);f.length>0&&(g.default=f),t[d]=g,c.required&&o.push(d);continue}}t[d]=p,u||n.set(d,c);let w=c.required;if(!w){let m=c;for(;;){let g=m.getRootNode();if(!(g instanceof ShadowRoot))break;let f=g.host;if(f.hasAttribute("required")||f.getAttribute("aria-required")==="true"){w=!0;break}m=f}}w&&o.push(d)}let l=at(e),s=new Set;for(let{el:c,role:u,key:d,enumValues:p,enumOneOf:b}of l){if(t[d])continue;if(u==="radio"){if(s.has(d))continue;s.add(d)}let T=me(c,u);p&&p.length>0&&(T.enum=p,b&&b.length>0&&(T.oneOf=b)),T.title=st(c);let w=lt(c);w&&(T.description=w),t[d]=T,n.set(d,c),c.getAttribute("aria-required")==="true"&&o.push(d)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:o},fieldElements:n}}var Te=/^_r_[0-9a-z]+_$|^:[a-z0-9]+:$/i;function ye(e){let t=e;if(t.dataset.webmcpName)return h(t.dataset.webmcpName);if(e.id&&!Te.test(e.id))return h(e.id);let o=e.getAttribute("aria-label");if(o)return h(o);if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim())return h(e.placeholder.trim());let n=it(e);return n||(e instanceof HTMLInputElement&&e.type!=="text"?e.type:null)}function it(e){let t=e;for(;;){let o=t.getRootNode();if(!(o instanceof ShadowRoot))break;let n=o.host,r=n.getAttribute("field-name");if(r)return console.log("[auto-webmcp] shadow host key: field-name=",r),h(r);let a=n.getAttribute("label")||n.getAttribute("aria-label");if(a)return console.log("[auto-webmcp] shadow host key: label=",a),h(a);let i=n.getAttribute("name");if(i)return console.log("[auto-webmcp] shadow host key: name=",i),h(i);t=n}return null}function rt(e){if(e.dataset.webmcpName)return h(e.dataset.webmcpName);if(e.id&&!Te.test(e.id))return h(e.id);let t=e.getAttribute("aria-label");if(t)return h(t);let o=e.getAttribute("placeholder");return o?h(o):null}function at(e){let t=C.map(s=>`[role="${s}"]`).join(", "),o=[];for(let s of Array.from(e.querySelectorAll(t))){if(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement||s.getAttribute("aria-hidden")==="true"||s.hidden)continue;let c=s.getAttribute("role"),u=de(s);u&&o.push({el:s,role:c,key:u})}let n=o.filter(s=>s.role==="radio"),r=o.filter(s=>s.role!=="radio"),a=new Map,i=[];for(let s of n){let c=s.el.closest('[role="radiogroup"]');c?(a.has(c)||a.set(c,[]),a.get(c).push(s.el)):i.push(s)}let l=[];for(let[s,c]of a){let u=de(s);if(!u)continue;let d=c.map(b=>(b.getAttribute("data-value")??b.getAttribute("aria-label")??b.textContent??"").trim()).filter(Boolean),p=c.map(b=>{let T=(b.getAttribute("data-value")??b.getAttribute("aria-label")??b.textContent??"").trim(),w=(b.getAttribute("aria-label")??b.textContent??"").trim();return{const:T,title:w||T}}).filter(b=>b.const!=="");d.length>0&&l.push({el:s,role:"radio",key:u,enumValues:d,enumOneOf:p})}return[...r,...l,...i]}function de(e){let t=e;if(t.dataset?.webmcpName)return h(t.dataset.webmcpName);if(e.id)return h(e.id);let o=e.getAttribute("aria-label");if(o)return h(o);let n=e.getAttribute("aria-labelledby");if(n){let r=document.getElementById(n)?.textContent?.trim();if(r)return h(r)}return null}function st(e){let t=e;if(t.dataset?.webmcpTitle)return t.dataset.webmcpTitle;let o=e.getAttribute("aria-label");if(o)return o.trim();let n=e.getAttribute("aria-labelledby");if(n){let r=document.getElementById(n)?.textContent?.trim();if(r)return r}return e.id?V(e.id):""}function lt(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let o=e;if(o.dataset?.webmcpDescription)return o.dataset.webmcpDescription;let n=e.getAttribute("aria-description");if(n)return n;let r=e.getAttribute("aria-describedby");if(r){let i=document.getElementById(r)?.textContent?.trim();if(i)return i}let a=e.getAttribute("placeholder")??e.dataset?.placeholder;return a?a.trim():""}function xe(e){if("dataset"in e&&e.dataset.webmcpTitle)return e.dataset.webmcpTitle;let t=ct(e);return t||(e.name?V(e.name):e.id?V(e.id):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?.trim()?e.placeholder.trim():"")}function we(e){let t=e.getAttribute("toolparamdescription");if(t)return t.trim();let o=e;if(o.dataset.webmcpDescription)return o.dataset.webmcpDescription;let n=e.getAttribute("aria-description");if(n)return n;let r=e.getAttribute("aria-describedby");if(r){let a=document.getElementById(r);if(a?.textContent?.trim())return a.textContent.trim()}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){let a=e.placeholder?.trim();if(a&&a.length>0)return a}return""}function ct(e){if(e.id){let r=document.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(r){let a=$(r);if(a)return a}}let t=e.getRootNode();if(t instanceof ShadowRoot){if(e.id){let a=t.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(a){let i=$(a);if(i)return i}}let r=t.querySelector("label");if(r){let a=$(r);if(a)return a}}let o=e.closest("label");if(o){let r=$(o);if(r)return r}let n=e;for(;;){let r=n.getRootNode();if(!(r instanceof ShadowRoot))break;let a=r.host,i=a.getAttribute("label")||a.getAttribute("aria-label");if(i)return i;n=a}return""}function $(e){let t=e.cloneNode(!0);return t.querySelectorAll("input, select, textarea, button").forEach(o=>o.remove()),t.textContent?.trim()??""}function V(e){return e.replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().replace(/\b\w/g,t=>t.toUpperCase())}function z(e){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||e.offsetParent===null&&t.position!=="fixed")return!1;let o=e;for(;o&&o!==document.body;){if(o.getAttribute("aria-hidden")==="true")return!1;o=o.parentElement}return!e.closest("fieldset")?.disabled}function Le(e,t,o){let n=mt(e,o),r=dt(e),{schema:a,fieldElements:i}=pt(t),l=ut(o);return{name:n,description:r,inputSchema:a,annotations:l,fieldElements:i}}function ut(e){let t={},o=e instanceof HTMLInputElement?e.value.trim():e?.textContent?.trim()??"";return be.test(o)&&(t.readOnlyHint=!0,t.idempotentHint=!0),he.test(o)&&(t.destructiveHint=!0),t.readOnlyHint!==!0&&(t.openWorldHint=!0),t.readOnlyHint===!0||t.destructiveHint===!0||t.idempotentHint===!0||t.openWorldHint===!1?t:{}}function mt(e,t){if(t){let r=t instanceof HTMLInputElement?t.value.trim():t.textContent?.trim()??"";if(r&&r.length>0&&r.length<80)return h(r)}let o=Me(e);if(o)return h(o);let n=document.title?.trim();return n?h(n):`form_${++pe}`}function dt(e){let t=Me(e),o=document.title?.trim();return t&&o&&t!==o?`${t} on ${o}`:t||o||"Submit form"}function Me(e){let t=e.querySelector("h1, h2, h3");if(t?.textContent?.trim())return t.textContent.trim();let o=e;for(;o;){let n=o.previousElementSibling;for(;n;){if(/^H[1-3]$/i.test(n.tagName)){let r=n.textContent?.trim()??"";if(r)return r}n=n.previousElementSibling}if(o=o.parentElement,!o||o===document.body)break}return""}function pt(e){let t={},o=[],n=new Map,r=new Set,a=new Set;for(let i of e){if(!(i instanceof HTMLInputElement)&&!(i instanceof HTMLTextAreaElement)&&!(i instanceof HTMLSelectElement)){let d=rt(i);if(!d||!z(i))continue;let p={type:"string"};p.title=i.getAttribute("aria-label")??d;let b=(i.getAttribute("aria-description")??i.getAttribute("aria-describedby"),null);b&&(p.description=b),t[d]=p,n.set(d,i),o.push(d);continue}let l=i.name,s=(l?h(l):null)||ye(i);if(!s)continue;if(i instanceof HTMLInputElement&&i.type==="radio"){if(r.has(s))continue;r.add(s)}if(i instanceof HTMLInputElement&&i.type==="checkbox"){if(a.has(s))continue;a.add(s)}let c=j(i);if(!c||!z(i))continue;c.title=xe(i);let u=we(i);if(u&&(c.description=u),i instanceof HTMLInputElement&&i.type==="checkbox"){let d=e.filter(p=>p instanceof HTMLInputElement&&p.type==="checkbox"&&p.name===s).map(p=>p.value).filter(p=>p!==""&&p!=="on");if(d.length>1){let p={type:"array",items:{type:"string",enum:d},title:c.title};c.description&&(p.description=c.description),t[s]=p,i.required&&o.push(s);continue}}t[s]=c,l||n.set(s,i),i.required&&o.push(s)}return{schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:t,required:o},fieldElements:n}}O();var P=new WeakMap,Ce=new WeakMap,_=new WeakMap,M=new WeakMap,A=new WeakMap,N=new WeakMap,gt=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,bt=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,v=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function ke(e,t,o,n){return n?.fieldElements&&_.set(e,n.fieldElements),Ae(e,o),async r=>{A.set(e,[]),M.delete(e),X(e,r);let a=Tt(n,r);return a.length>0&&M.set(e,a),window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:o}})),new Promise((i,l)=>{P.set(e,{resolve:i,reject:l}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&ve(e).then(async()=>{try{X(e,r);for(let c=0;c<2&&Et(e,r,_.get(e)).length!==0;c++)X(e,r),await ve(e,400,100);let s=e;if(!e.isConnected){let u=document.querySelector('button[type="submit"]:not([disabled]), input[type="submit"]:not([disabled])')?.closest("form");u&&(s=u,P.set(s,{resolve:i,reject:l}),Ae(s,o))}s!==e&&M.has(e)&&(M.set(s,M.get(e)),M.delete(e)),s.requestSubmit()}catch(s){l(s instanceof Error?s:new Error(String(s)))}})})}}function Ae(e,t){e.__awmcp_intercepted||(e.__awmcp_intercepted=!0,e.addEventListener("submit",o=>{let n=P.get(e);if(!n)return;let{resolve:r}=n;P.delete(e);let a=ht(e,Ce.get(e),_.get(e));N.delete(e);let i=M.get(e)??[];M.delete(e);let l=A.get(e)??[];A.delete(e);let s=l.filter(T=>T.type==="not_filled").map(T=>T.field),c={status:i.length>0||s.length>0?"partial":"success",filled_fields:a,skipped_fields:s,missing_required:i,warnings:[...i.map(T=>({field:T,type:"missing_required",message:`required field "${T}" was not provided`})),...l]},u=[...i.length?[`required fields were not filled: ${i.join(", ")}`]:[],...l.map(T=>T.message)],d=u.length?` Note: ${u.join("; ")}.`:"",b={content:[{type:"text",text:`Form submitted. Fields: ${JSON.stringify(a)}${d}`},{type:"text",text:JSON.stringify(c)}]};o.agentInvoked&&typeof o.respondWith=="function"&&(o.preventDefault(),o.respondWith(Promise.resolve(b))),r(b)}),e.addEventListener("reset",()=>{N.delete(e),window.dispatchEvent(new CustomEvent("toolcancel",{detail:{toolName:t}}))}))}function R(e,t){if(e.focus(),e.select?.(),document.execCommand("insertText",!1,t)&&e.value===t)return;let o=e instanceof HTMLTextAreaElement?bt:gt;o?o.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 Q(e,t){v?v.call(e,t):e.checked=t,e.dispatchEvent(new Event("change",{bubbles:!0}))}function B(e,t){for(let o of Array.from(e.querySelectorAll("*"))){let n=o.shadowRoot;if(!n)continue;let r=n.querySelector(t);if(r)return r;let a=B(n,t);if(a)return a}return null}function ee(e,t){let o=CSS.escape(t),n=e.querySelector(`[name="${o}"]`)??e.querySelector(`input#${o}, textarea#${o}, select#${o}`);return n||(B(document,`[name="${o}"]`)??B(document,`input#${o}, textarea#${o}, select#${o}`))}function X(e,t){Ce.set(e,t);let o=_.get(e),n={};for(let[r,a]of Object.entries(t)){let i=ee(e,r);if(i){if(i instanceof HTMLInputElement)if(Se(i,e,r,a),i.type==="checkbox")if(Array.isArray(a)){let s=CSS.escape(r);n[r]=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${s}"]`)).filter(c=>c.checked).map(c=>c.value)}else n[r]=i.checked;else n[r]=i.value;else i instanceof HTMLTextAreaElement?(R(i,String(a??"")),n[r]=i.value):i instanceof HTMLSelectElement&&(Z(i,a,e,r),n[r]=i.multiple?Array.from(i.options).filter(s=>s.selected).map(s=>s.value):i.value);continue}let l=o?.get(r);if(l){let s=l;if(!l.isConnected){let c=l.id;if(c){let u=document.getElementById(c)??B(document,`#${CSS.escape(c)}`);u&&(s=u)}}s instanceof HTMLInputElement?(Se(s,e,r,a),n[r]=s.type==="checkbox"?s.checked:s.value):s instanceof HTMLTextAreaElement?(R(s,String(a??"")),n[r]=s.value):s instanceof HTMLSelectElement?(Z(s,a,e,r),n[r]=s.multiple?Array.from(s.options).filter(c=>c.selected).map(c=>c.value):s.value):(Re(s,a),n[r]=a)}}N.set(e,n),window.__lastFillWarnings=A.get(e)??[]}function Se(e,t,o,n){let r=e.type.toLowerCase();if(r==="checkbox"){if(Array.isArray(n)){let a=CSS.escape(o),i=t.querySelectorAll(`input[type="checkbox"][name="${a}"]`);for(let l of i)Q(l,n.map(String).includes(l.value));return}Q(e,!!n);return}if(r==="number"||r==="range"){let a=String(n??""),i=Number(a);if(a===""||isNaN(i)){A.get(t)?.push({field:o,type:"type_mismatch",message:`"${o}" expects a number, got: ${JSON.stringify(n)}`,original:n});return}let l=e.min!==""?parseFloat(e.min):-1/0,s=e.max!==""?parseFloat(e.max):1/0;if(i<l||i>s){let c=Math.min(Math.max(i,l),s);A.get(t)?.push({field:o,type:"clamped",message:`"${o}" value ${i} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${c}`,original:i,actual:c}),e.value=String(c)}else e.value=String(i);e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:String(i)})),e.dispatchEvent(new Event("change",{bubbles:!0}));return}if(r==="radio"){let a=CSS.escape(o),i=t.querySelectorAll(`input[type="radio"][name="${a}"]`);for(let l of i)if(l.value===String(n)){v?v.call(l,!0):l.checked=!0,l.dispatchEvent(new Event("change",{bubbles:!0}));break}return}R(e,String(n??""))}function Z(e,t,o,n){if(e.multiple){let a=Array.isArray(t)?t.map(String):[String(t??"")];for(let i of Array.from(e.options))i.selected=a.includes(i.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}let r=String(t??"");if(e.value=r,e.value!==r){let a=r.toLowerCase(),i=Array.from(e.options).find(l=>l.text.trim().toLowerCase()===a||l.label.trim().toLowerCase()===a);i?e.value=i.value:o&&n&&A.get(o)?.push({field:n,type:"not_filled",message:`"${n}" value "${r}" did not match any option in the select`,original:r})}e.dispatchEvent(new Event("change",{bubbles:!0}))}function Re(e,t){let o=e.getAttribute("role");if(o==="checkbox"||o==="switch"){e.setAttribute("aria-checked",String(!!t)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(o==="radio"){e.setAttribute("aria-checked","true"),e.dispatchEvent(new MouseEvent("click",{bubbles:!0}));return}if(o==="radiogroup"){let r=Array.from(e.querySelectorAll('[role="radio"]'));for(let a of r)if((a.getAttribute("data-value")??a.getAttribute("aria-label")??a.textContent??"").trim()===String(t)){a.setAttribute("aria-checked","true"),a.dispatchEvent(new MouseEvent("click",{bubbles:!0}));for(let l of r)l!==a&&l.setAttribute("aria-checked","false");break}return}let n=e;if(console.log("[auto-webmcp] fillAriaField",{tag:e.tagName,role:o,isContentEditable:n.isContentEditable,id:e.id,ariaLabel:e.getAttribute("aria-label"),textContentBefore:(n.textContent??"").slice(0,80)}),n.isContentEditable){n.focus();let r=document.createRange();r.selectNodeContents(n);let a=window.getSelection();a?.removeAllRanges(),a?.addRange(r);let i=String(t??"");console.log("[auto-webmcp] fillAriaField: text to insert:",JSON.stringify(i));let l=!1;try{let s=new DataTransfer;s.setData("text/plain",i),n.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,composed:!0,clipboardData:s})),l=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S1 paste result:",l,JSON.stringify((n.textContent??"").slice(0,80)))}catch(s){console.log("[auto-webmcp] fillAriaField: S1 paste threw:",s)}if(!l){let s=document.execCommand("insertText",!1,i);l=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S2 execCommand result:",s,"inserted:",l,JSON.stringify((n.textContent??"").slice(0,80)))}if(!l)try{n.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,composed:!0,inputType:"insertText",data:i})),l=(n.textContent??"").trim().length>0,console.log("[auto-webmcp] fillAriaField: S3 beforeinput result:",l,JSON.stringify((n.textContent??"").slice(0,80)))}catch(s){console.log("[auto-webmcp] fillAriaField: S3 beforeinput threw:",s)}if(!l){n.textContent=i;let s=document.createRange();s.selectNodeContents(n),s.collapse(!1),a?.removeAllRanges(),a?.addRange(s),console.log("[auto-webmcp] fillAriaField: S4 textContent assignment done, textContent:",JSON.stringify((n.textContent??"").slice(0,80)))}n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:i})),console.log("[auto-webmcp] fillAriaField: done, final textContent:",JSON.stringify((n.textContent??"").slice(0,80)))}else console.log("[auto-webmcp] fillAriaField: not contentEditable, dispatching input/change only"),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function ht(e,t,o){let n={},r=new FormData(e),a=N.get(e);for(let[i,l]of r.entries())if(n[i]!==void 0){let s=n[i];Array.isArray(s)?s.push(l):n[i]=[s,l]}else n[i]=l;if(t)for(let i of Object.keys(t)){if(i in n)continue;if(a&&i in a){n[i]=a[i];continue}let l=ee(e,i)??o?.get(i)??null;if(l)if(l instanceof HTMLInputElement&&l.type==="checkbox")n[i]=l.checked;else if(l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement)n[i]=l.value;else{let s=l.getAttribute("role");s==="checkbox"||s==="switch"?n[i]=l.getAttribute("aria-checked")==="true":n[i]=l.textContent?.trim()??""}}return n}function Ie(e,t){if(e instanceof HTMLInputElement){let o=e.type.toLowerCase();o==="checkbox"?Q(e,!!t):o==="radio"?e.value===String(t)&&(v?v.call(e,!0):e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):R(e,String(t??""))}else e instanceof HTMLTextAreaElement?R(e,String(t??"")):e instanceof HTMLSelectElement?Z(e,t):Re(e,t)}function ve(e,t=800,o=150){return new Promise(n=>{let r=!1,a=null,i=()=>{r||(r=!0,l.disconnect(),a!==null&&clearTimeout(a),n())},l=new MutationObserver(()=>{a!==null&&clearTimeout(a),a=setTimeout(i,o)});l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(i,t),a=setTimeout(i,o)})}function Et(e,t,o){let n=[];for(let[r,a]of Object.entries(t)){let i=ee(e,r)??o?.get(r)??null;i&&(i instanceof HTMLInputElement&&i.type==="checkbox"?i.checked!==!!a&&n.push(r):(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&i.value!==String(a??"")&&n.push(r))}return n}function Tt(e,t){return e?.inputSchema?.required?.length?e.inputSchema.required.filter(o=>!(o in t)):[]}async function Fe(e,t){let o=String(t??"").trim();console.log("[auto-webmcp] fillComboboxButton: clicking button, value=",JSON.stringify(o)),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}));let n=await new Promise(l=>{let s=Date.now()+1e3,c=()=>{let u=document.querySelector('[role="listbox"]')??document.querySelector('[role="option"]')?.closest('[role="listbox"]')??null;if(u){l(u);return}if(Date.now()>=s){l(null);return}setTimeout(c,50)};c()});if(!n){console.warn("[auto-webmcp] fillComboboxButton: listbox did not appear after 1s");return}let r=Array.from(n.querySelectorAll('[role="option"]'));console.log("[auto-webmcp] fillComboboxButton: listbox has",r.length,"options");let a=o.toLowerCase(),i=r.find(l=>{let s=(l.getAttribute("data-value")??"").toLowerCase(),c=(l.getAttribute("aria-label")??"").toLowerCase(),u=(l.textContent??"").trim().toLowerCase();return s===a||c===a||u===a});i?(console.log("[auto-webmcp] fillComboboxButton: clicking option",i.textContent?.trim()),i.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))):console.warn("[auto-webmcp] fillComboboxButton: no option matched",JSON.stringify(o),"available:",r.map(l=>l.textContent?.trim()))}function Oe(e,t,o){window.dispatchEvent(new CustomEvent(e,{detail:{form:t,toolName:o}}))}function yt(e,t){if(e.dataset.noWebmcp!==void 0)return!0;for(let o of t.exclude)try{if(e.matches(o))return!0}catch{}return!1}async function D(e,t){if(yt(e,t))return;let o;for(let[l,s]of Object.entries(t.overrides))try{if(e.matches(l)){o=s;break}}catch{}let n=fe(e,o);t.debug&&Ct(n.name,n.description);let r=ke(e,t,n.name,n);await G(e,n,r),oe.add(e),Pe++;let a=e.querySelector('[type="submit"], button[data-variant="primary"], button:not([type])')??null,i=window.__pendingSubmitBtns??={};i[n.name]=a,t.debug&&console.log(`[auto-webmcp] Registered: ${n.name}`,n),Oe("form:registered",e,n.name)}async function xt(e,t){let{getRegisteredToolName:o}=await Promise.resolve().then(()=>(O(),He)),n=o(e);n&&(await k(e),oe.delete(e),t.debug&&console.log(`[auto-webmcp] Unregistered: ${n}`),Oe("form:unregistered",e,n))}var F=null,oe=new WeakSet,Pe=0,te=new Map,wt=300,q=null,Lt=500,ne=new Set;function Mt(e){q&&clearTimeout(q),q=setTimeout(()=>{q=null,_e(e)},Lt)}function $e(e){let t=e.tagName.toLowerCase();if(t==="input"||t==="textarea"||t==="select")return!0;let o=e.getAttribute("role");if(o&&C.includes(o)||e.querySelector("input, textarea, select"))return!0;for(let n of C)if(e.querySelector(`[role="${n}"]`))return!0;return!1}function Ht(e,t){let o=te.get(e);o&&clearTimeout(o),te.set(e,setTimeout(()=>{te.delete(e),D(e,t)},wt))}function At(e){F||(F=new MutationObserver(t=>{for(let o of t){for(let n of o.addedNodes){if(!(n instanceof Element))continue;if(n instanceof HTMLFormElement){D(n,e);continue}let r=n.closest("form");r instanceof HTMLFormElement&&oe.has(r)&&$e(n)&&Ht(r,e);for(let a of Array.from(n.querySelectorAll("form")))D(a,e);$e(n)&&!n.closest("form")&&Mt(e)}for(let n of o.removedNodes){if(!(n instanceof Element))continue;let r=n instanceof HTMLFormElement?[n]:Array.from(n.querySelectorAll("form"));for(let a of r)xt(a,e)}}}),F.observe(document.body,{childList:!0,subtree:!0}))}function St(e){window.addEventListener("hashchange",()=>I(e));let t={pushState:history.pushState.bind(history),replaceState:history.replaceState.bind(history)};history.pushState=function(...o){t.pushState(...o),I(e)},history.replaceState=function(...o){t.replaceState(...o),I(e)},window.addEventListener("popstate",()=>I(e))}async function I(e){let t=Array.from(document.querySelectorAll("form"));await Promise.allSettled(t.map(o=>D(o,e)))}var vt=new Set(["password","hidden","file","submit","reset","button","image"]);async function _e(e){if(!L())return;let t='[type="submit"]:not([disabled]), button[data-variant="primary"]:not([disabled])',o='[type="submit"], button[data-variant="primary"]',n=/subscribe|submit|sign[\s-]?up|send|join|go|search|post|tweet|publish|save/i,r=Array.from(document.querySelectorAll('input:not(form input), textarea:not(form textarea), select:not(form select), [role="textbox"]:not(form [role="textbox"]):not(input):not(textarea), [role="searchbox"]:not(form [role="searchbox"]):not(input):not(textarea), [contenteditable="true"]:not(form [contenteditable="true"]):not(input):not(textarea), button[role="combobox"]:not(form button[role="combobox"])')).filter(i=>{if(i instanceof HTMLInputElement&&vt.has(i.type.toLowerCase()))return console.log(`[auto-webmcp] orphan: skipping excluded type "${i.type}" (name="${i.name}" id="${i.id}")`),!1;let l=i.getBoundingClientRect();return l.width===0||l.height===0?(console.log(`[auto-webmcp] orphan: skipping invisible input (name="${i.name}" id="${i.id}")`),!1):!0});if(console.log(`[auto-webmcp] orphan: found ${r.length} visible orphan input(s)`),r.length===0)return;let a=new Map;for(let i of r){let l=i.parentElement,s=i.parentElement??document.body;for(;l&&l!==document.body;){if(l.querySelector(o)!==null||Array.from(l.querySelectorAll("button")).some(u=>n.test(u.textContent??""))){s=l;break}l=l.parentElement}console.log(`[auto-webmcp] orphan: input (name="${i.name}" id="${i.id}") grouped into container`,s),a.has(s)||a.set(s,[]),a.get(s).push(i)}console.log(`[auto-webmcp] orphan: ${a.size} group(s) found`);for(let[i,l]of a){let s=Array.from(i.querySelectorAll(t)).filter(m=>{let g=m.getBoundingClientRect();return g.width>0&&g.height>0}),c=s[s.length-1]??null;if(!c){let m=Array.from(i.querySelectorAll(o)).filter(g=>{let f=g.getBoundingClientRect();return f.width>0&&f.height>0&&g.disabled});c=m[m.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using disabled submit button as reference: "${c.textContent?.trim()}"`)}if(!c){let m=Array.from(i.querySelectorAll('button, [role="button"]')).filter(g=>{let f=g.getBoundingClientRect();return f.width>0&&f.height>0&&!g.disabled&&g.getAttribute("aria-disabled")!=="true"&&n.test(g.textContent??"")});c=m[m.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using text-matched button in container: "${c.textContent?.trim()}"`)}if(!c){let m=i.closest('[role="dialog"], [aria-modal="true"]');if(m){let g=Array.from(m.querySelectorAll('button, [role="button"]')).filter(x=>{let S=x.getBoundingClientRect();return S.width>0&&S.height>0&&n.test(x.textContent??"")});console.log("[auto-webmcp] orphan: dialog buttons matching submit text:",g.map(x=>`"${x.textContent?.trim().slice(0,30)}" disabled=${x.disabled} aria-disabled=${x.getAttribute("aria-disabled")}`));let f=g.filter(x=>x.disabled||x.getAttribute("aria-disabled")==="true"),E=g.filter(x=>!x.disabled&&x.getAttribute("aria-disabled")!=="true"),y=f.length>0?f:E;c=y[y.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using text-matched button in dialog: "${c.textContent?.trim().slice(0,40)}" disabled=${c.disabled} aria-disabled=${c.getAttribute("aria-disabled")}`)}}if(!c){let m=Array.from(document.querySelectorAll('button, [role="button"]')).filter(g=>{let f=g.getBoundingClientRect();return f.width>0&&f.height>0&&g.getAttribute("aria-disabled")!=="true"&&n.test(g.textContent??"")});c=m[m.length-1]??null,c&&console.log(`[auto-webmcp] orphan: using page-wide fallback submit button: "${c.textContent?.trim()}"`)}console.log("[auto-webmcp] orphan: submit button for group:",c?`"${c.textContent?.trim()}" disabled=${c.disabled}`:"none");let u=Le(i,l,c);console.log(`[auto-webmcp] orphan: tool="${u.name}" schema keys:`,Object.keys(u.inputSchema.properties));let d=[],p=u.inputSchema.properties,b=/^_r_[0-9a-z]+_$/i;for(let m of l){let g=m.id&&!b.test(m.id)?m.id:null,f=m.name||m.getAttribute("name")||m.dataset.webmcpName||g||m.getAttribute("aria-label")||m.getAttribute("placeholder")||null,E=f?f.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64):null,y=!!(E&&p[E]);console.log(`[auto-webmcp] orphan: field (name="${m.name??""}" id="${m.id}") rawKey="${f}" safeKey="${E}" matched=${y}`),y&&d.push({key:E,el:m})}if(console.log(`[auto-webmcp] orphan: ${d.length}/${l.length} input(s) mapped to schema keys`),d.length===0){console.log(`[auto-webmcp] orphan: skipping group "${u.name}" \u2014 no inputs mapped to schema keys`);continue}let T=u.name,w=async m=>{console.log(`[auto-webmcp] orphan execute: tool="${T}" params=`,m),console.log("[auto-webmcp] orphan execute: inputPairs=",d.map(E=>E.key));for(let{key:E,el:y}of d)m[E]!==void 0?(console.log(`[auto-webmcp] orphan execute: filling key="${E}" value=`,m[E],"element=",y),y.getAttribute("role")==="combobox"&&y.tagName.toLowerCase()==="button"?await Fe(y,m[E]):Ie(y,m[E]),console.log("[auto-webmcp] orphan execute: after fill, element value=",y.value)):console.log(`[auto-webmcp] orphan execute: key="${E}" not in params, skipping`);if(window.dispatchEvent(new CustomEvent("toolactivated",{detail:{toolName:T}})),!(e.autoSubmit||!!c?.hasAttribute("toolautosubmit")||c instanceof HTMLElement&&c.dataset.webmcpAutosubmit!==void 0||i.hasAttribute("toolautosubmit")||i instanceof HTMLElement&&i.dataset.webmcpAutosubmit!==void 0))return console.log("[auto-webmcp] orphan execute: autoSubmit=false, returning without clicking submit"),{content:[{type:"text",text:"Fields filled. Ready to submit."}]};console.log("[auto-webmcp] orphan execute: resolving submit button (up to 2s)...");let f=null;if(c&&document.contains(c)){let E=!c.disabled&&c.getAttribute("aria-disabled")!=="true",y=c.getBoundingClientRect();E&&y.width>0&&y.height>0&&(f=c,console.log(`[auto-webmcp] orphan execute: using captured submit button "${f.textContent?.trim()}"`))}if(!f){let E=Date.now()+2e3;for(;Date.now()<E;){let y=Array.from(i.querySelectorAll(t)).filter(S=>{let ie=S.getBoundingClientRect();return ie.width>0&&ie.height>0}),x=y[y.length-1]??null;if(x){f=x;break}await new Promise(S=>setTimeout(S,100))}}if(!f){let E=Array.from((i!==document.body?i:document).querySelectorAll('button, [role="button"]')).filter(y=>{let x=y.getBoundingClientRect();return x.width>0&&x.height>0&&!y.disabled&&y.getAttribute("aria-disabled")!=="true"&&n.test(y.textContent??"")});f=E[E.length-1]??null,f&&console.log(`[auto-webmcp] orphan execute: using text-matched fallback button "${f.textContent?.trim()}"`)}return f?(console.log(`[auto-webmcp] orphan execute: clicking submit button "${f.textContent?.trim()}"`),f.click(),{content:[{type:"text",text:"Fields filled and form submitted."}]}):(console.warn("[auto-webmcp] orphan execute: submit button still disabled after 2s"),{content:[{type:"text",text:"Fields filled but the submit button is still disabled. The page may require additional input before submitting."}]})};try{if(ne.has(u.name)){console.log(`[auto-webmcp] orphan: "${u.name}" already registered, skipping`);continue}let m={name:u.name,description:u.description,inputSchema:u.inputSchema,execute:w};u.annotations&&Object.keys(u.annotations).length>0&&(m.annotations=u.annotations),await navigator.modelContext.registerTool(m),ne.add(u.name);let g=window.__pendingSubmitBtns??={};g[u.name]=c,e.debug&&console.log(`[auto-webmcp] Orphan tool registered: ${u.name}`,u)}catch{}}}function Ct(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 Ne(e){document.readyState==="loading"&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),Pe=0,ne.clear(),At(e),St(e),await I(e),await _e(e)}function Be(){F?.disconnect(),F=null}O();async function qe(e){let t=ae(e);return t.debug&&console.debug("[auto-webmcp] Initializing",{webmcpSupported:L(),config:t}),await Ne(t),{destroy:async()=>{Be(),await Y()},getTools:K,isSupported:L()}}typeof window<"u"&&!window.__AUTO_WEBMCP_NO_AUTOINIT&&qe();return Ve(kt);})();
|
|
2
2
|
//# sourceMappingURL=auto-webmcp.iife.js.map
|