@nxisai/nxis 2.3.2 → 2.3.3
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/build/nxis.js +1 -1
- package/package.json +1 -1
- package/src/client.ts +5 -2
package/build/nxis.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(){const e={NXIS_API_HOST:"https://proxy.nxis.ai"};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,e)}catch(e){}globalThis.process={env:e}}();class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}var t;!function(e){e[e.OK=0]="OK",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"}(t||(t={})),t.OK,t.INVALID_ARGUMENT,t.NOT_FOUND,t.PERMISSION_DENIED,t.RESOURCE_EXHAUSTED,t.INTERNAL,t.UNAUTHENTICATED;class n extends Error{constructor(e,t,o){super(o),this.code=e,this.httpStatus=t,this.name="ProxyError",Object.setPrototypeOf(this,n.prototype)}get isRetryable(){return this.code===t.RESOURCE_EXHAUSTED||this.code===t.INTERNAL}get isAuthError(){return this.code===t.UNAUTHENTICATED||this.code===t.PERMISSION_DENIED}static fromResponse(e,t){return new n(t.code,e,t.message)}}var o,r,i=function(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n},a=function(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)};class s extends Event{constructor(e,t={}){super(e,t),o.set(this,void 0),i(this,o,`${t.toolName??""}`,"f")}get toolName(){return a(this,o,"f")}}o=new WeakMap;class l extends Event{constructor(e,t={}){super(e,t),r.set(this,void 0),i(this,r,`${t.toolName??""}`,"f")}get toolName(){return a(this,r,"f")}}r=new WeakMap;var u,c,d,f,p,m,h,v,g,w,y=function(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)};const b=/^[A-Za-z0-9_.-]{1,128}$/;function E(e,t){return"function"==typeof DOMException?new DOMException(e,t):Object.assign(new Error(e),{name:t})}function T(e){setTimeout(e,0)}function x(e){return`${e}`}function N(e){const t=x(e);return"function"==typeof t.toWellFormed?t.toWellFormed():t.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"�")}function A(e){return"object"==typeof e&&null!==e||"function"==typeof e}function $(e){const t=JSON.stringify(e);if(void 0===t)throw new TypeError("The value cannot be serialized as JSON.");return t}function S(e,t){if(null==e)return{};if(!A(e))throw new TypeError(`The provided value is not of type '${t}'.`);return e}function j(e,t,n){const o=e[t];if(void 0===o)throw new TypeError(`Failed to read the '${t}' property from '${n}': Required member is undefined.`);return o}function C(e){const t=S(e,"ToolAnnotations"),n=e=>void 0!==t[e]&&Boolean(t[e]);return{consequentialHint:n("consequentialHint"),debugging:n("debugging"),readOnlyHint:n("readOnlyHint"),untrustedContentHint:n("untrustedContentHint")}}function O(e,t){if(void 0!==e){if("function"==typeof AbortSignal&&!(e instanceof AbortSignal))throw new TypeError(`Failed to read the 'signal' property from '${t}': The provided value is not of type 'AbortSignal'.`);return e}}function k(e,t,n){if(void 0!==e){if(!A(e)||"function"!=typeof e[Symbol.iterator])throw new TypeError(`Failed to read the '${t}' property from '${n}': The provided value cannot be converted to a sequence.`);return[...e].map(N)}}function L(e){const t="RegisteredTool",n=S(e,t);if(void 0!==n.annotations&&C(n.annotations),x(j(n,"description",t)),void 0!==n.inputSchema&&!A(n.inputSchema))throw new TypeError(`Failed to read the 'inputSchema' property from '${t}': The provided value is not of type 'object'.`);const o=x(j(n,"name",t)),r=N(j(n,"origin",t));void 0!==n.title&&x(n.title);const i=j(n,"window",t);if(!function(e){return"undefined"==typeof window?e===globalThis:A(e)&&e.window===e}(i))throw new TypeError(`Failed to read the 'window' property from '${t}': The provided value is not of type 'Window'.`);return{name:o,origin:r,window:i}}function M(){return"undefined"!=typeof window?window:globalThis}function P(){return"undefined"!=typeof location?location.origin:"http://localhost"}function I(e){return e.map(e=>{let t;try{t=new URL(e)}catch{throw E(`"${e}" is not a valid origin.`,"SecurityError")}if(!function(e){if("null"===e.origin)return!1;if("https:"===e.protocol||"wss:"===e.protocol)return!0;const t=e.hostname;return!("localhost"!==t&&!t.endsWith(".localhost"))||/^127(?:\.\d{1,3}){3}$/.test(t)||"[::1]"===t}(t))throw E(`"${e}" is not a potentially trustworthy origin.`,"SecurityError");return t.origin})}function R(){const e=globalThis,t="undefined"!=typeof location?location.protocol:"";return!1===e.originAgentCluster&&"file:"!==t?E("This page's agent cluster is not origin-keyed.","SecurityError"):function(){if("undefined"==typeof document)return!0;const e=document,t=e.permissionsPolicy??e.featurePolicy;if(!t?.features||!t.allowsFeature)return!0;try{return!t.features().includes("tools")||t.allowsFeature("tools")}catch{return!0}}()?null:E("The 'tools' permissions policy does not allow this document to use tools.","NotAllowedError")}class U extends EventTarget{constructor(){super(...arguments),u.add(this),c.set(this,new Map),d.set(this,new Map),f.set(this,{}),p.set(this,{})}get ontoolchange(){return y(this,f,"f").toolchange??null}set ontoolchange(e){y(this,u,"m",w).call(this,"toolchange",e)}get ontoolactivated(){return y(this,f,"f").toolactivated??null}set ontoolactivated(e){y(this,u,"m",w).call(this,"toolactivated",e)}get ontoolcancel(){return y(this,f,"f").toolcancel??null}set ontoolcancel(e){y(this,u,"m",w).call(this,"toolcancel",e)}registerTool(e,t={}){let n,o,r;try{n=function(e){const t="ModelContextTool",n=S(e,t),o=void 0===n.annotations?void 0:C(n.annotations),r=x(j(n,"description",t)),i=j(n,"execute",t);if("function"!=typeof i)throw new TypeError(`Failed to read the 'execute' property from '${t}': The provided value is not a function.`);const a=n.inputSchema;if(void 0!==a&&!A(a))throw new TypeError(`Failed to read the 'inputSchema' property from '${t}': The provided value is not of type 'object'.`);return{annotations:o,description:r,execute:i,inputSchema:a,name:x(j(n,"name",t)),title:void 0===n.title?void 0:N(n.title)}}(e);const i=S(t,"ModelContextRegisterToolOptions");r=k(i.exposedTo,"exposedTo","ModelContextRegisterToolOptions"),o=O(i.signal,"ModelContextRegisterToolOptions")}catch(e){return Promise.reject(e)}const i=R();if(i)return Promise.reject(i);const a=n.name;if(y(this,c,"f").has(a))return Promise.reject(E(`A tool named "${a}" is already registered.`,"InvalidStateError"));if(!b.test(a))return Promise.reject(E(`"${a}" is not a valid tool name: 1 to 128 ASCII letters, digits, "_", "-" or ".".`,"InvalidStateError"));if(""===n.description)return Promise.reject(E("A tool's description must not be empty.","InvalidStateError"));let s="";if(void 0!==n.inputSchema)try{s=$(n.inputSchema)}catch(e){return Promise.reject(e)}if(o?.aborted)return Promise.reject(o.reason);let l,d=[];if(r)try{d=I(r)}catch(e){return Promise.reject(e)}const f=new Promise((e,t)=>l={resolve:e,reject:t});if(o){const e=o;e.addEventListener("abort",()=>{y(this,u,"m",v).call(this,a),l.reject(e.reason)},{once:!0})}return y(this,c,"f").set(a,{name:a,title:n.title??null,description:n.description,inputSchema:s,annotations:void 0===n.annotations?null:C(n.annotations),exposedOrigins:d,tool:n}),y(this,u,"m",g).call(this),T(()=>l.resolve()),f}getTools(e={}){let t;try{t=k(S(e,"ModelContextGetToolOptions").fromOrigins,"fromOrigins","ModelContextGetToolOptions")}catch(e){return Promise.reject(e)}const n=R();if(n)return Promise.reject(n);if(t)try{I(t)}catch(e){return Promise.reject(e)}return new Promise(e=>{const t=P(),n=M(),o=[...y(this,c,"f").values()].map(e=>{const o={};return e.annotations&&(o.annotations={...e.annotations}),o.description=e.description,""!==e.inputSchema&&(o.inputSchema=JSON.parse(e.inputSchema)),o.name=e.name,o.origin=t,o.title=e.title??"",o.window=n,o});o.sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0),T(()=>e(o))})}executeTool(e,t,n={}){let o,r;try{o=L(e),r=O(S(n,"ModelContextExecuteToolOptions").signal,"ModelContextExecuteToolOptions")}catch(e){return Promise.reject(e)}const i=R();if(i)return Promise.reject(i);let a,s,l;try{a=new URL(o.origin).origin}catch{return Promise.reject(E(`"${o.origin}" is not a valid origin.`,"NotSupportedError"))}if("null"===a)return Promise.reject(E("A tool's origin must not be opaque.","NotSupportedError"));if(!A(t))return Promise.reject(new TypeError("Failed to execute 'executeTool' on 'ModelContext': The input is not an object."));try{s=$(t)}catch(e){return Promise.reject(e)}const f=new Promise((e,t)=>l={resolve:e,reject:t}),p=Symbol("tool execution");if(r){if(r.aborted)return Promise.reject(r.reason);const e=r;e.addEventListener("abort",()=>{l.reject(e.reason),T(()=>y(this,u,"m",h).call(this,p))},{once:!0})}const v=()=>T(()=>l.reject(E("The tool could not be executed.","UnknownError")));return T(()=>{if(o.window!==M()||P()!==a)return v();if(!y(this,c,"f").has(o.name))return v();const e={toolName:o.name,controller:new AbortController,started:!1,complete:(e,t)=>{y(this,d,"f").has(p)&&(y(this,d,"f").delete(p),T(()=>t?l.resolve(e):l.reject(E("The tool's execution failed.","UnknownError"))))}};y(this,d,"f").set(p,e),T(()=>y(this,u,"m",m).call(this,o.name,s,e))}),f}}function _(e,t){e in globalThis||Object.defineProperty(globalThis,e,{value:t,writable:!0,enumerable:!1,configurable:!0})}c=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,u=new WeakSet,m=function(e,t,n){const o=y(this,c,"f").get(e);if(!o)return n.complete(null,!1);let r;try{r=JSON.parse(t)}catch{return n.complete(null,!1)}if(!A(r))return n.complete(null,!1);this.dispatchEvent(new s("toolactivated",{toolName:o.name})),n.started=!0;const i={signal:n.controller.signal};let a;try{a=Promise.resolve(o.tool.execute.call(void 0,r,i))}catch(e){a=Promise.reject(e)}a.then(e=>{if(!n.started)return;let t;n.started=!1;try{t=$(e)}catch{return n.complete(null,!1)}n.complete(t,!0)},()=>{n.started&&(n.started=!1,n.complete(null,!1))})},h=function(e){const t=y(this,d,"f").get(e);t&&(y(this,d,"f").delete(e),T(()=>{t.started&&(t.started=!1,t.controller.abort(),this.dispatchEvent(new l("toolcancel",{toolName:t.toolName})))}))},v=function(e){y(this,c,"f").delete(e)&&y(this,u,"m",g).call(this)},g=function(){T(()=>this.dispatchEvent(new Event("toolchange")))},w=function(e,t){const n="function"==typeof t?t:null;if(y(this,f,"f")[e]=n,n&&!y(this,p,"f")[e]){const t=t=>{const n=y(this,f,"f")[e];n&&!1===n.call(this,t)&&t.preventDefault()};y(this,p,"f")[e]=t,this.addEventListener(e,t)}else!n&&y(this,p,"f")[e]&&(this.removeEventListener(e,y(this,p,"f")[e]),delete y(this,p,"f")[e])};const D=["AskAction","SearchAction","SubscribeAction","RegisterAction","BuyAction","OrderAction","AddAction","ScheduleAction","ReserveAction","RsvpAction","ApplyAction","QuoteAction","DownloadAction","ReviewAction","CommentAction","TrackAction","CommunicateAction","InteractAction"];const V="https://nxis.ai/ns#";function F(e,t,n){var o;return null!==(o=e[t])&&void 0!==o?o:e[n]}function H(e,t){return F(e,t,"https://schema.org/"+t)}function W(e,t){const n=H(e,t);return"string"==typeof n?n:null}function q(e,t,n){const o=F(e,t,n);return Array.isArray(o)?o:[]}function z(e){if(Array.isArray(e)){const t=[];for(const n of e)t.push(...z(n));return t}if(e&&"object"==typeof e){const t=e;if(Array.isArray(t["@graph"])){const e=[];for(const n of t["@graph"])e.push(...z(n));return e}return[t]}return[]}function G(e){var t;if(!e||"object"!=typeof e)return null;const n=e,o="string"==typeof n["@type"]?n["@type"]:null;if(!o)return null;if(!o.endsWith("Action")&&!function(e){return D.includes(e)}(o))return null;const r="string"==typeof n["@id"]?n["@id"]:null,i=W(n,"name"),a=function(e){var t,n;if(!e||"object"!=typeof e)return null;const o=e,r=null!==(n=null===(t=W(o,"httpMethod"))||void 0===t?void 0:t.toUpperCase())&&void 0!==n?n:null;if(!r)return null;const i={"@type":"EntryPoint",httpMethod:r},a=W(o,"encodingType");null!==a&&(i.encodingType=a);const s=W(o,"urlTemplate");null!==s&&(i.urlTemplate=s);const l=F(o,"nxis:targetKind",V+"targetKind");"selfPage"!==l&&"clientSide"!==l||(i["nxis:targetKind"]=l);const u=F(o,"nxis:pageUrl",V+"pageUrl");"string"==typeof u&&(i["nxis:pageUrl"]=u);const c=F(o,"nxis:jsHandled",V+"jsHandled");!0===c&&(i["nxis:jsHandled"]=!0);return i}(H(n,"target"));if(!r||!i||!a)return null;const s=q(n,"nxis:input",V+"input").map(X).filter(e=>null!==e),l=null!==(t=W(n,"description"))&&void 0!==t?t:function(e,t,n){const o=e.replace(/^.*[/#]/,"").replace(/Action$/,"").toLowerCase(),r=n.map(e=>e.valueName).join(", ");if(0===n.length)return`Trigger the ${o} action "${t}".`;return`Fill the ${o} form "${t}" with fields: ${r}.`}(o,i,s);return{"@context":n["@context"],"@type":o,"@id":r,name:i,description:l,target:a,input:s.length>0?s:void 0,"nxis:extractedAt":F(n,"nxis:extractedAt",V+"extractedAt")}}function X(e){if(!e||"object"!=typeof e)return null;const t=e,n=W(t,"valueName");if(!n)return null;const o=F(t,"nxis:valueType",V+"valueType"),r={"@type":"PropertyValueSpecification",valueName:n,"nxis:valueType":"string"==typeof o?o:"string"},i=W(t,"description");null!==i&&(r.description=i),!0===H(t,"valueRequired")&&(r.valueRequired=!0);const a=W(t,"defaultValue");null!==a&&(r.defaultValue=a);const s=e=>{const n=H(t,e);return"number"==typeof n?n:null},l=s("valueMinLength");null!==l&&(r.valueMinLength=l);const u=s("valueMaxLength");null!==u&&(r.valueMaxLength=u);const c=s("minValue");null!==c&&(r.minValue=c);const d=s("maxValue");null!==d&&(r.maxValue=d);const f=s("stepValue");null!==f&&(r.stepValue=f);const p=W(t,"valuePattern");null!==p&&(r.valuePattern=p),!0===H(t,"multipleValues")&&(r.multipleValues=!0),!0===H(t,"readonlyValue")&&(r.readonlyValue=!0);const m=q(t,"nxis:valueOption",V+"valueOption");if(m.length>0){const e=m.filter(e=>e&&"object"==typeof e&&null!==W(e,"value")).map(e=>{var t;const n=e;return{"@type":"nxis:ValueOption",value:W(n,"value"),name:null!==(t=W(n,"name"))&&void 0!==t?t:void 0}});e.length>0&&(r["nxis:valueOption"]=e)}return r}function J(e){switch(e){case"string":case"date":case"file":default:return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean"}}function B(e){var t;const n={},o=[],r=null!==(t=e.input)&&void 0!==t?t:[];for(const e of r){const t=K(e);if(e.multipleValues){const o={type:"array",items:t};void 0!==e.valueMinLength&&(o.minItems=e.valueMinLength,delete t.minLength),void 0!==e.valueMaxLength&&(o.maxItems=e.valueMaxLength,delete t.maxLength),e.description&&(o.description=e.description,delete t.description),n[e.valueName]=o}else n[e.valueName]=t;e.valueRequired&&o.push(e.valueName)}const i={type:"object",properties:n};return o.length>0&&(i.required=o),i}function K(e){const t={type:J(e["nxis:valueType"])},n=function(e){if("date"===e)return"date"}(e["nxis:valueType"]);if(n&&(t.format=n),e.description&&(t.description=e.description),void 0!==e.defaultValue&&(t.default=function(e,t){switch(t){case"number":case"integer":{const t=Number(e);return isNaN(t)?e:t}case"boolean":return"true"===e||"1"===e;default:return e}}(e.defaultValue,e["nxis:valueType"])),void 0!==e.valueMinLength&&(t.minLength=e.valueMinLength),void 0!==e.valueMaxLength&&(t.maxLength=e.valueMaxLength),e.valuePattern){const n=e.valuePattern,o=n.startsWith("^")&&n.endsWith("$")?n:`^${n}$`;t.pattern=o}void 0!==e.minValue&&(t.minimum=e.minValue),void 0!==e.maxValue&&(t.maximum=e.maxValue),void 0!==e.stepValue&&(t.multipleOf=e.stepValue),e.readonlyValue&&(t.readOnly=!0);const o=e["nxis:valueOption"];if(o&&o.length>0){t.enum=o.map(e=>e.value);if(o.some(e=>void 0!==e.name&&e.name!==e.value)){const e=o.filter(e=>e.name&&e.name!==e.value).map(e=>`${e.value} = "${e.name}"`).join(", "),n=t.description?`${t.description}. `:"";t.description=`${n}Values: ${e}`}}return t}function Q(e){const t=Array.from(document.querySelectorAll("form"));if(0===t.length)return null;const n=function(e){return e.input?e.input.map(e=>e.valueName):[]}(e);let o;if(o=!e.target.urlTemplate?t:function(e,t,n){const o=function(e){const t=e.replace(/\{[^}]*\}/g,"");try{return new URL(t,window.location.href)}catch(e){return null}}(t);return e.filter(e=>{if((e.method||"GET").toUpperCase()!==n.toUpperCase())return!1;if(!o)return!0;const t=function(e){const t=e.getAttribute("action");if(!t||"#"===t||t.startsWith("#")||""===t)return window.location.href.split("#")[0].split("?")[0];if(t.startsWith("javascript:"))return window.location.href.split("#")[0].split("?")[0];try{return new URL(t,window.location.href).href}catch(e){return t}}(e);return function(e,t){let n;try{n=new URL(e,window.location.href)}catch(e){return!1}if(n.origin!==t.origin)return!1;const o=n.pathname.replace(/\/+$/,""),r=t.pathname.replace(/\/+$/,"");return""===r||(o===r||o.startsWith(r+"/")||r.startsWith(o+"/"))}(t,o)})}(t,e.target.urlTemplate,e.target.httpMethod),0===o.length&&(o=t),1===o.length)return o[0];const r=o.map(e=>({form:e,controlNames:Z(e)})).filter(({controlNames:e})=>n.every(t=>e.has(t)));return 0===r.length?(console.warn(`[nxis/webmcp] No field-set match for action "${e.name}". Expected fields: [${n.join(", ")}]. Falling back to first candidate.`),o[0]):1===r.length?r[0].form:(r.sort((e,t)=>e.controlNames.size-t.controlNames.size),r[0].controlNames.size===r[1].controlNames.size?(console.warn(`[nxis/webmcp] Ambiguous form match for action "${e.name}". ${r.length} forms have identical field sets. Returning null.`),null):r[0].form)}function Z(e){const t=new Set,n=e.elements;for(let e=0;e<n.length;e++){const o=n[e];o.name&&t.add(o.name)}return t}function Y(e,t){var n;return(null!==(n=e.input)&&void 0!==n?n:[]).map(e=>function(e,t){var n;const o=t=>({valueName:e.valueName,pvs:e,strategy:t}),r=function(e,t){const n=[],o=e.elements;for(let e=0;e<o.length;e++){const r=o[e];r.name===t&&n.push(r)}return n}(t,e.valueName),i=null!==(n=r[0])&&void 0!==n?n:null;if(!i)return o({kind:"skip",reason:`No control found with name="${e.valueName}"`});if(i instanceof HTMLInputElement&&"radio"===i.type){const t=r.filter(e=>e instanceof HTMLInputElement&&"radio"===e.type&&!e.disabled);return 0===t.length?o({kind:"skip",reason:`Radio group "${e.valueName}" has no enabled options`}):o({kind:"radio",name:e.valueName,elements:t})}if(i instanceof HTMLInputElement&&"checkbox"===i.type){const t=r.filter(e=>e instanceof HTMLInputElement&&"checkbox"===e.type&&!e.disabled);return 0===t.length?o({kind:"skip",reason:`Checkbox "${e.valueName}" is disabled`}):t.length>1?o({kind:"checkboxGroup",name:e.valueName,elements:t}):o({kind:"checked",element:t[0]})}if(!0===i.readOnly||null!==i.getAttribute("readonly"))return o({kind:"skip",reason:`Control "${e.valueName}" is readonly in the DOM`});if(i.disabled)return o({kind:"skip",reason:`Control "${e.valueName}" is disabled`});if(i instanceof HTMLSelectElement){const e=[];for(let t=0;t<i.options.length;t++){const n=i.options[t];n.value&&e.push(n.value)}return o(i.multiple?{kind:"multiSelect",element:i,allowedValues:e}:{kind:"select",element:i,allowedValues:e})}if(i instanceof HTMLTextAreaElement)return o({kind:"value",element:i});if(i instanceof HTMLInputElement)return o({kind:"value",element:i});return o({kind:"skip",reason:`Unsupported control type for "${e.valueName}"`})}(e,t))}async function ee(e,t){var n,o;const r=function(e){const t=e.target["nxis:pageUrl"];if(!t)return null;try{const n=new URL(t),o=new URL(window.location.href);if(n.origin!==o.origin||n.pathname!==o.pathname)return`Action "${e.name}" was extracted from ${n.origin}${n.pathname} but the current page is ${o.origin}${o.pathname}. The form may have moved or changed.`}catch(e){return null}return null}(e),i=Q(e);if(!i){const t=`Form not found for action "${e.name}". The page may have changed since the tool was registered.`,n={success:!1,submitted:!1,message:r?`Warning: ${r} ${t}`:t,filled:[],skipped:[]};return r&&(n.stale=!0),n}const a=Y(e,i),s=null!==(n=e.input)&&void 0!==n?n:[],l=[],u=[];let c=!1;for(const e of s)!e.valueRequired||void 0!==t[e.valueName]&&null!==t[e.valueName]||(c=!0,u.push({field:e.valueName,reason:`Required field '${e.valueName}' was not provided. Expected type: ${e["nxis:valueType"]}.`}));for(const e of a){const n=t[e.valueName];if(null==n){u.some(t=>t.field===e.valueName)||u.push({field:e.valueName,reason:"No value provided (optional field)."});continue}const o=ne(e,n);!1===o.ok?u.push({field:e.valueName,reason:o.reason}):l.push(e.valueName)}await new Promise(e=>setTimeout(e,0));for(const e of a)if("value"===e.strategy.kind&&l.includes(e.valueName)){const n=e.strategy.element,r=oe(null!==(o=t[e.valueName])&&void 0!==o?o:"");n.value!==r&&(u.push({field:e.valueName,reason:`Value was set to "${r}" but the DOM now shows "${n.value}". A framework may have reverted it.`}),l.splice(l.indexOf(e.valueName),1))}const d=l.length>0&&!c;let f=!1;d&&(f=function(e){try{return"function"==typeof e.requestSubmit?e.requestSubmit():e.submit(),!0}catch(e){return console.warn("[nxis/webmcp] Form submission failed:",e),!1}}(i));const p={success:d,submitted:f,message:te(l,u,f,r),filled:l,skipped:u};return r&&(p.stale=!0),p}function te(e,t,n,o){const r=[];if(o&&r.push(`Warning: ${o}`),0===e.length&&0===t.length)return r.push("No fields were filled. Verify field names match the input schema."),r.join(" ");if(e.length>0&&r.push(`Filled ${e.length} field(s): ${e.join(", ")}.`),t.length>0){const e=t.map(e=>`${e.field} (${e.reason})`).join("; ");r.push(`Skipped ${t.length}: ${e}`)}return n?r.push("Form submitted."):e.length>0&&r.push("Form was NOT submitted due to missing required fields or fill errors."),r.join(" ")}function ne(e,t){const{strategy:n}=e;switch(n.kind){case"skip":return{ok:!1,reason:n.reason};case"value":return function(e,t){var n;const o=null===(n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))||void 0===n?void 0:n.set;o?o.call(e,t):e.value=t;return e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.element,oe(t));case"checked":return function(e,t){return e.checked=function(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){const t=e.trim().toLowerCase();return""!==t&&"false"!==t&&"0"!==t&&"off"!==t&&"no"!==t}return Boolean(e)}(t),e.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.element,t);case"radio":return function(e,t){var n,o;const r=String(t),i=null!==(o=null!==(n=e.find(e=>e.value===r))&&void 0!==n?n:e.find(e=>e.value.toLowerCase()===r.toLowerCase()))&&void 0!==o?o:e.find(e=>function(e){var t;if(e.labels&&e.labels.length>0)return(null!==(t=e.labels[0].textContent)&&void 0!==t?t:"").trim();return e.value}(e).toLowerCase()===r.toLowerCase());if(!i){const t=e.map(e=>e.value).join(", ");return{ok:!1,reason:`Value "${r}" is not an allowed option for radio "${e[0].name}". Allowed: [${t}].`}}return i.checked=!0,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.elements,t);case"checkboxGroup":return function(e,t){const n=(Array.isArray(t)?t:[t]).map(e=>String(e)),o=n.map(e=>e.toLowerCase());let r=!1;for(const t of e){const e=n.includes(t.value)||o.includes(t.value.toLowerCase());t.checked=e,e&&(r=!0),t.dispatchEvent(new Event("change",{bubbles:!0}))}if(!r){const t=e.map(e=>e.value).join(", ");return{ok:!1,reason:`None of [${n.join(", ")}] match checkbox group "${e[0].name}". Allowed: [${t}].`}}return{ok:!0}}(n.elements,t);case"select":return function(e,t,n){const o=re(e,t,n);if(null===o)return{ok:!1,reason:`Value "${t}" is not an allowed option for "${e.name}". Allowed: [${n.join(", ")}].`};return e.value=o,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.element,String(t),n.allowedValues);case"multiSelect":return function(e,t,n){const o=(Array.isArray(t)?t:[t]).map(e=>String(e)),r=new Set,i=[];for(const t of o){const o=re(e,t,n);null===o?i.push(t):r.add(o)}if(0===r.size)return{ok:!1,reason:`None of [${o.join(", ")}] are allowed options for "${e.name}". Allowed: [${n.join(", ")}].`};for(const t of Array.from(e.options))t.selected=r.has(t.value);if(e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),i.length>0)return{ok:!1,reason:`Selected [${Array.from(r).join(", ")}] but [${i.join(", ")}] are not allowed options for "${e.name}". Allowed: [${n.join(", ")}].`};return{ok:!0}}(n.element,t,n.allowedValues);default:return{ok:!1,reason:`Unsupported fill strategy for field "${e.valueName}".`}}}function oe(e){return Array.isArray(e)?e.map(e=>String(e)).join(","):String(e)}function re(e,t,n){if(n.includes(t))return t;const o=n.find(e=>e.toLowerCase()===t.toLowerCase());if(o)return o;for(const n of Array.from(e.options))if(n.text.toLowerCase()===t.toLowerCase())return n.value;return null}function ie(e){var t;const n=!1!==(null==e?void 0:e.observe),o=null!==(t=null==e?void 0:e.doc)&&void 0!==t?t:"undefined"!=typeof document?document:void 0;if(!o)return console.warn("[nxis/webmcp] No document available (not running in a browser). Tools will not be registered."),()=>{};!function(e={}){const{force:t=!1,installNavigatorAlias:n=!1}=e,o="undefined"!=typeof document&&document.modelContext||"undefined"!=typeof navigator&&navigator.modelContext||void 0;if(o&&!t)return o;if(!1===globalThis.isSecureContext)return;let r;if(_("ModelContext",U),_("ToolActivatedEvent",s),_("ToolCancelEvent",l),"undefined"!=typeof document){const e=globalThis.Document;if(e&&document instanceof e){const t=new WeakMap;Object.defineProperty(e.prototype,"modelContext",{get(){if(!(this instanceof e))throw new TypeError("Illegal invocation");let n=t.get(this);return n||t.set(this,n=new U),n},enumerable:!0,configurable:!0}),Object.prototype.hasOwnProperty.call(document,"modelContext")&&delete document.modelContext}else Object.defineProperty(document,"modelContext",{value:new U,writable:!1,enumerable:!0,configurable:!0});r=document.modelContext}else r=new U;n&&"undefined"!=typeof navigator&&Object.defineProperty(navigator,"modelContext",{value:r,writable:!1,enumerable:!0,configurable:!0})}();const r=function(e){var t,n;const o=null!==(n=null===(t=e.defaultView)||void 0===t?void 0:t.navigator)&&void 0!==n?n:"undefined"!=typeof navigator?navigator:void 0;return e.modelContext||(null==o?void 0:o.modelContext)||null}(o);if(!r)return console.warn("[nxis/webmcp] WebMCP API not available — document.modelContext is undefined. Tools will not be registered."),()=>{};const i=new AbortController;(null==e?void 0:e.signal)&&(e.signal.aborted?i.abort():e.signal.addEventListener("abort",()=>i.abort()));const a={ids:new Set,names:new Set};ae(o,r,i,a);let u=null;return n&&(u=function(e,t,n,o){const r=new MutationObserver(r=>{(function(e){for(const t of e)for(const e of Array.from(t.addedNodes)){if(se(e))return!0;if(e instanceof Element&&e.querySelector('script[type="application/ld+json"]'))return!0}return!1})(r)&&ae(e,t,n,o)});return n.signal.addEventListener("abort",()=>r.disconnect()),r.observe(e.documentElement,{childList:!0,subtree:!0}),r}(o,r,i,a)),()=>{i.abort(),u&&(u.disconnect(),u=null)}}async function ae(e,t,n,o){const r=function(e=("undefined"!=typeof document?document:void 0)){const t=[];if(!e)return t;const n=e.querySelectorAll('script[type="application/ld+json"]');for(const e of Array.from(n)){const n=e.textContent;if(!n)continue;let o;try{o=JSON.parse(n)}catch(e){continue}const r=z(o);for(const e of r){const n=G(e);n&&t.push(n)}}return t}(e).filter(e=>!o.ids.has(e["@id"])),i=await Promise.all(r.map(e=>async function(e,t,n,o){const r=function(e,t){if(!t.has(e))return e;for(let n=2;;n++){const o=`_${n}`,r=e.slice(0,64-o.length)+o;if(!t.has(r))return r}}(function(e){return e.toLowerCase().replace(/[\s-]+/g,"_").replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").slice(0,64)||"unnamed_action"}(e.name),o.names);o.ids.add(e["@id"]),o.names.add(r);try{const o={name:r,description:e.description||`Fill in and submit the "${e.name}" form.`,inputSchema:B(e),annotations:{readOnlyHint:!1,untrustedContentHint:!0,"ai.nxis/actionId":e["@id"]},execute:t=>ee(e,t)};return await t.registerTool(o,{signal:n.signal}),!0}catch(t){return n.signal.aborted||(o.ids.delete(e["@id"]),o.names.delete(r),console.warn(`[nxis/webmcp] Failed to register tool for action "${e.name}":`,t)),!1}}(e,t,n,o))),a=i.filter(Boolean).length;a>0&&console.info(`[nxis/webmcp] Registered ${a} tool(s) (${o.ids.size} total) from ${r.length} new action(s).`)}function se(e){return e instanceof HTMLScriptElement&&"application/ld+json"===e.type}const le=["nxis_handoff","nxis_intent"];function ue(e){const t=new URL(e);if(!t.search)return t;const n=t.search.slice(1).split("&").filter(e=>!le.includes(function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}}(e.split("=")[0])));return t.search=n.length?`?${n.join("&")}`:"",t}function ce(t){t instanceof e?console.warn(JSON.parse(t.message).message):console.error(`Unable to retrieve structured data for ${window.location.href}`)}!function(){var t,o;const r=window.__NXIS_CONFIG__,i=null!==(o=null===(t=null==r?void 0:r.webmcp)||void 0===t?void 0:t.mode)&&void 0!==o?o:"browser";if("ssr"===i)return void ie();const a=process.env.NXIS_API_HOST,s=new Headers,l=new URL(`${a}/v1/nxis:inject`);l.search=function(e){var t,n;const o=new URLSearchParams;return(null===(t=e.organization_id)||void 0===t?void 0:t.value)&&o.append("organization_id",e.organization_id.value),(null===(n=e.site_id)||void 0===n?void 0:n.value)&&o.append("site_id",e.site_id.value),o.append("uri",e.uri.href),e.referrer&&o.append("referrer",e.referrer),o}({organization_id:{value:null==r?void 0:r.org_id},site_id:{value:null==r?void 0:r.site_id},uri:ue(window.location.href),referrer:document.referrer}).toString(),(null==r?void 0:r.sub_id)&&s.set("X-NXIS-SUBSCRIPTION",r.sub_id),s.set("Content-Type","application/json"),s.set("User-Agent",navigator.userAgent),fetch(`${l}`,{headers:s}).then(t=>async function(t,o){const r=null!=o?o:"unknown";if(200===t.status){const n=await t.json();if((null==n?void 0:n.data)&&Object.keys(n.data).length>0)return n;throw new e(JSON.stringify({message:`No Nxis resource found for ${r}`}))}const i=await async function(e){try{return await e.json()}catch(e){return null}}(t);if(void 0!==(null==i?void 0:i.code)&&(null==i?void 0:i.message))throw n.fromResponse(t.status,i);switch(t.status){case 500:throw new n(13,500,"An internal server error occurred, please contact technical support.");case 502:throw new n(13,502,"An internal server error occurred, please contact technical support.");case 503:throw new n(8,503,"Service is temporarily unavailable, please try again later.");default:throw new n(13,t.status,`Unexpected response status: ${t.status}`)}}(t,window.location.href)).then(e=>{!function(e){if(e.data&&Object.keys(e.data).length>0){const t=document.createComment("Nxis.ai"),n=document.createComment("End Nxis.ai"),o=document.createElement("script");o.setAttribute("type","application/ld+json"),o.textContent=JSON.stringify(e.data),document.head.appendChild(o),o.before(t),o.after(n)}}(e),"browser"===i&&ie()}).catch(ce)}();
|
|
1
|
+
!function(){const e={NXIS_API_HOST:"https://proxy.nxis.ai"};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,e)}catch(e){}globalThis.process={env:e}}();class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}var t;!function(e){e[e.OK=0]="OK",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"}(t||(t={})),t.OK,t.INVALID_ARGUMENT,t.NOT_FOUND,t.PERMISSION_DENIED,t.RESOURCE_EXHAUSTED,t.INTERNAL,t.UNAUTHENTICATED;class n extends Error{constructor(e,t,o){super(o),this.code=e,this.httpStatus=t,this.name="ProxyError",Object.setPrototypeOf(this,n.prototype)}get isRetryable(){return this.code===t.RESOURCE_EXHAUSTED||this.code===t.INTERNAL}get isAuthError(){return this.code===t.UNAUTHENTICATED||this.code===t.PERMISSION_DENIED}static fromResponse(e,t){return new n(t.code,e,t.message)}}var o,r,i=function(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n},a=function(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)};class s extends Event{constructor(e,t={}){super(e,t),o.set(this,void 0),i(this,o,`${t.toolName??""}`,"f")}get toolName(){return a(this,o,"f")}}o=new WeakMap;class l extends Event{constructor(e,t={}){super(e,t),r.set(this,void 0),i(this,r,`${t.toolName??""}`,"f")}get toolName(){return a(this,r,"f")}}r=new WeakMap;var u,c,d,f,p,m,h,v,g,w,y=function(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)};const b=/^[A-Za-z0-9_.-]{1,128}$/;function E(e,t){return"function"==typeof DOMException?new DOMException(e,t):Object.assign(new Error(e),{name:t})}function T(e){setTimeout(e,0)}function x(e){return`${e}`}function N(e){const t=x(e);return"function"==typeof t.toWellFormed?t.toWellFormed():t.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"�")}function A(e){return"object"==typeof e&&null!==e||"function"==typeof e}function $(e){const t=JSON.stringify(e);if(void 0===t)throw new TypeError("The value cannot be serialized as JSON.");return t}function S(e,t){if(null==e)return{};if(!A(e))throw new TypeError(`The provided value is not of type '${t}'.`);return e}function j(e,t,n){const o=e[t];if(void 0===o)throw new TypeError(`Failed to read the '${t}' property from '${n}': Required member is undefined.`);return o}function C(e){const t=S(e,"ToolAnnotations"),n=e=>void 0!==t[e]&&Boolean(t[e]);return{consequentialHint:n("consequentialHint"),debugging:n("debugging"),readOnlyHint:n("readOnlyHint"),untrustedContentHint:n("untrustedContentHint")}}function O(e,t){if(void 0!==e){if("function"==typeof AbortSignal&&!(e instanceof AbortSignal))throw new TypeError(`Failed to read the 'signal' property from '${t}': The provided value is not of type 'AbortSignal'.`);return e}}function k(e,t,n){if(void 0!==e){if(!A(e)||"function"!=typeof e[Symbol.iterator])throw new TypeError(`Failed to read the '${t}' property from '${n}': The provided value cannot be converted to a sequence.`);return[...e].map(N)}}function L(e){const t="RegisteredTool",n=S(e,t);if(void 0!==n.annotations&&C(n.annotations),x(j(n,"description",t)),void 0!==n.inputSchema&&!A(n.inputSchema))throw new TypeError(`Failed to read the 'inputSchema' property from '${t}': The provided value is not of type 'object'.`);const o=x(j(n,"name",t)),r=N(j(n,"origin",t));void 0!==n.title&&x(n.title);const i=j(n,"window",t);if(!function(e){return"undefined"==typeof window?e===globalThis:A(e)&&e.window===e}(i))throw new TypeError(`Failed to read the 'window' property from '${t}': The provided value is not of type 'Window'.`);return{name:o,origin:r,window:i}}function M(){return"undefined"!=typeof window?window:globalThis}function P(){return"undefined"!=typeof location?location.origin:"http://localhost"}function I(e){return e.map(e=>{let t;try{t=new URL(e)}catch{throw E(`"${e}" is not a valid origin.`,"SecurityError")}if(!function(e){if("null"===e.origin)return!1;if("https:"===e.protocol||"wss:"===e.protocol)return!0;const t=e.hostname;return!("localhost"!==t&&!t.endsWith(".localhost"))||/^127(?:\.\d{1,3}){3}$/.test(t)||"[::1]"===t}(t))throw E(`"${e}" is not a potentially trustworthy origin.`,"SecurityError");return t.origin})}function R(){const e=globalThis,t="undefined"!=typeof location?location.protocol:"";return!1===e.originAgentCluster&&"file:"!==t?E("This page's agent cluster is not origin-keyed.","SecurityError"):function(){if("undefined"==typeof document)return!0;const e=document,t=e.permissionsPolicy??e.featurePolicy;if(!t?.features||!t.allowsFeature)return!0;try{return!t.features().includes("tools")||t.allowsFeature("tools")}catch{return!0}}()?null:E("The 'tools' permissions policy does not allow this document to use tools.","NotAllowedError")}class _ extends EventTarget{constructor(){super(...arguments),u.add(this),c.set(this,new Map),d.set(this,new Map),f.set(this,{}),p.set(this,{})}get ontoolchange(){return y(this,f,"f").toolchange??null}set ontoolchange(e){y(this,u,"m",w).call(this,"toolchange",e)}get ontoolactivated(){return y(this,f,"f").toolactivated??null}set ontoolactivated(e){y(this,u,"m",w).call(this,"toolactivated",e)}get ontoolcancel(){return y(this,f,"f").toolcancel??null}set ontoolcancel(e){y(this,u,"m",w).call(this,"toolcancel",e)}registerTool(e,t={}){let n,o,r;try{n=function(e){const t="ModelContextTool",n=S(e,t),o=void 0===n.annotations?void 0:C(n.annotations),r=x(j(n,"description",t)),i=j(n,"execute",t);if("function"!=typeof i)throw new TypeError(`Failed to read the 'execute' property from '${t}': The provided value is not a function.`);const a=n.inputSchema;if(void 0!==a&&!A(a))throw new TypeError(`Failed to read the 'inputSchema' property from '${t}': The provided value is not of type 'object'.`);return{annotations:o,description:r,execute:i,inputSchema:a,name:x(j(n,"name",t)),title:void 0===n.title?void 0:N(n.title)}}(e);const i=S(t,"ModelContextRegisterToolOptions");r=k(i.exposedTo,"exposedTo","ModelContextRegisterToolOptions"),o=O(i.signal,"ModelContextRegisterToolOptions")}catch(e){return Promise.reject(e)}const i=R();if(i)return Promise.reject(i);const a=n.name;if(y(this,c,"f").has(a))return Promise.reject(E(`A tool named "${a}" is already registered.`,"InvalidStateError"));if(!b.test(a))return Promise.reject(E(`"${a}" is not a valid tool name: 1 to 128 ASCII letters, digits, "_", "-" or ".".`,"InvalidStateError"));if(""===n.description)return Promise.reject(E("A tool's description must not be empty.","InvalidStateError"));let s="";if(void 0!==n.inputSchema)try{s=$(n.inputSchema)}catch(e){return Promise.reject(e)}if(o?.aborted)return Promise.reject(o.reason);let l,d=[];if(r)try{d=I(r)}catch(e){return Promise.reject(e)}const f=new Promise((e,t)=>l={resolve:e,reject:t});if(o){const e=o;e.addEventListener("abort",()=>{y(this,u,"m",v).call(this,a),l.reject(e.reason)},{once:!0})}return y(this,c,"f").set(a,{name:a,title:n.title??null,description:n.description,inputSchema:s,annotations:void 0===n.annotations?null:C(n.annotations),exposedOrigins:d,tool:n}),y(this,u,"m",g).call(this),T(()=>l.resolve()),f}getTools(e={}){let t;try{t=k(S(e,"ModelContextGetToolOptions").fromOrigins,"fromOrigins","ModelContextGetToolOptions")}catch(e){return Promise.reject(e)}const n=R();if(n)return Promise.reject(n);if(t)try{I(t)}catch(e){return Promise.reject(e)}return new Promise(e=>{const t=P(),n=M(),o=[...y(this,c,"f").values()].map(e=>{const o={};return e.annotations&&(o.annotations={...e.annotations}),o.description=e.description,""!==e.inputSchema&&(o.inputSchema=JSON.parse(e.inputSchema)),o.name=e.name,o.origin=t,o.title=e.title??"",o.window=n,o});o.sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0),T(()=>e(o))})}executeTool(e,t,n={}){let o,r;try{o=L(e),r=O(S(n,"ModelContextExecuteToolOptions").signal,"ModelContextExecuteToolOptions")}catch(e){return Promise.reject(e)}const i=R();if(i)return Promise.reject(i);let a,s,l;try{a=new URL(o.origin).origin}catch{return Promise.reject(E(`"${o.origin}" is not a valid origin.`,"NotSupportedError"))}if("null"===a)return Promise.reject(E("A tool's origin must not be opaque.","NotSupportedError"));if(!A(t))return Promise.reject(new TypeError("Failed to execute 'executeTool' on 'ModelContext': The input is not an object."));try{s=$(t)}catch(e){return Promise.reject(e)}const f=new Promise((e,t)=>l={resolve:e,reject:t}),p=Symbol("tool execution");if(r){if(r.aborted)return Promise.reject(r.reason);const e=r;e.addEventListener("abort",()=>{l.reject(e.reason),T(()=>y(this,u,"m",h).call(this,p))},{once:!0})}const v=()=>T(()=>l.reject(E("The tool could not be executed.","UnknownError")));return T(()=>{if(o.window!==M()||P()!==a)return v();if(!y(this,c,"f").has(o.name))return v();const e={toolName:o.name,controller:new AbortController,started:!1,complete:(e,t)=>{y(this,d,"f").has(p)&&(y(this,d,"f").delete(p),T(()=>t?l.resolve(e):l.reject(E("The tool's execution failed.","UnknownError"))))}};y(this,d,"f").set(p,e),T(()=>y(this,u,"m",m).call(this,o.name,s,e))}),f}}function U(e,t){e in globalThis||Object.defineProperty(globalThis,e,{value:t,writable:!0,enumerable:!1,configurable:!0})}c=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,u=new WeakSet,m=function(e,t,n){const o=y(this,c,"f").get(e);if(!o)return n.complete(null,!1);let r;try{r=JSON.parse(t)}catch{return n.complete(null,!1)}if(!A(r))return n.complete(null,!1);this.dispatchEvent(new s("toolactivated",{toolName:o.name})),n.started=!0;const i={signal:n.controller.signal};let a;try{a=Promise.resolve(o.tool.execute.call(void 0,r,i))}catch(e){a=Promise.reject(e)}a.then(e=>{if(!n.started)return;let t;n.started=!1;try{t=$(e)}catch{return n.complete(null,!1)}n.complete(t,!0)},()=>{n.started&&(n.started=!1,n.complete(null,!1))})},h=function(e){const t=y(this,d,"f").get(e);t&&(y(this,d,"f").delete(e),T(()=>{t.started&&(t.started=!1,t.controller.abort(),this.dispatchEvent(new l("toolcancel",{toolName:t.toolName})))}))},v=function(e){y(this,c,"f").delete(e)&&y(this,u,"m",g).call(this)},g=function(){T(()=>this.dispatchEvent(new Event("toolchange")))},w=function(e,t){const n="function"==typeof t?t:null;if(y(this,f,"f")[e]=n,n&&!y(this,p,"f")[e]){const t=t=>{const n=y(this,f,"f")[e];n&&!1===n.call(this,t)&&t.preventDefault()};y(this,p,"f")[e]=t,this.addEventListener(e,t)}else!n&&y(this,p,"f")[e]&&(this.removeEventListener(e,y(this,p,"f")[e]),delete y(this,p,"f")[e])};const D=["AskAction","SearchAction","SubscribeAction","RegisterAction","BuyAction","OrderAction","AddAction","ScheduleAction","ReserveAction","RsvpAction","ApplyAction","QuoteAction","DownloadAction","ReviewAction","CommentAction","TrackAction","CommunicateAction","InteractAction"];const V="https://nxis.ai/ns#";function F(e,t,n){var o;return null!==(o=e[t])&&void 0!==o?o:e[n]}function H(e,t){return F(e,t,"https://schema.org/"+t)}function W(e,t){const n=H(e,t);return"string"==typeof n?n:null}function q(e,t,n){const o=F(e,t,n);return Array.isArray(o)?o:[]}function z(e){if(Array.isArray(e)){const t=[];for(const n of e)t.push(...z(n));return t}if(e&&"object"==typeof e){const t=e;if(Array.isArray(t["@graph"])){const e=[];for(const n of t["@graph"])e.push(...z(n));return e}return[t]}return[]}function G(e){var t;if(!e||"object"!=typeof e)return null;const n=e,o="string"==typeof n["@type"]?n["@type"]:null;if(!o)return null;if(!o.endsWith("Action")&&!function(e){return D.includes(e)}(o))return null;const r="string"==typeof n["@id"]?n["@id"]:null,i=W(n,"name"),a=function(e){var t,n;if(!e||"object"!=typeof e)return null;const o=e,r=null!==(n=null===(t=W(o,"httpMethod"))||void 0===t?void 0:t.toUpperCase())&&void 0!==n?n:null;if(!r)return null;const i={"@type":"EntryPoint",httpMethod:r},a=W(o,"encodingType");null!==a&&(i.encodingType=a);const s=W(o,"urlTemplate");null!==s&&(i.urlTemplate=s);const l=F(o,"nxis:targetKind",V+"targetKind");"selfPage"!==l&&"clientSide"!==l||(i["nxis:targetKind"]=l);const u=F(o,"nxis:pageUrl",V+"pageUrl");"string"==typeof u&&(i["nxis:pageUrl"]=u);const c=F(o,"nxis:jsHandled",V+"jsHandled");!0===c&&(i["nxis:jsHandled"]=!0);return i}(H(n,"target"));if(!r||!i||!a)return null;const s=q(n,"nxis:input",V+"input").map(X).filter(e=>null!==e),l=null!==(t=W(n,"description"))&&void 0!==t?t:function(e,t,n){const o=e.replace(/^.*[/#]/,"").replace(/Action$/,"").toLowerCase(),r=n.map(e=>e.valueName).join(", ");if(0===n.length)return`Trigger the ${o} action "${t}".`;return`Fill the ${o} form "${t}" with fields: ${r}.`}(o,i,s);return{"@context":n["@context"],"@type":o,"@id":r,name:i,description:l,target:a,input:s.length>0?s:void 0,"nxis:extractedAt":F(n,"nxis:extractedAt",V+"extractedAt")}}function X(e){if(!e||"object"!=typeof e)return null;const t=e,n=W(t,"valueName");if(!n)return null;const o=F(t,"nxis:valueType",V+"valueType"),r={"@type":"PropertyValueSpecification",valueName:n,"nxis:valueType":"string"==typeof o?o:"string"},i=W(t,"description");null!==i&&(r.description=i),!0===H(t,"valueRequired")&&(r.valueRequired=!0);const a=W(t,"defaultValue");null!==a&&(r.defaultValue=a);const s=e=>{const n=H(t,e);return"number"==typeof n?n:null},l=s("valueMinLength");null!==l&&(r.valueMinLength=l);const u=s("valueMaxLength");null!==u&&(r.valueMaxLength=u);const c=s("minValue");null!==c&&(r.minValue=c);const d=s("maxValue");null!==d&&(r.maxValue=d);const f=s("stepValue");null!==f&&(r.stepValue=f);const p=W(t,"valuePattern");null!==p&&(r.valuePattern=p),!0===H(t,"multipleValues")&&(r.multipleValues=!0),!0===H(t,"readonlyValue")&&(r.readonlyValue=!0);const m=q(t,"nxis:valueOption",V+"valueOption");if(m.length>0){const e=m.filter(e=>e&&"object"==typeof e&&null!==W(e,"value")).map(e=>{var t;const n=e;return{"@type":"nxis:ValueOption",value:W(n,"value"),name:null!==(t=W(n,"name"))&&void 0!==t?t:void 0}});e.length>0&&(r["nxis:valueOption"]=e)}return r}function J(e){switch(e){case"string":case"date":case"file":default:return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean"}}function B(e){var t;const n={},o=[],r=null!==(t=e.input)&&void 0!==t?t:[];for(const e of r){const t=K(e);if(e.multipleValues){const o={type:"array",items:t};void 0!==e.valueMinLength&&(o.minItems=e.valueMinLength,delete t.minLength),void 0!==e.valueMaxLength&&(o.maxItems=e.valueMaxLength,delete t.maxLength),e.description&&(o.description=e.description,delete t.description),n[e.valueName]=o}else n[e.valueName]=t;e.valueRequired&&o.push(e.valueName)}const i={type:"object",properties:n};return o.length>0&&(i.required=o),i}function K(e){const t={type:J(e["nxis:valueType"])},n=function(e){if("date"===e)return"date"}(e["nxis:valueType"]);if(n&&(t.format=n),e.description&&(t.description=e.description),void 0!==e.defaultValue&&(t.default=function(e,t){switch(t){case"number":case"integer":{const t=Number(e);return isNaN(t)?e:t}case"boolean":return"true"===e||"1"===e;default:return e}}(e.defaultValue,e["nxis:valueType"])),void 0!==e.valueMinLength&&(t.minLength=e.valueMinLength),void 0!==e.valueMaxLength&&(t.maxLength=e.valueMaxLength),e.valuePattern){const n=e.valuePattern,o=n.startsWith("^")&&n.endsWith("$")?n:`^${n}$`;t.pattern=o}void 0!==e.minValue&&(t.minimum=e.minValue),void 0!==e.maxValue&&(t.maximum=e.maxValue),void 0!==e.stepValue&&(t.multipleOf=e.stepValue),e.readonlyValue&&(t.readOnly=!0);const o=e["nxis:valueOption"];if(o&&o.length>0){t.enum=o.map(e=>e.value);if(o.some(e=>void 0!==e.name&&e.name!==e.value)){const e=o.filter(e=>e.name&&e.name!==e.value).map(e=>`${e.value} = "${e.name}"`).join(", "),n=t.description?`${t.description}. `:"";t.description=`${n}Values: ${e}`}}return t}function Q(e){const t=Array.from(document.querySelectorAll("form"));if(0===t.length)return null;const n=function(e){return e.input?e.input.map(e=>e.valueName):[]}(e);let o;if(o=!e.target.urlTemplate?t:function(e,t,n){const o=function(e){const t=e.replace(/\{[^}]*\}/g,"");try{return new URL(t,window.location.href)}catch(e){return null}}(t);return e.filter(e=>{if((e.method||"GET").toUpperCase()!==n.toUpperCase())return!1;if(!o)return!0;const t=function(e){const t=e.getAttribute("action");if(!t||"#"===t||t.startsWith("#")||""===t)return window.location.href.split("#")[0].split("?")[0];if(t.startsWith("javascript:"))return window.location.href.split("#")[0].split("?")[0];try{return new URL(t,window.location.href).href}catch(e){return t}}(e);return function(e,t){let n;try{n=new URL(e,window.location.href)}catch(e){return!1}if(n.origin!==t.origin)return!1;const o=n.pathname.replace(/\/+$/,""),r=t.pathname.replace(/\/+$/,"");return""===r||(o===r||o.startsWith(r+"/")||r.startsWith(o+"/"))}(t,o)})}(t,e.target.urlTemplate,e.target.httpMethod),0===o.length&&(o=t),1===o.length)return o[0];const r=o.map(e=>({form:e,controlNames:Z(e)})).filter(({controlNames:e})=>n.every(t=>e.has(t)));return 0===r.length?(console.warn(`[nxis/webmcp] No field-set match for action "${e.name}". Expected fields: [${n.join(", ")}]. Falling back to first candidate.`),o[0]):1===r.length?r[0].form:(r.sort((e,t)=>e.controlNames.size-t.controlNames.size),r[0].controlNames.size===r[1].controlNames.size?(console.warn(`[nxis/webmcp] Ambiguous form match for action "${e.name}". ${r.length} forms have identical field sets. Returning null.`),null):r[0].form)}function Z(e){const t=new Set,n=e.elements;for(let e=0;e<n.length;e++){const o=n[e];o.name&&t.add(o.name)}return t}function Y(e,t){var n;return(null!==(n=e.input)&&void 0!==n?n:[]).map(e=>function(e,t){var n;const o=t=>({valueName:e.valueName,pvs:e,strategy:t}),r=function(e,t){const n=[],o=e.elements;for(let e=0;e<o.length;e++){const r=o[e];r.name===t&&n.push(r)}return n}(t,e.valueName),i=null!==(n=r[0])&&void 0!==n?n:null;if(!i)return o({kind:"skip",reason:`No control found with name="${e.valueName}"`});if(i instanceof HTMLInputElement&&"radio"===i.type){const t=r.filter(e=>e instanceof HTMLInputElement&&"radio"===e.type&&!e.disabled);return 0===t.length?o({kind:"skip",reason:`Radio group "${e.valueName}" has no enabled options`}):o({kind:"radio",name:e.valueName,elements:t})}if(i instanceof HTMLInputElement&&"checkbox"===i.type){const t=r.filter(e=>e instanceof HTMLInputElement&&"checkbox"===e.type&&!e.disabled);return 0===t.length?o({kind:"skip",reason:`Checkbox "${e.valueName}" is disabled`}):t.length>1?o({kind:"checkboxGroup",name:e.valueName,elements:t}):o({kind:"checked",element:t[0]})}if(!0===i.readOnly||null!==i.getAttribute("readonly"))return o({kind:"skip",reason:`Control "${e.valueName}" is readonly in the DOM`});if(i.disabled)return o({kind:"skip",reason:`Control "${e.valueName}" is disabled`});if(i instanceof HTMLSelectElement){const e=[];for(let t=0;t<i.options.length;t++){const n=i.options[t];n.value&&e.push(n.value)}return o(i.multiple?{kind:"multiSelect",element:i,allowedValues:e}:{kind:"select",element:i,allowedValues:e})}if(i instanceof HTMLTextAreaElement)return o({kind:"value",element:i});if(i instanceof HTMLInputElement)return o({kind:"value",element:i});return o({kind:"skip",reason:`Unsupported control type for "${e.valueName}"`})}(e,t))}async function ee(e,t){var n,o;const r=function(e){const t=e.target["nxis:pageUrl"];if(!t)return null;try{const n=new URL(t),o=new URL(window.location.href);if(n.origin!==o.origin||n.pathname!==o.pathname)return`Action "${e.name}" was extracted from ${n.origin}${n.pathname} but the current page is ${o.origin}${o.pathname}. The form may have moved or changed.`}catch(e){return null}return null}(e),i=Q(e);if(!i){const t=`Form not found for action "${e.name}". The page may have changed since the tool was registered.`,n={success:!1,submitted:!1,message:r?`Warning: ${r} ${t}`:t,filled:[],skipped:[]};return r&&(n.stale=!0),n}const a=Y(e,i),s=null!==(n=e.input)&&void 0!==n?n:[],l=[],u=[];let c=!1;for(const e of s)!e.valueRequired||void 0!==t[e.valueName]&&null!==t[e.valueName]||(c=!0,u.push({field:e.valueName,reason:`Required field '${e.valueName}' was not provided. Expected type: ${e["nxis:valueType"]}.`}));for(const e of a){const n=t[e.valueName];if(null==n){u.some(t=>t.field===e.valueName)||u.push({field:e.valueName,reason:"No value provided (optional field)."});continue}const o=ne(e,n);!1===o.ok?u.push({field:e.valueName,reason:o.reason}):l.push(e.valueName)}await new Promise(e=>setTimeout(e,0));for(const e of a)if("value"===e.strategy.kind&&l.includes(e.valueName)){const n=e.strategy.element,r=oe(null!==(o=t[e.valueName])&&void 0!==o?o:"");n.value!==r&&(u.push({field:e.valueName,reason:`Value was set to "${r}" but the DOM now shows "${n.value}". A framework may have reverted it.`}),l.splice(l.indexOf(e.valueName),1))}const d=l.length>0&&!c;let f=!1;d&&(f=function(e){try{return"function"==typeof e.requestSubmit?e.requestSubmit():e.submit(),!0}catch(e){return console.warn("[nxis/webmcp] Form submission failed:",e),!1}}(i));const p={success:d,submitted:f,message:te(l,u,f,r),filled:l,skipped:u};return r&&(p.stale=!0),p}function te(e,t,n,o){const r=[];if(o&&r.push(`Warning: ${o}`),0===e.length&&0===t.length)return r.push("No fields were filled. Verify field names match the input schema."),r.join(" ");if(e.length>0&&r.push(`Filled ${e.length} field(s): ${e.join(", ")}.`),t.length>0){const e=t.map(e=>`${e.field} (${e.reason})`).join("; ");r.push(`Skipped ${t.length}: ${e}`)}return n?r.push("Form submitted."):e.length>0&&r.push("Form was NOT submitted due to missing required fields or fill errors."),r.join(" ")}function ne(e,t){const{strategy:n}=e;switch(n.kind){case"skip":return{ok:!1,reason:n.reason};case"value":return function(e,t){var n;const o=null===(n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))||void 0===n?void 0:n.set;o?o.call(e,t):e.value=t;return e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.element,oe(t));case"checked":return function(e,t){return e.checked=function(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){const t=e.trim().toLowerCase();return""!==t&&"false"!==t&&"0"!==t&&"off"!==t&&"no"!==t}return Boolean(e)}(t),e.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.element,t);case"radio":return function(e,t){var n,o;const r=String(t),i=null!==(o=null!==(n=e.find(e=>e.value===r))&&void 0!==n?n:e.find(e=>e.value.toLowerCase()===r.toLowerCase()))&&void 0!==o?o:e.find(e=>function(e){var t;if(e.labels&&e.labels.length>0)return(null!==(t=e.labels[0].textContent)&&void 0!==t?t:"").trim();return e.value}(e).toLowerCase()===r.toLowerCase());if(!i){const t=e.map(e=>e.value).join(", ");return{ok:!1,reason:`Value "${r}" is not an allowed option for radio "${e[0].name}". Allowed: [${t}].`}}return i.checked=!0,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.elements,t);case"checkboxGroup":return function(e,t){const n=(Array.isArray(t)?t:[t]).map(e=>String(e)),o=n.map(e=>e.toLowerCase());let r=!1;for(const t of e){const e=n.includes(t.value)||o.includes(t.value.toLowerCase());t.checked=e,e&&(r=!0),t.dispatchEvent(new Event("change",{bubbles:!0}))}if(!r){const t=e.map(e=>e.value).join(", ");return{ok:!1,reason:`None of [${n.join(", ")}] match checkbox group "${e[0].name}". Allowed: [${t}].`}}return{ok:!0}}(n.elements,t);case"select":return function(e,t,n){const o=re(e,t,n);if(null===o)return{ok:!1,reason:`Value "${t}" is not an allowed option for "${e.name}". Allowed: [${n.join(", ")}].`};return e.value=o,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0}}(n.element,String(t),n.allowedValues);case"multiSelect":return function(e,t,n){const o=(Array.isArray(t)?t:[t]).map(e=>String(e)),r=new Set,i=[];for(const t of o){const o=re(e,t,n);null===o?i.push(t):r.add(o)}if(0===r.size)return{ok:!1,reason:`None of [${o.join(", ")}] are allowed options for "${e.name}". Allowed: [${n.join(", ")}].`};for(const t of Array.from(e.options))t.selected=r.has(t.value);if(e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),i.length>0)return{ok:!1,reason:`Selected [${Array.from(r).join(", ")}] but [${i.join(", ")}] are not allowed options for "${e.name}". Allowed: [${n.join(", ")}].`};return{ok:!0}}(n.element,t,n.allowedValues);default:return{ok:!1,reason:`Unsupported fill strategy for field "${e.valueName}".`}}}function oe(e){return Array.isArray(e)?e.map(e=>String(e)).join(","):String(e)}function re(e,t,n){if(n.includes(t))return t;const o=n.find(e=>e.toLowerCase()===t.toLowerCase());if(o)return o;for(const n of Array.from(e.options))if(n.text.toLowerCase()===t.toLowerCase())return n.value;return null}function ie(e){var t;const n=!1!==(null==e?void 0:e.observe),o=null!==(t=null==e?void 0:e.doc)&&void 0!==t?t:"undefined"!=typeof document?document:void 0;if(!o)return console.warn("[nxis/webmcp] No document available (not running in a browser). Tools will not be registered."),()=>{};!function(e={}){const{force:t=!1,installNavigatorAlias:n=!1}=e,o="undefined"!=typeof document&&document.modelContext||"undefined"!=typeof navigator&&navigator.modelContext||void 0;if(o&&!t)return o;if(!1===globalThis.isSecureContext)return;let r;if(U("ModelContext",_),U("ToolActivatedEvent",s),U("ToolCancelEvent",l),"undefined"!=typeof document){const e=globalThis.Document;if(e&&document instanceof e){const t=new WeakMap;Object.defineProperty(e.prototype,"modelContext",{get(){if(!(this instanceof e))throw new TypeError("Illegal invocation");let n=t.get(this);return n||t.set(this,n=new _),n},enumerable:!0,configurable:!0}),Object.prototype.hasOwnProperty.call(document,"modelContext")&&delete document.modelContext}else Object.defineProperty(document,"modelContext",{value:new _,writable:!1,enumerable:!0,configurable:!0});r=document.modelContext}else r=new _;n&&"undefined"!=typeof navigator&&Object.defineProperty(navigator,"modelContext",{value:r,writable:!1,enumerable:!0,configurable:!0})}();const r=function(e){var t,n;const o=null!==(n=null===(t=e.defaultView)||void 0===t?void 0:t.navigator)&&void 0!==n?n:"undefined"!=typeof navigator?navigator:void 0;return e.modelContext||(null==o?void 0:o.modelContext)||null}(o);if(!r)return console.warn("[nxis/webmcp] WebMCP API not available — document.modelContext is undefined. Tools will not be registered."),()=>{};const i=new AbortController;(null==e?void 0:e.signal)&&(e.signal.aborted?i.abort():e.signal.addEventListener("abort",()=>i.abort()));const a={ids:new Set,names:new Set};ae(o,r,i,a);let u=null;return n&&(u=function(e,t,n,o){const r=new MutationObserver(r=>{(function(e){for(const t of e)for(const e of Array.from(t.addedNodes)){if(se(e))return!0;if(e instanceof Element&&e.querySelector('script[type="application/ld+json"]'))return!0}return!1})(r)&&ae(e,t,n,o)});return n.signal.addEventListener("abort",()=>r.disconnect()),r.observe(e.documentElement,{childList:!0,subtree:!0}),r}(o,r,i,a)),()=>{i.abort(),u&&(u.disconnect(),u=null)}}async function ae(e,t,n,o){const r=function(e=("undefined"!=typeof document?document:void 0)){const t=[];if(!e)return t;const n=e.querySelectorAll('script[type="application/ld+json"]');for(const e of Array.from(n)){const n=e.textContent;if(!n)continue;let o;try{o=JSON.parse(n)}catch(e){continue}const r=z(o);for(const e of r){const n=G(e);n&&t.push(n)}}return t}(e).filter(e=>!o.ids.has(e["@id"])),i=await Promise.all(r.map(e=>async function(e,t,n,o){const r=function(e,t){if(!t.has(e))return e;for(let n=2;;n++){const o=`_${n}`,r=e.slice(0,64-o.length)+o;if(!t.has(r))return r}}(function(e){return e.toLowerCase().replace(/[\s-]+/g,"_").replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").slice(0,64)||"unnamed_action"}(e.name),o.names);o.ids.add(e["@id"]),o.names.add(r);try{const o={name:r,description:e.description||`Fill in and submit the "${e.name}" form.`,inputSchema:B(e),annotations:{readOnlyHint:!1,untrustedContentHint:!0,"ai.nxis/actionId":e["@id"]},execute:t=>ee(e,t)};return await t.registerTool(o,{signal:n.signal}),!0}catch(t){return n.signal.aborted||(o.ids.delete(e["@id"]),o.names.delete(r),console.warn(`[nxis/webmcp] Failed to register tool for action "${e.name}":`,t)),!1}}(e,t,n,o))),a=i.filter(Boolean).length;a>0&&console.info(`[nxis/webmcp] Registered ${a} tool(s) (${o.ids.size} total) from ${r.length} new action(s).`)}function se(e){return e instanceof HTMLScriptElement&&"application/ld+json"===e.type}const le=["nxis_handoff","nxis_intent","nxis_report"];function ue(e){const t=new URL(e);if(!t.search)return t;const n=t.search.slice(1).split("&").filter(e=>!le.includes(function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}}(e.split("=")[0])));return t.search=n.length?`?${n.join("&")}`:"",t}function ce(t){t instanceof e?console.warn(JSON.parse(t.message).message):console.error(`Unable to retrieve structured data for ${window.location.href}`)}!function(){var t,o;const r=window.__NXIS_CONFIG__,i=null!==(o=null===(t=null==r?void 0:r.webmcp)||void 0===t?void 0:t.mode)&&void 0!==o?o:"browser";if("ssr"===i)return void ie();const a=process.env.NXIS_API_HOST,s=new Headers,l=new URL(`${a}/v1/nxis:inject`);l.search=function(e){var t,n;const o=new URLSearchParams;return(null===(t=e.organization_id)||void 0===t?void 0:t.value)&&o.append("organization_id",e.organization_id.value),(null===(n=e.site_id)||void 0===n?void 0:n.value)&&o.append("site_id",e.site_id.value),o.append("uri",e.uri.href),e.referrer&&o.append("referrer",e.referrer),o}({organization_id:{value:null==r?void 0:r.org_id},site_id:{value:null==r?void 0:r.site_id},uri:ue(window.location.href),referrer:document.referrer}).toString(),(null==r?void 0:r.sub_id)&&s.set("X-NXIS-SUBSCRIPTION",r.sub_id),s.set("Content-Type","application/json"),s.set("User-Agent",navigator.userAgent),fetch(`${l}`,{headers:s}).then(t=>async function(t,o){const r=null!=o?o:"unknown";if(200===t.status){const n=await t.json();if((null==n?void 0:n.data)&&Object.keys(n.data).length>0)return n;throw new e(JSON.stringify({message:`No Nxis resource found for ${r}`}))}const i=await async function(e){try{return await e.json()}catch(e){return null}}(t);if(void 0!==(null==i?void 0:i.code)&&(null==i?void 0:i.message))throw n.fromResponse(t.status,i);switch(t.status){case 500:throw new n(13,500,"An internal server error occurred, please contact technical support.");case 502:throw new n(13,502,"An internal server error occurred, please contact technical support.");case 503:throw new n(8,503,"Service is temporarily unavailable, please try again later.");default:throw new n(13,t.status,`Unexpected response status: ${t.status}`)}}(t,window.location.href)).then(e=>{!function(e){if(e.data&&Object.keys(e.data).length>0){const t=document.createComment("Nxis.ai"),n=document.createComment("End Nxis.ai"),o=document.createElement("script");o.setAttribute("type","application/ld+json"),o.textContent=JSON.stringify(e.data),document.head.appendChild(o),o.before(t),o.after(n)}}(e),"browser"===i&&ie()}).catch(ce)}();
|
package/package.json
CHANGED
package/src/client.ts
CHANGED
|
@@ -53,8 +53,11 @@ function inject(response: StructuredDataResponse): void {
|
|
|
53
53
|
*
|
|
54
54
|
* @internal
|
|
55
55
|
*/
|
|
56
|
-
/**
|
|
57
|
-
|
|
56
|
+
/**
|
|
57
|
+
* The parameters the NxisAI app adds when it hands someone to a page's agent: the action, what they asked, and the
|
|
58
|
+
* report token the agent sends back with the form so the conversion counts as verified.
|
|
59
|
+
*/
|
|
60
|
+
const HANDOFF_PARAMS = ["nxis_handoff", "nxis_intent", "nxis_report"];
|
|
58
61
|
|
|
59
62
|
/**
|
|
60
63
|
* A page's address without the NxisAI app's handoff parameters.
|