auto-webmcp 0.3.3 → 0.3.4
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/auto-webmcp.cjs.js +22 -4
- package/dist/auto-webmcp.cjs.js.map +2 -2
- package/dist/auto-webmcp.esm.js +22 -4
- 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/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 O=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var Y=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})},Re=(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=we(t,i))||r.enumerable});return e};var Fe=e=>Re(O({},"__esModule",{value:!0}),e);var ge={};Y(ge,{getAllRegisteredTools:()=>D,getRegisteredToolName:()=>et,isWebMCPSupported:()=>T,registerFormTool:()=>N,unregisterAll:()=>B,unregisterFormTool:()=>H});function T(){return typeof navigator<"u"&&typeof navigator.modelContext<"u"}async function N(e,t,n){if(!T())return;h.get(e)&&await H(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 H(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])=>H(t)))}var h,w=Ie(()=>{"use strict";h=new Map});var Et={};Y(Et,{autoWebMCP:()=>ve});function X(e){return{exclude:e?.exclude??[],autoSubmit:e?.autoSubmit??!1,overrides:e?.overrides??{},debug:e?.debug??!1}}var L=["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 Q(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)||Q(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(Q(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 Z(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!==""&&n!=="on")}function ee(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(r=>r.value).filter(r=>r!=="")}function te(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 ne(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(c=>(c.getAttribute("data-value")??c.textContent??"").trim()).filter(Boolean),o=i.map(c=>({const:(c.getAttribute("data-value")??c.textContent??"").trim(),title:(c.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 oe=0;function se(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 E(t);let n=e.dataset.webmcpName;if(n)return E(n);let r=$(e);if(r)return E(r);let i=ae(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_${++oe}`}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 ae(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=ae(e),c=document.title?.trim();return o&&c?`${o}: ${c}`:o||c||"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 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 le(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")),...le(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")),...le(e)];for(let l of o){let f=l.name,m=f||ce(l);if(!m)continue;if(l instanceof HTMLInputElement&&l.type==="radio"){if(i.has(m))continue;i.add(m)}if(l instanceof HTMLInputElement&&l.type==="checkbox"){if(s.has(m))continue;s.add(m)}let d=_(l);if(!d||!de(l))continue;d.title=ue(l);let p=me(l);p&&(d.description=p);let u=Ue(l);if(u!==void 0&&(d.default=u),l instanceof HTMLInputElement&&l.type==="radio"){d.enum=ee(e,m);let g=te(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(l instanceof HTMLInputElement&&l.type==="checkbox"){let g=Z(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 K=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(m)}"]:checked`)).map(Ae=>Ae.value);K.length>0&&(b.default=K),t[m]=b,l.required&&n.push(m);continue}}t[m]=d,f||r.set(m,l),l.required&&n.push(m)}let c=ze(e),a=new Set;for(let{el:l,role:f,key:m,enumValues:d,enumOneOf:p}of c){if(t[m])continue;if(f==="radio"){if(a.has(m))continue;a.add(m)}let u=ne(l,f);d&&d.length>0&&(u.enum=d,p&&p.length>0&&(u.oneOf=p)),u.title=Ge(l);let g=Ke(l);g&&(u.description=g),t[m]=u,r.set(m,l),l.getAttribute("aria-required")==="true"&&n.push(m)}return{schema:{type:"object",properties:t,required:n},fieldElements:r}}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");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=L.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 l=a.getAttribute("role"),f=re(a);f&&n.push({el:a,role:l,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 l=a.el.closest('[role="radiogroup"]');l?(s.has(l)||s.set(l,[]),s.get(l).push(a.el)):o.push(a)}let c=[];for(let[a,l]of s){let f=re(a);if(!f)continue;let m=l.map(p=>(p.getAttribute("data-value")??p.getAttribute("aria-label")??p.textContent??"").trim()).filter(Boolean),d=l.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&&c.push({el:a,role:"radio",key:f,enumValues:m,enumOneOf:d})}return[...i,...c,...o]}function re(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 ue(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 me(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=ie(n);if(r)return r}}let t=e.closest("label");if(t){let n=ie(t);if(n)return n}return""}function ie(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 de(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 fe(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=pe(e);if(n)return E(n);let r=document.title?.trim();return r?E(r):`form_${++oe}`}function Qe(e){let t=pe(e),n=document.title?.trim();return t&&n&&t!==n?`${t} on ${n}`:t||n||"Submit form"}function pe(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 c=o.name,a=c||ce(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 l=_(o);if(!l||!de(o))continue;l.title=ue(o);let f=me(o);if(f&&(l.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:l.title};l.description&&(d.description=l.description),t[a]=d,o.required&&n.push(a);continue}}t[a]=l,c||r.set(a,o),o.required&&n.push(a)}return{schema:{type:"object",properties:t,required:n},fieldElements:r}}w();var C=new WeakMap,ye=new WeakMap,k=new WeakMap,y=new WeakMap,x=new WeakMap,I=new WeakMap,tt=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set,nt=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set,M=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked")?.set;function he(e,t,n,r){return r?.fieldElements&&k.set(e,r.fieldElements),Ee(e,n),async i=>{x.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,c)=>{C.set(e,{resolve:o,reject:c}),(t.autoSubmit||e.hasAttribute("toolautosubmit")||e.dataset.webmcpAutosubmit!==void 0)&&Te(e).then(async()=>{try{W(e,i);for(let l=0;l<2&&it(e,i,k.get(e)).length!==0;l++)W(e,i),await Te(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:c}),Ee(a,n))}a!==e&&y.has(e)&&(y.set(a,y.get(e)),y.delete(e)),a.requestSubmit()}catch(a){c(a instanceof Error?a:new Error(String(a)))}})})}}function Ee(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,ye.get(e),k.get(e));I.delete(e);let o=y.get(e)??[];y.delete(e);let c=x.get(e)??[];x.delete(e);let a=c.filter(u=>u.type==="not_filled").map(u=>u.field),l={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`})),...c]},f=[...o.length?[`required fields were not filled: ${o.join(", ")}`]:[],...c.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(l)}]};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 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 R(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=R(r,t);if(s)return s}return null}function U(e,t){let n=CSS.escape(t),r=e.querySelector(`[name="${n}"]`)??e.querySelector(`input#${n}, textarea#${n}, select#${n}`);return r||(R(document,`[name="${n}"]`)??R(document,`input#${n}, textarea#${n}, select#${n}`))}function W(e,t){ye.set(e,t);let n=k.get(e),r={};for(let[i,s]of Object.entries(t)){let o=U(e,i);if(o){if(o instanceof HTMLInputElement)if(be(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(l=>l.checked).map(l=>l.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),r[i]=o.multiple?Array.from(o.options).filter(a=>a.selected).map(a=>a.value):o.value);continue}let c=n?.get(i);if(c){let a=c;if(!c.isConnected){let l=c.id;if(l){let f=document.getElementById(l)??R(document,`#${CSS.escape(l)}`);f&&(a=f)}}a instanceof HTMLInputElement?(be(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),r[i]=a.multiple?Array.from(a.options).filter(l=>l.selected).map(l=>l.value):a.value):(Me(a,s),r[i]=s)}}I.set(e,r)}function be(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 c of o)J(c,r.map(String).includes(c.value));return}J(e,!!r);return}if(i==="number"||i==="range"){let s=String(r??""),o=Number(s);if(s===""||isNaN(o)){x.get(t)?.push({field:n,type:"type_mismatch",message:`"${n}" expects a number, got: ${JSON.stringify(r)}`,original:r});return}let c=e.min!==""?parseFloat(e.min):-1/0,a=e.max!==""?parseFloat(e.max):1/0;if(o<c||o>a){let l=Math.min(Math.max(o,c),a);x.get(t)?.push({field:n,type:"clamped",message:`"${n}" value ${o} is outside allowed range [${e.min||"?"}, ${e.max||"?"}], clamped to ${l}`,original:o,actual:l}),e.value=String(l)}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 c of o)if(c.value===String(r)){M?M.call(c,!0):c.checked=!0,c.dispatchEvent(new Event("change",{bubbles:!0}));break}return}S(e,String(r??""))}function j(e,t){if(e.multiple){let n=Array.isArray(t)?t.map(String):[String(t??"")];for(let r of Array.from(e.options))r.selected=n.includes(r.value);e.dispatchEvent(new Event("change",{bubbles:!0}));return}e.value=String(t??""),e.dispatchEvent(new Event("change",{bubbles:!0}))}function Me(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 c of i)c!==s&&c.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,c]of i.entries())if(r[o]!==void 0){let a=r[o];Array.isArray(a)?a.push(c):r[o]=[a,c]}else r[o]=c;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 c=U(e,o)??n?.get(o)??null;if(c)if(c instanceof HTMLInputElement&&c.type==="checkbox")r[o]=c.checked;else if(c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)r[o]=c.value;else{let a=c.getAttribute("role");a==="checkbox"||a==="switch"?r[o]=c.getAttribute("aria-checked")==="true":r[o]=c.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):Me(e,t)}function Te(e,t=800,n=150){return new Promise(r=>{let i=!1,s=null,o=()=>{i||(i=!0,c.disconnect(),s!==null&&clearTimeout(s),r())},c=new MutationObserver(()=>{s!==null&&clearTimeout(s),s=setTimeout(o,n)});c.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=U(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 He(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=se(e,n);t.debug&>(r.name,r.description);let i=he(e,t,r.name,r);await N(e,r,i),G.add(e),z++,t.debug&&console.debug(`[auto-webmcp] Registered: ${r.name}`,r),He("form:registered",e,r.name)}async function at(e,t){let{getRegisteredToolName:n}=await Promise.resolve().then(()=>(w(),ge)),r=n(e);r&&(await H(e),G.delete(e),t.debug&&console.debug(`[auto-webmcp] Unregistered: ${r}`),He("form:unregistered",e,r))}var A=null,G=new WeakSet,z=0,V=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&&L.includes(n)||e.querySelector("input, textarea, select"))return!0;for(let r of L)if(e.querySelector(`[role="${r}"]`))return!0;return!1}function ut(e,t){let n=V.get(e);n&&clearTimeout(n),V.set(e,setTimeout(()=>{V.delete(e),F(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){F(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")))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)}}}),A.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,c=s.parentElement??document.body;for(;o&&o!==document.body;){if(o.querySelector(t)!==null||Array.from(o.querySelectorAll("button")).some(l=>n.test(l.textContent??""))){c=o;break}o=o.parentElement}i.has(c)||i.set(c,[]),i.get(c).push(s)}for(let[s,o]of i){let c=Array.from(s.querySelectorAll(t)).filter(u=>{let g=u.getBoundingClientRect();return g.width>0&&g.height>0}),a=c[c.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 l=fe(s,o,a),f=[],m=l.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=l.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:l.name,description:l.description,inputSchema:l.inputSchema,execute:p}),e.debug&&console.debug(`[auto-webmcp] Orphan tool registered: ${l.name}`,l)}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})),z=0,mt(e),dt(e),await v(e),z===0&&await pt(e)}function Se(){A?.disconnect(),A=null}w();async function ve(e){let t=X(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 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 Y=(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 ge={};Y(ge,{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={};Y(Et,{autoWebMCP:()=>ve});function X(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 Q(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)||Q(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(Q(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 Z(e,t){return Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(t)}"]`)).map(n=>n.value).filter(n=>n!==""&&n!=="on")}function ee(e,t){return Array.from(e.querySelectorAll(`input[type="radio"][name="${CSS.escape(t)}"]`)).map(r=>r.value).filter(r=>r!=="")}function te(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 ne(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 oe=0;function se(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=ae(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_${++oe}`}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 ae(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=ae(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 le(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")),...le(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")),...le(e)];for(let c of o){let f=c.name,m=f||ce(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||!de(c))continue;d.title=ue(c);let p=me(c);p&&(d.description=p);let u=Ve(c);if(u!==void 0&&(d.default=u),c instanceof HTMLInputElement&&c.type==="radio"){d.enum=ee(e,m);let g=te(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=Z(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 K=Array.from(e.querySelectorAll(`input[type="checkbox"][name="${CSS.escape(m)}"]:checked`)).map(we=>we.value);K.length>0&&(b.default=K),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=ne(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 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");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=re(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=re(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 re(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 ue(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 me(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=ie(n);if(r)return r}}let t=e.closest("label");if(t){let n=ie(t);if(n)return n}return""}function ie(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 de(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 fe(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=pe(e);if(n)return E(n);let r=document.title?.trim();return r?E(r):`form_${++oe}`}function Qe(e){let t=pe(e),n=document.title?.trim();return t&&n&&t!==n?`${t} on ${n}`:t||n||"Submit form"}function pe(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||ce(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||!de(o))continue;c.title=ue(o);let f=me(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,ye=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 he(e,t,n,r){return r?.fieldElements&&k.set(e,r.fieldElements),Ee(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)&&Te(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 Te(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}),Ee(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 Ee(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,ye.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){ye.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(be(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?(be(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):(Le(a,s),r[i]=s)}}R.set(e,r),window.__lastFillWarnings=L.get(e)??[]}function be(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 Le(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 Me(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):Le(e,t)}function Te(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 He(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=se(e,n);t.debug&>(r.name,r.description);let i=he(e,t,r.name,r);await N(e,r,i),G.add(e),z++,t.debug&&console.debug(`[auto-webmcp] Registered: ${r.name}`,r),He("form:registered",e,r.name)}async function at(e,t){let{getRegisteredToolName:n}=await Promise.resolve().then(()=>(A(),ge)),r=n(e);r&&(await x(e),G.delete(e),t.debug&&console.debug(`[auto-webmcp] Unregistered: ${r}`),He("form:unregistered",e,r))}var w=null,G=new WeakSet,z=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&&G.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=fe(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&&Me(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})),z=0,mt(e),dt(e),await v(e),z===0&&await pt(e)}function Se(){w?.disconnect(),w=null}A();async function ve(e){let t=X(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);})();
|
|
2
2
|
//# sourceMappingURL=auto-webmcp.iife.js.map
|