momentic-mobile 0.59.0 → 0.59.1

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/bin/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="432f71fe-6620-5c85-b8e8-00b634d5aa15")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="71a2b584-0a49-55d7-9b02-be449570bf78")}catch(e){}}();
4
4
  var M4=Object.create;var XE=Object.defineProperty;var P4=Object.getOwnPropertyDescriptor;var I4=Object.getOwnPropertyNames;var O4=Object.getPrototypeOf,N4=Object.prototype.hasOwnProperty;var Vt=(r,e)=>()=>(r&&(e=r(r=0)),e);var Q=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),L4=(r,e)=>{for(var t in e)XE(r,t,{get:e[t],enumerable:!0})},D4=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of I4(e))!N4.call(r,o)&&o!==t&&XE(r,o,{get:()=>e[o],enumerable:!(n=P4(e,o))||n.enumerable});return r};var Jf=(r,e,t)=>(t=r!=null?M4(O4(r)):{},D4(e||!r||!r.__esModule?XE(t,"default",{value:r,enumerable:!0}):t,r));var w0,C0=Vt(()=>{"use strict";w0=typeof globalThis=="object"?globalThis:global});var R0=Vt(()=>{"use strict";C0()});var x0=Vt(()=>{"use strict";R0()});var Ji,Qv=Vt(()=>{"use strict";Ji="1.9.0"});function n6(r){var e=new Set([r]),t=new Set,n=r.match(_0);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===r};function i(s){return t.add(s),!1}function a(s){return e.add(s),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var c=l.match(_0);if(!c)return i(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?i(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):i(l):o.minor<=u.minor?a(l):i(l)}}var _0,M0,P0=Vt(()=>{"use strict";Qv();_0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;M0=n6(Ji)});function eu(r,e,t,n){var o;n===void 0&&(n=!1);var i=Vm[Wm]=(o=Vm[Wm])!==null&&o!==void 0?o:{version:Ji};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Ji){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Ji);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Ji+"."),!0}function Zi(r){var e,t,n=(e=Vm[Wm])===null||e===void 0?void 0:e.version;if(!(!n||!M0(n)))return(t=Vm[Wm])===null||t===void 0?void 0:t[r]}function tu(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Ji+".");var t=Vm[Wm];t&&delete t[r]}var o6,Wm,Vm,qm=Vt(()=>{"use strict";x0();Qv();P0();o6=Ji.split(".")[0],Wm=Symbol.for("opentelemetry.js.api."+o6),Vm=w0});function Km(r,e,t){var n=Zi("diag");if(n)return t.unshift(e),n[r].apply(n,a6([],i6(t),!1))}var i6,a6,I0,O0=Vt(()=>{"use strict";qm();i6=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},a6=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},I0=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Km("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Km("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Km("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Km("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Km("verbose",this._namespace,e)},r}()});var Dt,mg=Vt(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(Dt||(Dt={}))});function N0(r,e){r<Dt.NONE?r=Dt.NONE:r>Dt.ALL&&(r=Dt.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",Dt.ERROR),warn:t("warn",Dt.WARN),info:t("info",Dt.INFO),debug:t("debug",Dt.DEBUG),verbose:t("verbose",Dt.VERBOSE)}}var L0=Vt(()=>{"use strict";mg()});var s6,l6,c6,pi,Ym=Vt(()=>{"use strict";O0();L0();mg();qm();s6=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},l6=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},c6="diag",pi=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Zi("diag");if(s)return s[o].apply(s,l6([],s6(i),!1))}}var t=this,n=function(o,i){var a,s,l;if(i===void 0&&(i={logLevel:Dt.INFO}),o===t){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Zi("diag"),d=N0((s=i.logLevel)!==null&&s!==void 0?s:Dt.INFO,o);if(u&&!i.suppressOverrideMessage){var m=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+m),d.warn("Current logger will overwrite one already registered from "+m)}return eu("diag",d,t,!0)};t.setLogger=n,t.disable=function(){tu(c6,t)},t.createComponentLogger=function(o){return new I0(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var D0,k0=Vt(()=>{"use strict";D0=Symbol("BaggageEntryMetadata")});function eA(r){return typeof r!="string"&&(u6.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:D0,toString:function(){return r}}}var u6,F0=Vt(()=>{"use strict";Ym();k0();u6=pi.instance()});function tA(r){return Symbol.for(r)}var d6,rA,nA=Vt(()=>{"use strict";d6=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),rA=new d6});function aA(){return iA}var nl,m6,pg,p6,f6,h6,g6,oA,y6,S6,b6,iA,E6,T6,v6,A6,w6,C6,R6,sA=Vt(()=>{"use strict";nl=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),m6=function(){function r(){}return r.prototype.createGauge=function(e,t){return T6},r.prototype.createHistogram=function(e,t){return v6},r.prototype.createCounter=function(e,t){return E6},r.prototype.createUpDownCounter=function(e,t){return A6},r.prototype.createObservableGauge=function(e,t){return C6},r.prototype.createObservableCounter=function(e,t){return w6},r.prototype.createObservableUpDownCounter=function(e,t){return R6},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),pg=function(){function r(){}return r}(),p6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(pg),f6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(pg),h6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(pg),g6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(pg),oA=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),y6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(oA),S6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(oA),b6=function(r){nl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(oA),iA=new m6,E6=new p6,T6=new h6,v6=new g6,A6=new f6,w6=new y6,C6=new S6,R6=new b6});var zn,U0=Vt(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(zn||(zn={}))});var x6,_6,B0,z0=Vt(()=>{"use strict";nA();x6=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_6=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},B0=function(){function r(){}return r.prototype.active=function(){return rA},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,_6([n],x6(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var M6,P6,lA,I6,$0,H0=Vt(()=>{"use strict";z0();qm();Ym();M6=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},P6=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},lA="context",I6=new B0,$0=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return eu(lA,e,pi.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,P6([e,t,n],M6(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Zi(lA)||I6},r.prototype.disable=function(){this._getContextManager().disable(),tu(lA,pi.instance())},r}()});var ru,j0=Vt(()=>{"use strict";H0();ru=$0.getInstance()});var le,G0=Vt(()=>{"use strict";Ym();le=pi.instance()});var O6,W0,V0=Vt(()=>{"use strict";sA();O6=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return iA},r}(),W0=new O6});var cA,q0,K0=Vt(()=>{"use strict";V0();qm();Ym();cA="metrics",q0=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return eu(cA,e,pi.instance())},r.prototype.getMeterProvider=function(){return Zi(cA)||W0},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){tu(cA,pi.instance())},r}()});var fg,Y0=Vt(()=>{"use strict";K0();fg=q0.getInstance()});var Rt=Vt(()=>{"use strict";F0();nA();mg();sA();U0();j0();G0();Y0()});var ff=Q(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.regexpCode=mt.getEsmExportName=mt.getProperty=mt.safeStringify=mt.stringify=mt.strConcat=mt.addCodeArg=mt.str=mt._=mt.nil=mt._Code=mt.Name=mt.IDENTIFIER=mt._CodeOrName=void 0;var mf=class{};mt._CodeOrName=mf;mt.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Bl=class extends mf{constructor(e){if(super(),!mt.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};mt.Name=Bl;var Ro=class extends mf{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof Bl&&(t[n.str]=(t[n.str]||0)+1),t),{})}};mt._Code=Ro;mt.nil=new Ro("");function jW(r,...e){let t=[r[0]],n=0;for(;n<e.length;)rx(t,e[n]),t.push(r[++n]);return new Ro(t)}mt._=jW;var tx=new Ro("+");function GW(r,...e){let t=[pf(r[0])],n=0;for(;n<e.length;)t.push(tx),rx(t,e[n]),t.push(tx,pf(r[++n]));return Nme(t),new Ro(t)}mt.str=GW;function rx(r,e){e instanceof Ro?r.push(...e._items):e instanceof Bl?r.push(e):r.push(kme(e))}mt.addCodeArg=rx;function Nme(r){let e=1;for(;e<r.length-1;){if(r[e]===tx){let t=Lme(r[e-1],r[e+1]);if(t!==void 0){r.splice(e-1,3,t);continue}r[e++]="+"}e++}}function Lme(r,e){if(e==='""')return r;if(r==='""')return e;if(typeof r=="string")return e instanceof Bl||r[r.length-1]!=='"'?void 0:typeof e!="string"?`${r.slice(0,-1)}${e}"`:e[0]==='"'?r.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(r instanceof Bl))return`"${r}${e.slice(1)}`}function Dme(r,e){return e.emptyStr()?r:r.emptyStr()?e:GW`${r}${e}`}mt.strConcat=Dme;function kme(r){return typeof r=="number"||typeof r=="boolean"||r===null?r:pf(Array.isArray(r)?r.join(","):r)}function Fme(r){return new Ro(pf(r))}mt.stringify=Fme;function pf(r){return JSON.stringify(r).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}mt.safeStringify=pf;function Ume(r){return typeof r=="string"&&mt.IDENTIFIER.test(r)?new Ro(`.${r}`):jW`[${r}]`}mt.getProperty=Ume;function Bme(r){if(typeof r=="string"&&mt.IDENTIFIER.test(r))return new Ro(`${r}`);throw new Error(`CodeGen: invalid export name: ${r}, use explicit $id name mapping`)}mt.getEsmExportName=Bme;function zme(r){return new Ro(r.toString())}mt.regexpCode=zme});var ix=Q(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.ValueScope=On.ValueScopeName=On.Scope=On.varKinds=On.UsedValueState=void 0;var In=ff(),nx=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Vb;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Vb||(On.UsedValueState=Vb={}));On.varKinds={const:new In.Name("const"),let:new In.Name("let"),var:new In.Name("var")};var qb=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof In.Name?e:this.name(e)}name(e){return new In.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};On.Scope=qb;var Kb=class extends In.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,In._)`.${new In.Name(t)}[${n}]`}};On.ValueScopeName=Kb;var $me=(0,In._)`\n`,ox=class extends qb{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$me:In.nil}}get(){return this._scope}name(e){return new Kb(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,a=(n=t.key)!==null&&n!==void 0?n:t.ref,s=this._values[i];if(s){let u=s.get(a);if(u)return u}else s=this._values[i]=new Map;s.set(a,o);let l=this._scope[i]||(this._scope[i]=[]),c=l.length;return l[c]=t.ref,o.setValue(t,{property:i,itemIndex:c}),o}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,In._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},t,n)}_reduceValues(e,t,n={},o){let i=In.nil;for(let a in e){let s=e[a];if(!s)continue;let l=n[a]=n[a]||new Map;s.forEach(c=>{if(l.has(c))return;l.set(c,Vb.Started);let u=t(c);if(u){let d=this.opts.es5?On.varKinds.var:On.varKinds.const;i=(0,In._)`${i}${d} ${c} = ${u};${this.opts._n}`}else if(u=o?.(c))i=(0,In._)`${i}${u}${this.opts._n}`;else throw new nx(c);l.set(c,Vb.Completed)})}return i}};On.ValueScope=ox});var Be=Q(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.or=je.and=je.not=je.CodeGen=je.operators=je.varKinds=je.ValueScopeName=je.ValueScope=je.Scope=je.Name=je.regexpCode=je.stringify=je.getProperty=je.nil=je.strConcat=je.str=je._=void 0;var ot=ff(),qo=ix(),ps=ff();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return ps._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return ps.str}});Object.defineProperty(je,"strConcat",{enumerable:!0,get:function(){return ps.strConcat}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return ps.nil}});Object.defineProperty(je,"getProperty",{enumerable:!0,get:function(){return ps.getProperty}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return ps.stringify}});Object.defineProperty(je,"regexpCode",{enumerable:!0,get:function(){return ps.regexpCode}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return ps.Name}});var Zb=ix();Object.defineProperty(je,"Scope",{enumerable:!0,get:function(){return Zb.Scope}});Object.defineProperty(je,"ValueScope",{enumerable:!0,get:function(){return Zb.ValueScope}});Object.defineProperty(je,"ValueScopeName",{enumerable:!0,get:function(){return Zb.ValueScopeName}});Object.defineProperty(je,"varKinds",{enumerable:!0,get:function(){return Zb.varKinds}});je.operators={GT:new ot._Code(">"),GTE:new ot._Code(">="),LT:new ot._Code("<"),LTE:new ot._Code("<="),EQ:new ot._Code("==="),NEQ:new ot._Code("!=="),NOT:new ot._Code("!"),OR:new ot._Code("||"),AND:new ot._Code("&&"),ADD:new ot._Code("+")};var ca=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},ax=class extends ca{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?qo.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=md(this.rhs,e,t)),this}get names(){return this.rhs instanceof ot._CodeOrName?this.rhs.names:{}}},Yb=class extends ca{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof ot.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=md(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ot.Name?{}:{...this.lhs.names};return Jb(e,this.rhs)}},sx=class extends Yb{constructor(e,t,n,o){super(e,n,o),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},lx=class extends ca{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},cx=class extends ca{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ux=class extends ca{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},dx=class extends ca{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=md(this.code,e,t),this}get names(){return this.code instanceof ot._CodeOrName?this.code.names:{}}},hf=class extends ca{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(e,t)||(Hme(e,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Hl(e,t.names),{})}},ua=class extends hf{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},mx=class extends hf{},dd=class extends ua{};dd.kind="else";var zl=class r extends ua{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new dd(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(WW(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=md(this.condition,e,t),this}get names(){let e=super.names;return Jb(e,this.condition),this.else&&Hl(e,this.else.names),e}};zl.kind="if";var $l=class extends ua{};$l.kind="for";var px=class extends $l{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=md(this.iteration,e,t),this}get names(){return Hl(super.names,this.iteration.names)}},fx=class extends $l{constructor(e,t,n,o){super(),this.varKind=e,this.name=t,this.from=n,this.to=o}render(e){let t=e.es5?qo.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${t} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=Jb(super.names,this.from);return Jb(e,this.to)}},Xb=class extends $l{constructor(e,t,n,o){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=md(this.iterable,e,t),this}get names(){return Hl(super.names,this.iterable.names)}},gf=class extends ua{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};gf.kind="func";var yf=class extends hf{render(e){return"return "+super.render(e)}};yf.kind="return";var hx=class extends ua{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,o;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(o=this.finally)===null||o===void 0||o.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Hl(e,this.catch.names),this.finally&&Hl(e,this.finally.names),e}},Sf=class extends ua{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Sf.kind="catch";var bf=class extends ua{render(e){return"finally"+super.render(e)}};bf.kind="finally";var gx=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
5
5
  `:""},this._extScope=e,this._scope=new qo.Scope({parent:e}),this._nodes=[new mx]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,o){let i=this._scope.toName(t);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new ax(e,i,n)),i}const(e,t,n){return this._def(qo.varKinds.const,e,t,n)}let(e,t,n){return this._def(qo.varKinds.let,e,t,n)}var(e,t,n){return this._def(qo.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Yb(e,t,n))}add(e,t){return this._leafNode(new sx(e,je.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ot.nil&&this._leafNode(new dx(e)),this}object(...e){let t=["{"];for(let[n,o]of e)t.length>1&&t.push(","),t.push(n),(n!==o||this.opts.es5)&&(t.push(":"),(0,ot.addCodeArg)(t,o));return t.push("}"),new ot._Code(t)}if(e,t,n){if(this._blockNode(new zl(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new zl(e))}else(){return this._elseNode(new dd)}endIf(){return this._endBlockNode(zl,dd)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new px(e),t)}forRange(e,t,n,o,i=this.opts.es5?qo.varKinds.var:qo.varKinds.let){let a=this._scope.toName(e);return this._for(new fx(i,a,t,n),()=>o(a))}forOf(e,t,n,o=qo.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let a=t instanceof ot.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ot._)`${a}.length`,s=>{this.var(i,(0,ot._)`${a}[${s}]`),n(i)})}return this._for(new Xb("of",o,i,t),()=>n(i))}forIn(e,t,n,o=this.opts.es5?qo.varKinds.var:qo.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ot._)`Object.keys(${t})`,n);let i=this._scope.toName(e);return this._for(new Xb("in",o,i,t),()=>n(i))}endFor(){return this._endBlockNode($l)}label(e){return this._leafNode(new lx(e))}break(e){return this._leafNode(new cx(e))}return(e){let t=new yf;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(yf)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new hx;if(this._blockNode(o),this.code(e),t){let i=this.name("e");this._currNode=o.catch=new Sf(i),t(i)}return n&&(this._currNode=o.finally=new bf,this.code(n)),this._endBlockNode(Sf,bf)}throw(e){return this._leafNode(new ux(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=ot.nil,n,o){return this._blockNode(new gf(e,t,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(gf)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof zl))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};je.CodeGen=gx;function Hl(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Jb(r,e){return e instanceof ot._CodeOrName?Hl(r,e.names):r}function md(r,e,t){if(r instanceof ot.Name)return n(r);if(!o(r))return r;return new ot._Code(r._items.reduce((i,a)=>(a instanceof ot.Name&&(a=n(a)),a instanceof ot._Code?i.push(...a._items):i.push(a),i),[]));function n(i){let a=t[i.str];return a===void 0||e[i.str]!==1?i:(delete e[i.str],a)}function o(i){return i instanceof ot._Code&&i._items.some(a=>a instanceof ot.Name&&e[a.str]===1&&t[a.str]!==void 0)}}function Hme(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function WW(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ot._)`!${yx(r)}`}je.not=WW;var jme=VW(je.operators.AND);function Gme(...r){return r.reduce(jme)}je.and=Gme;var Wme=VW(je.operators.OR);function Vme(...r){return r.reduce(Wme)}je.or=Vme;function VW(r){return(e,t)=>e===ot.nil?t:t===ot.nil?e:(0,ot._)`${yx(e)} ${r} ${yx(t)}`}function yx(r){return r instanceof ot.Name?r:(0,ot._)`(${r})`}});var lt=Q(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.checkStrictMode=We.getErrorPath=We.Type=We.useFunc=We.setEvaluated=We.evaluatedPropsToName=We.mergeEvaluated=We.eachItem=We.unescapeJsonPointer=We.escapeJsonPointer=We.escapeFragment=We.unescapeFragment=We.schemaRefOrVal=We.schemaHasRulesButRef=We.schemaHasRules=We.checkUnknownRules=We.alwaysValidSchema=We.toHash=void 0;var It=Be(),qme=ff();function Kme(r){let e={};for(let t of r)e[t]=!0;return e}We.toHash=Kme;function Yme(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(YW(r,e),!XW(e,r.self.RULES.all))}We.alwaysValidSchema=Yme;function YW(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let i in e)o[i]||QW(r,`unknown keyword: "${i}"`)}We.checkUnknownRules=YW;function XW(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}We.schemaHasRules=XW;function Xme(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}We.schemaHasRulesButRef=Xme;function Jme({topSchemaRef:r,schemaPath:e},t,n,o){if(!o){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,It._)`${t}`}return(0,It._)`${r}${e}${(0,It.getProperty)(n)}`}We.schemaRefOrVal=Jme;function Zme(r){return JW(decodeURIComponent(r))}We.unescapeFragment=Zme;function Qme(r){return encodeURIComponent(bx(r))}We.escapeFragment=Qme;function bx(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}We.escapeJsonPointer=bx;function JW(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}We.unescapeJsonPointer=JW;function epe(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}We.eachItem=epe;function qW({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(o,i,a,s)=>{let l=a===void 0?i:a instanceof It.Name?(i instanceof It.Name?r(o,i,a):e(o,i,a),a):i instanceof It.Name?(e(o,a,i),i):t(i,a);return s===It.Name&&!(l instanceof It.Name)?n(o,l):l}}We.mergeEvaluated={props:qW({mergeNames:(r,e,t)=>r.if((0,It._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,It._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,It._)`${t} || {}`).code((0,It._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,It._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,It._)`${t} || {}`),Ex(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:ZW}),items:qW({mergeNames:(r,e,t)=>r.if((0,It._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,It._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,It._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,It._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function ZW(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,It._)`{}`);return e!==void 0&&Ex(r,t,e),t}We.evaluatedPropsToName=ZW;function Ex(r,e,t){Object.keys(t).forEach(n=>r.assign((0,It._)`${e}${(0,It.getProperty)(n)}`,!0))}We.setEvaluated=Ex;var KW={};function tpe(r,e){return r.scopeValue("func",{ref:e,code:KW[e.code]||(KW[e.code]=new qme._Code(e.code))})}We.useFunc=tpe;var Sx;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(Sx||(We.Type=Sx={}));function rpe(r,e,t){if(r instanceof It.Name){let n=e===Sx.Num;return t?n?(0,It._)`"[" + ${r} + "]"`:(0,It._)`"['" + ${r} + "']"`:n?(0,It._)`"/" + ${r}`:(0,It._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,It.getProperty)(r).toString():"/"+bx(r)}We.getErrorPath=rpe;function QW(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}We.checkStrictMode=QW});var da=Q(Tx=>{"use strict";Object.defineProperty(Tx,"__esModule",{value:!0});var Zr=Be(),npe={data:new Zr.Name("data"),valCxt:new Zr.Name("valCxt"),instancePath:new Zr.Name("instancePath"),parentData:new Zr.Name("parentData"),parentDataProperty:new Zr.Name("parentDataProperty"),rootData:new Zr.Name("rootData"),dynamicAnchors:new Zr.Name("dynamicAnchors"),vErrors:new Zr.Name("vErrors"),errors:new Zr.Name("errors"),this:new Zr.Name("this"),self:new Zr.Name("self"),scope:new Zr.Name("scope"),json:new Zr.Name("json"),jsonPos:new Zr.Name("jsonPos"),jsonLen:new Zr.Name("jsonLen"),jsonPart:new Zr.Name("jsonPart")};Tx.default=npe});var Ef=Q(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.extendErrors=Qr.resetErrorsCount=Qr.reportExtraError=Qr.reportError=Qr.keyword$DataError=Qr.keywordError=void 0;var ct=Be(),Qb=lt(),bn=da();Qr.keywordError={message:({keyword:r})=>(0,ct.str)`must pass "${r}" keyword validation`};Qr.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ct.str)`"${r}" keyword must be ${e} ($data)`:(0,ct.str)`"${r}" keyword is invalid ($data)`};function ope(r,e=Qr.keywordError,t,n){let{it:o}=r,{gen:i,compositeRule:a,allErrors:s}=o,l=rV(r,e,t);n??(a||s)?eV(i,l):tV(o,(0,ct._)`[${l}]`)}Qr.reportError=ope;function ipe(r,e=Qr.keywordError,t){let{it:n}=r,{gen:o,compositeRule:i,allErrors:a}=n,s=rV(r,e,t);eV(o,s),i||a||tV(n,bn.default.vErrors)}Qr.reportExtraError=ipe;function ape(r,e){r.assign(bn.default.errors,e),r.if((0,ct._)`${bn.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ct._)`${bn.default.vErrors}.length`,e),()=>r.assign(bn.default.vErrors,null)))}Qr.resetErrorsCount=ape;function spe({gen:r,keyword:e,schemaValue:t,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let a=r.name("err");r.forRange("i",o,bn.default.errors,s=>{r.const(a,(0,ct._)`${bn.default.vErrors}[${s}]`),r.if((0,ct._)`${a}.instancePath === undefined`,()=>r.assign((0,ct._)`${a}.instancePath`,(0,ct.strConcat)(bn.default.instancePath,i.errorPath))),r.assign((0,ct._)`${a}.schemaPath`,(0,ct.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(r.assign((0,ct._)`${a}.schema`,t),r.assign((0,ct._)`${a}.data`,n))})}Qr.extendErrors=spe;function eV(r,e){let t=r.const("err",e);r.if((0,ct._)`${bn.default.vErrors} === null`,()=>r.assign(bn.default.vErrors,(0,ct._)`[${t}]`),(0,ct._)`${bn.default.vErrors}.push(${t})`),r.code((0,ct._)`${bn.default.errors}++`)}function tV(r,e){let{gen:t,validateName:n,schemaEnv:o}=r;o.$async?t.throw((0,ct._)`new ${r.ValidationError}(${e})`):(t.assign((0,ct._)`${n}.errors`,e),t.return(!1))}var jl={keyword:new ct.Name("keyword"),schemaPath:new ct.Name("schemaPath"),params:new ct.Name("params"),propertyName:new ct.Name("propertyName"),message:new ct.Name("message"),schema:new ct.Name("schema"),parentSchema:new ct.Name("parentSchema")};function rV(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ct._)`{}`:lpe(r,e,t)}function lpe(r,e,t={}){let{gen:n,it:o}=r,i=[cpe(o,t),upe(r,t)];return dpe(r,e,i),n.object(...i)}function cpe({errorPath:r},{instancePath:e}){let t=e?(0,ct.str)`${r}${(0,Qb.getErrorPath)(e,Qb.Type.Str)}`:r;return[bn.default.instancePath,(0,ct.strConcat)(bn.default.instancePath,t)]}function upe({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let o=n?e:(0,ct.str)`${e}/${r}`;return t&&(o=(0,ct.str)`${o}${(0,Qb.getErrorPath)(t,Qb.Type.Str)}`),[jl.schemaPath,o]}function dpe(r,{params:e,message:t},n){let{keyword:o,data:i,schemaValue:a,it:s}=r,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=s;n.push([jl.keyword,o],[jl.params,typeof e=="function"?e(r):e||(0,ct._)`{}`]),l.messages&&n.push([jl.message,typeof t=="function"?t(r):t]),l.verbose&&n.push([jl.schema,a],[jl.parentSchema,(0,ct._)`${u}${d}`],[bn.default.data,i]),c&&n.push([jl.propertyName,c])}});var oV=Q(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.boolOrEmptySchema=pd.topBoolOrEmptySchema=void 0;var mpe=Ef(),ppe=Be(),fpe=da(),hpe={message:"boolean schema is false"};function gpe(r){let{gen:e,schema:t,validateName:n}=r;t===!1?nV(r,!1):typeof t=="object"&&t.$async===!0?e.return(fpe.default.data):(e.assign((0,ppe._)`${n}.errors`,null),e.return(!0))}pd.topBoolOrEmptySchema=gpe;function ype(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),nV(r)):t.var(e,!0)}pd.boolOrEmptySchema=ype;function nV(r,e){let{gen:t,data:n}=r,o={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,mpe.reportError)(o,hpe,void 0,e)}});var vx=Q(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});fd.getRules=fd.isJSONType=void 0;var Spe=["string","number","integer","boolean","null","object","array"],bpe=new Set(Spe);function Epe(r){return typeof r=="string"&&bpe.has(r)}fd.isJSONType=Epe;function Tpe(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}fd.getRules=Tpe});var Ax=Q(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.shouldUseRule=fs.shouldUseGroup=fs.schemaHasRulesForType=void 0;function vpe({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&iV(r,n)}fs.schemaHasRulesForType=vpe;function iV(r,e){return e.rules.some(t=>aV(r,t))}fs.shouldUseGroup=iV;function aV(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}fs.shouldUseRule=aV});var Tf=Q(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.reportTypeError=en.checkDataTypes=en.checkDataType=en.coerceAndCheckDataType=en.getJSONTypes=en.getSchemaTypes=en.DataType=void 0;var Ape=vx(),wpe=Ax(),Cpe=Ef(),De=Be(),sV=lt(),hd;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(hd||(en.DataType=hd={}));function Rpe(r){let e=lV(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}en.getSchemaTypes=Rpe;function lV(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Ape.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}en.getJSONTypes=lV;function xpe(r,e){let{gen:t,data:n,opts:o}=r,i=_pe(e,o.coerceTypes),a=e.length>0&&!(i.length===0&&e.length===1&&(0,wpe.schemaHasRulesForType)(r,e[0]));if(a){let s=Cx(e,n,o.strictNumbers,hd.Wrong);t.if(s,()=>{i.length?Mpe(r,e,i):Rx(r)})}return a}en.coerceAndCheckDataType=xpe;var cV=new Set(["string","number","integer","boolean","null"]);function _pe(r,e){return e?r.filter(t=>cV.has(t)||e==="array"&&t==="array"):[]}function Mpe(r,e,t){let{gen:n,data:o,opts:i}=r,a=n.let("dataType",(0,De._)`typeof ${o}`),s=n.let("coerced",(0,De._)`undefined`);i.coerceTypes==="array"&&n.if((0,De._)`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,De._)`${o}[0]`).assign(a,(0,De._)`typeof ${o}`).if(Cx(e,o,i.strictNumbers),()=>n.assign(s,o))),n.if((0,De._)`${s} !== undefined`);for(let c of t)(cV.has(c)||c==="array"&&i.coerceTypes==="array")&&l(c);n.else(),Rx(r),n.endIf(),n.if((0,De._)`${s} !== undefined`,()=>{n.assign(o,s),Ppe(r,s)});function l(c){switch(c){case"string":n.elseIf((0,De._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,De._)`"" + ${o}`).elseIf((0,De._)`${o} === null`).assign(s,(0,De._)`""`);return;case"number":n.elseIf((0,De._)`${a} == "boolean" || ${o} === null
6
6
  || (${a} == "string" && ${o} && ${o} == +${o})`).assign(s,(0,De._)`+${o}`);return;case"integer":n.elseIf((0,De._)`${a} === "boolean" || ${o} === null
7
7
  || (${a} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(s,(0,De._)`+${o}`);return;case"boolean":n.elseIf((0,De._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(s,!1).elseIf((0,De._)`${o} === "true" || ${o} === 1`).assign(s,!0);return;case"null":n.elseIf((0,De._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(s,null);return;case"array":n.elseIf((0,De._)`${a} === "string" || ${a} === "number"
8
- || ${a} === "boolean" || ${o} === null`).assign(s,(0,De._)`[${o}]`)}}}function Ppe({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,De._)`${e} !== undefined`,()=>r.assign((0,De._)`${e}[${t}]`,n))}function wx(r,e,t,n=hd.Correct){let o=n===hd.Correct?De.operators.EQ:De.operators.NEQ,i;switch(r){case"null":return(0,De._)`${e} ${o} null`;case"array":i=(0,De._)`Array.isArray(${e})`;break;case"object":i=(0,De._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=a((0,De._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=a();break;default:return(0,De._)`typeof ${e} ${o} ${r}`}return n===hd.Correct?i:(0,De.not)(i);function a(s=De.nil){return(0,De.and)((0,De._)`typeof ${e} == "number"`,s,t?(0,De._)`isFinite(${e})`:De.nil)}}en.checkDataType=wx;function Cx(r,e,t,n){if(r.length===1)return wx(r[0],e,t,n);let o,i=(0,sV.toHash)(r);if(i.array&&i.object){let a=(0,De._)`typeof ${e} != "object"`;o=i.null?a:(0,De._)`!${e} || ${a}`,delete i.null,delete i.array,delete i.object}else o=De.nil;i.number&&delete i.integer;for(let a in i)o=(0,De.and)(o,wx(a,e,t,n));return o}en.checkDataTypes=Cx;var Ipe={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,De._)`{type: ${r}}`:(0,De._)`{type: ${e}}`};function Rx(r){let e=Ope(r);(0,Cpe.reportError)(e,Ipe)}en.reportTypeError=Rx;function Ope(r){let{gen:e,data:t,schema:n}=r,o=(0,sV.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:r}}});var dV=Q(eE=>{"use strict";Object.defineProperty(eE,"__esModule",{value:!0});eE.assignDefaults=void 0;var gd=Be(),Npe=lt();function Lpe(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let o in t)uV(r,o,t[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,i)=>uV(r,i,o.default))}eE.assignDefaults=Lpe;function uV(r,e,t){let{gen:n,compositeRule:o,data:i,opts:a}=r;if(t===void 0)return;let s=(0,gd._)`${i}${(0,gd.getProperty)(e)}`;if(o){(0,Npe.checkStrictMode)(r,`default is ignored for: ${s}`);return}let l=(0,gd._)`${s} === undefined`;a.useDefaults==="empty"&&(l=(0,gd._)`${l} || ${s} === null || ${s} === ""`),n.if(l,(0,gd._)`${s} = ${(0,gd.stringify)(t)}`)}});var xo=Q(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.validateUnion=wt.validateArray=wt.usePattern=wt.callValidateCode=wt.schemaProperties=wt.allSchemaProperties=wt.noPropertyInData=wt.propertyInData=wt.isOwnProperty=wt.hasPropFunc=wt.reportMissingProp=wt.checkMissingProp=wt.checkReportMissingProp=void 0;var Ft=Be(),xx=lt(),hs=da(),Dpe=lt();function kpe(r,e){let{gen:t,data:n,it:o}=r;t.if(Mx(t,n,e,o.opts.ownProperties),()=>{r.setParams({missingProperty:(0,Ft._)`${e}`},!0),r.error()})}wt.checkReportMissingProp=kpe;function Fpe({gen:r,data:e,it:{opts:t}},n,o){return(0,Ft.or)(...n.map(i=>(0,Ft.and)(Mx(r,e,i,t.ownProperties),(0,Ft._)`${o} = ${i}`)))}wt.checkMissingProp=Fpe;function Upe(r,e){r.setParams({missingProperty:e},!0),r.error()}wt.reportMissingProp=Upe;function mV(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ft._)`Object.prototype.hasOwnProperty`})}wt.hasPropFunc=mV;function _x(r,e,t){return(0,Ft._)`${mV(r)}.call(${e}, ${t})`}wt.isOwnProperty=_x;function Bpe(r,e,t,n){let o=(0,Ft._)`${e}${(0,Ft.getProperty)(t)} !== undefined`;return n?(0,Ft._)`${o} && ${_x(r,e,t)}`:o}wt.propertyInData=Bpe;function Mx(r,e,t,n){let o=(0,Ft._)`${e}${(0,Ft.getProperty)(t)} === undefined`;return n?(0,Ft.or)(o,(0,Ft.not)(_x(r,e,t))):o}wt.noPropertyInData=Mx;function pV(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}wt.allSchemaProperties=pV;function zpe(r,e){return pV(e).filter(t=>!(0,xx.alwaysValidSchema)(r,e[t]))}wt.schemaProperties=zpe;function $pe({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:o,errorPath:i},it:a},s,l,c){let u=c?(0,Ft._)`${r}, ${e}, ${n}${o}`:e,d=[[hs.default.instancePath,(0,Ft.strConcat)(hs.default.instancePath,i)],[hs.default.parentData,a.parentData],[hs.default.parentDataProperty,a.parentDataProperty],[hs.default.rootData,hs.default.rootData]];a.opts.dynamicRef&&d.push([hs.default.dynamicAnchors,hs.default.dynamicAnchors]);let m=(0,Ft._)`${u}, ${t.object(...d)}`;return l!==Ft.nil?(0,Ft._)`${s}.call(${l}, ${m})`:(0,Ft._)`${s}(${m})`}wt.callValidateCode=$pe;var Hpe=(0,Ft._)`new RegExp`;function jpe({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(t,n);return r.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Ft._)`${o.code==="new RegExp"?Hpe:(0,Dpe.useFunc)(r,o)}(${t}, ${n})`})}wt.usePattern=jpe;function Gpe(r){let{gen:e,data:t,keyword:n,it:o}=r,i=e.name("valid");if(o.allErrors){let s=e.let("valid",!0);return a(()=>e.assign(s,!1)),s}return e.var(i,!0),a(()=>e.break()),i;function a(s){let l=e.const("len",(0,Ft._)`${t}.length`);e.forRange("i",0,l,c=>{r.subschema({keyword:n,dataProp:c,dataPropType:xx.Type.Num},i),e.if((0,Ft.not)(i),s)})}}wt.validateArray=Gpe;function Wpe(r){let{gen:e,schema:t,keyword:n,it:o}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(l=>(0,xx.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let a=e.let("valid",!1),s=e.name("_valid");e.block(()=>t.forEach((l,c)=>{let u=r.subschema({keyword:n,schemaProp:c,compositeRule:!0},s);e.assign(a,(0,Ft._)`${a} || ${s}`),r.mergeValidEvaluated(u,s)||e.if((0,Ft.not)(a))})),r.result(a,()=>r.reset(),()=>r.error(!0))}wt.validateUnion=Wpe});var gV=Q(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.validateKeywordUsage=Pi.validSchemaType=Pi.funcKeywordCode=Pi.macroKeywordCode=void 0;var En=Be(),Gl=da(),Vpe=xo(),qpe=Ef();function Kpe(r,e){let{gen:t,keyword:n,schema:o,parentSchema:i,it:a}=r,s=e.macro.call(a.self,o,i,a),l=hV(t,n,s);a.opts.validateSchema!==!1&&a.self.validateSchema(s,!0);let c=t.name("valid");r.subschema({schema:s,schemaPath:En.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),r.pass(c,()=>r.error(!0))}Pi.macroKeywordCode=Kpe;function Ype(r,e){var t;let{gen:n,keyword:o,schema:i,parentSchema:a,$data:s,it:l}=r;Jpe(l,e);let c=!s&&e.compile?e.compile.call(l.self,i,a,l):e.validate,u=hV(n,o,c),d=n.let("valid");r.block$data(d,m),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function m(){if(e.errors===!1)h(),e.modifying&&fV(r),g(()=>r.error());else{let y=e.async?p():f();e.modifying&&fV(r),g(()=>Xpe(r,y))}}function p(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,En._)`await `),b=>n.assign(d,!1).if((0,En._)`${b} instanceof ${l.ValidationError}`,()=>n.assign(y,(0,En._)`${b}.errors`),()=>n.throw(b))),y}function f(){let y=(0,En._)`${u}.errors`;return n.assign(y,null),h(En.nil),y}function h(y=e.async?(0,En._)`await `:En.nil){let b=l.opts.passContext?Gl.default.this:Gl.default.self,E=!("compile"in e&&!s||e.schema===!1);n.assign(d,(0,En._)`${y}${(0,Vpe.callValidateCode)(r,u,b,E)}`,e.modifying)}function g(y){var b;n.if((0,En.not)((b=e.valid)!==null&&b!==void 0?b:d),y)}}Pi.funcKeywordCode=Ype;function fV(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,En._)`${n.parentData}[${n.parentDataProperty}]`))}function Xpe(r,e){let{gen:t}=r;t.if((0,En._)`Array.isArray(${e})`,()=>{t.assign(Gl.default.vErrors,(0,En._)`${Gl.default.vErrors} === null ? ${e} : ${Gl.default.vErrors}.concat(${e})`).assign(Gl.default.errors,(0,En._)`${Gl.default.vErrors}.length`),(0,qpe.extendErrors)(r)},()=>r.error())}function Jpe({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function hV(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,En.stringify)(t)})}function Zpe(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}Pi.validSchemaType=Zpe;function Qpe({schema:r,opts:e,self:t,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let a=o.dependencies;if(a?.some(s=>!Object.prototype.hasOwnProperty.call(r,s)))throw new Error(`parent schema must have dependencies of ${i}: ${a.join(",")}`);if(o.validateSchema&&!o.validateSchema(r[i])){let l=`keyword "${i}" value is invalid at path "${n}": `+t.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(l);else throw new Error(l)}}Pi.validateKeywordUsage=Qpe});var SV=Q(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.extendSubschemaMode=gs.extendSubschemaData=gs.getSubschema=void 0;var Ii=Be(),yV=lt();function efe(r,{keyword:e,schemaProp:t,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:a}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let s=r.schema[e];return t===void 0?{schema:s,schemaPath:(0,Ii._)`${r.schemaPath}${(0,Ii.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:s[t],schemaPath:(0,Ii._)`${r.schemaPath}${(0,Ii.getProperty)(e)}${(0,Ii.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,yV.escapeFragment)(t)}`}}if(n!==void 0){if(o===void 0||i===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:a,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}gs.getSubschema=efe;function tfe(r,e,{dataProp:t,dataPropType:n,data:o,dataTypes:i,propertyName:a}){if(o!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=e;if(t!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=e,m=s.let("data",(0,Ii._)`${e.data}${(0,Ii.getProperty)(t)}`,!0);l(m),r.errorPath=(0,Ii.str)`${c}${(0,yV.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,Ii._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(o!==void 0){let c=o instanceof Ii.Name?o:s.let("data",o,!0);l(c),a!==void 0&&(r.propertyName=a)}i&&(r.dataTypes=i);function l(c){r.data=c,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,c]}}gs.extendSubschemaData=tfe;function rfe(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(r.compositeRule=n),o!==void 0&&(r.createErrors=o),i!==void 0&&(r.allErrors=i),r.jtdDiscriminator=e,r.jtdMetadata=t}gs.extendSubschemaMode=rfe});var Px=Q((R$t,bV)=>{"use strict";bV.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,o,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(o=n;o--!==0;)if(!r(e[o],t[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[o]))return!1;for(o=n;o--!==0;){var a=i[o];if(!r(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}});var TV=Q((x$t,EV)=>{"use strict";var ys=EV.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},o=t.post||function(){};tE(e,n,o,r,"",r)};ys.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ys.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ys.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ys.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function tE(r,e,t,n,o,i,a,s,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,i,a,s,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in ys.arrayKeywords)for(var m=0;m<d.length;m++)tE(r,e,t,d[m],o+"/"+u+"/"+m,i,o,u,n,m)}else if(u in ys.propsKeywords){if(d&&typeof d=="object")for(var p in d)tE(r,e,t,d[p],o+"/"+u+"/"+nfe(p),i,o,u,n,p)}else(u in ys.keywords||r.allKeys&&!(u in ys.skipKeywords))&&tE(r,e,t,d,o+"/"+u,i,o,u,n)}t(n,o,i,a,s,l,c)}}function nfe(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}});var vf=Q(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.getSchemaRefs=Nn.resolveUrl=Nn.normalizeId=Nn._getFullPath=Nn.getFullPath=Nn.inlineRef=void 0;var ofe=lt(),ife=Px(),afe=TV(),sfe=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function lfe(r,e=!0){return typeof r=="boolean"?!0:e===!0?!Ix(r):e?vV(r)<=e:!1}Nn.inlineRef=lfe;var cfe=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ix(r){for(let e in r){if(cfe.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(Ix)||typeof t=="object"&&Ix(t))return!0}return!1}function vV(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!sfe.has(t)&&(typeof r[t]=="object"&&(0,ofe.eachItem)(r[t],n=>e+=vV(n)),e===1/0))return 1/0}return e}function AV(r,e="",t){t!==!1&&(e=yd(e));let n=r.parse(e);return wV(r,n)}Nn.getFullPath=AV;function wV(r,e){return r.serialize(e).split("#")[0]+"#"}Nn._getFullPath=wV;var ufe=/#\/?$/;function yd(r){return r?r.replace(ufe,""):""}Nn.normalizeId=yd;function dfe(r,e,t){return t=yd(t),r.resolve(e,t)}Nn.resolveUrl=dfe;var mfe=/^[a-z_][-a-z0-9._]*$/i;function pfe(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,o=yd(r[t]||e),i={"":o},a=AV(n,o,!1),s={},l=new Set;return afe(r,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let h=a+m,g=i[f];typeof d[t]=="string"&&(g=y.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[m]=g;function y(E){let v=this.opts.uriResolver.resolve;if(E=yd(g?v(g,E):E),l.has(E))throw u(E);l.add(E);let w=this.refs[E];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?c(d,w.schema,E):E!==yd(h)&&(E[0]==="#"?(c(d,s[E],E),s[E]=d):this.refs[E]=h),E}function b(E){if(typeof E=="string"){if(!mfe.test(E))throw new Error(`invalid anchor "${E}"`);y.call(this,`#${E}`)}}}),s;function c(d,m,p){if(m!==void 0&&!ife(d,m))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Nn.getSchemaRefs=pfe});var Cf=Q(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.getData=Ss.KeywordCxt=Ss.validateFunctionCode=void 0;var MV=oV(),CV=Tf(),Nx=Ax(),rE=Tf(),ffe=dV(),wf=gV(),Ox=SV(),ue=Be(),Re=da(),hfe=vf(),ma=lt(),Af=Ef();function gfe(r){if(OV(r)&&(NV(r),IV(r))){bfe(r);return}PV(r,()=>(0,MV.topBoolOrEmptySchema)(r))}Ss.validateFunctionCode=gfe;function PV({gen:r,validateName:e,schema:t,schemaEnv:n,opts:o},i){o.code.es5?r.func(e,(0,ue._)`${Re.default.data}, ${Re.default.valCxt}`,n.$async,()=>{r.code((0,ue._)`"use strict"; ${RV(t,o)}`),Sfe(r,o),r.code(i)}):r.func(e,(0,ue._)`${Re.default.data}, ${yfe(o)}`,n.$async,()=>r.code(RV(t,o)).code(i))}function yfe(r){return(0,ue._)`{${Re.default.instancePath}="", ${Re.default.parentData}, ${Re.default.parentDataProperty}, ${Re.default.rootData}=${Re.default.data}${r.dynamicRef?(0,ue._)`, ${Re.default.dynamicAnchors}={}`:ue.nil}}={}`}function Sfe(r,e){r.if(Re.default.valCxt,()=>{r.var(Re.default.instancePath,(0,ue._)`${Re.default.valCxt}.${Re.default.instancePath}`),r.var(Re.default.parentData,(0,ue._)`${Re.default.valCxt}.${Re.default.parentData}`),r.var(Re.default.parentDataProperty,(0,ue._)`${Re.default.valCxt}.${Re.default.parentDataProperty}`),r.var(Re.default.rootData,(0,ue._)`${Re.default.valCxt}.${Re.default.rootData}`),e.dynamicRef&&r.var(Re.default.dynamicAnchors,(0,ue._)`${Re.default.valCxt}.${Re.default.dynamicAnchors}`)},()=>{r.var(Re.default.instancePath,(0,ue._)`""`),r.var(Re.default.parentData,(0,ue._)`undefined`),r.var(Re.default.parentDataProperty,(0,ue._)`undefined`),r.var(Re.default.rootData,Re.default.data),e.dynamicRef&&r.var(Re.default.dynamicAnchors,(0,ue._)`{}`)})}function bfe(r){let{schema:e,opts:t,gen:n}=r;PV(r,()=>{t.$comment&&e.$comment&&DV(r),wfe(r),n.let(Re.default.vErrors,null),n.let(Re.default.errors,0),t.unevaluated&&Efe(r),LV(r),xfe(r)})}function Efe(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,ue._)`${t}.evaluated`),e.if((0,ue._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,ue._)`${r.evaluated}.props`,(0,ue._)`undefined`)),e.if((0,ue._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,ue._)`${r.evaluated}.items`,(0,ue._)`undefined`))}function RV(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,ue._)`/*# sourceURL=${t} */`:ue.nil}function Tfe(r,e){if(OV(r)&&(NV(r),IV(r))){vfe(r,e);return}(0,MV.boolOrEmptySchema)(r,e)}function IV({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function OV(r){return typeof r.schema!="boolean"}function vfe(r,e){let{schema:t,gen:n,opts:o}=r;o.$comment&&t.$comment&&DV(r),Cfe(r),Rfe(r);let i=n.const("_errs",Re.default.errors);LV(r,i),n.var(e,(0,ue._)`${i} === ${Re.default.errors}`)}function NV(r){(0,ma.checkUnknownRules)(r),Afe(r)}function LV(r,e){if(r.opts.jtd)return xV(r,[],!1,e);let t=(0,CV.getSchemaTypes)(r.schema),n=(0,CV.coerceAndCheckDataType)(r,t);xV(r,t,!n,e)}function Afe(r){let{schema:e,errSchemaPath:t,opts:n,self:o}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,ma.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function wfe(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,ma.checkStrictMode)(r,"default is ignored in the schema root")}function Cfe(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,hfe.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function Rfe(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function DV({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:o}){let i=t.$comment;if(o.$comment===!0)r.code((0,ue._)`${Re.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let a=(0,ue.str)`${n}/$comment`,s=r.scopeValue("root",{ref:e.root});r.code((0,ue._)`${Re.default.self}.opts.$comment(${i}, ${a}, ${s}.schema)`)}}function xfe(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:o,opts:i}=r;t.$async?e.if((0,ue._)`${Re.default.errors} === 0`,()=>e.return(Re.default.data),()=>e.throw((0,ue._)`new ${o}(${Re.default.vErrors})`)):(e.assign((0,ue._)`${n}.errors`,Re.default.vErrors),i.unevaluated&&_fe(r),e.return((0,ue._)`${Re.default.errors} === 0`))}function _fe({gen:r,evaluated:e,props:t,items:n}){t instanceof ue.Name&&r.assign((0,ue._)`${e}.props`,t),n instanceof ue.Name&&r.assign((0,ue._)`${e}.items`,n)}function xV(r,e,t,n){let{gen:o,schema:i,data:a,allErrors:s,opts:l,self:c}=r,{RULES:u}=c;if(i.$ref&&(l.ignoreKeywordsWithRef||!(0,ma.schemaHasRulesButRef)(i,u))){o.block(()=>FV(r,"$ref",u.all.$ref.definition));return}l.jtd||Mfe(r,e),o.block(()=>{for(let m of u.rules)d(m);d(u.post)});function d(m){(0,Nx.shouldUseGroup)(i,m)&&(m.type?(o.if((0,rE.checkDataType)(m.type,a,l.strictNumbers)),_V(r,m),e.length===1&&e[0]===m.type&&t&&(o.else(),(0,rE.reportTypeError)(r)),o.endIf()):_V(r,m),s||o.if((0,ue._)`${Re.default.errors} === ${n||0}`))}}function _V(r,e){let{gen:t,schema:n,opts:{useDefaults:o}}=r;o&&(0,ffe.assignDefaults)(r,e.type),t.block(()=>{for(let i of e.rules)(0,Nx.shouldUseRule)(n,i)&&FV(r,i.keyword,i.definition,e.type)})}function Mfe(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(Pfe(r,e),r.opts.allowUnionTypes||Ife(r,e),Ofe(r,r.dataTypes))}function Pfe(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{kV(r.dataTypes,t)||Lx(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),Lfe(r,e)}}function Ife(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Lx(r,"use allowUnionTypes to allow union type keyword")}function Ofe(r,e){let t=r.self.RULES.all;for(let n in t){let o=t[n];if(typeof o=="object"&&(0,Nx.shouldUseRule)(r.schema,o)){let{type:i}=o.definition;i.length&&!i.some(a=>Nfe(e,a))&&Lx(r,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Nfe(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function kV(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function Lfe(r,e){let t=[];for(let n of r.dataTypes)kV(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function Lx(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,ma.checkStrictMode)(r,e,r.opts.strictTypes)}var nE=class{constructor(e,t,n){if((0,wf.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ma.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",UV(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,wf.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Re.default.errors))}result(e,t,n){this.failResult((0,ue.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,ue.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,ue._)`${t} !== undefined && (${(0,ue.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Af.reportExtraError:Af.reportError)(this,this.def.error,t)}$dataError(){(0,Af.reportError)(this,this.def.$dataError||Af.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Af.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=ue.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=ue.nil,t=ue.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:a}=this;n.if((0,ue.or)((0,ue._)`${o} === undefined`,t)),e!==ue.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==ue.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:o,it:i}=this;return(0,ue.or)(a(),s());function a(){if(n.length){if(!(t instanceof ue.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,ue._)`${(0,rE.checkDataTypes)(l,t,i.opts.strictNumbers,rE.DataType.Wrong)}`}return ue.nil}function s(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,ue._)`!${l}(${t})`}return ue.nil}}subschema(e,t){let n=(0,Ox.getSubschema)(this.it,e);(0,Ox.extendSubschemaData)(n,this.it,e),(0,Ox.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Tfe(o,t),o}mergeEvaluated(e,t){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ma.mergeEvaluated.props(o,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=ma.mergeEvaluated.items(o,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(t,()=>this.mergeEvaluated(e,ue.Name)),!0}};Ss.KeywordCxt=nE;function FV(r,e,t,n){let o=new nE(r,t,e);"code"in t?t.code(o,n):o.$data&&t.validate?(0,wf.funcKeywordCode)(o,t):"macro"in t?(0,wf.macroKeywordCode)(o,t):(t.compile||t.validate)&&(0,wf.funcKeywordCode)(o,t)}var Dfe=/^\/(?:[^~]|~0|~1)*$/,kfe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function UV(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let o,i;if(r==="")return Re.default.rootData;if(r[0]==="/"){if(!Dfe.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);o=r,i=Re.default.rootData}else{let c=kfe.exec(r);if(!c)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+c[1];if(o=c[2],o==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(i=t[e-u],!o)return i}let a=i,s=o.split("/");for(let c of s)c&&(i=(0,ue._)`${i}${(0,ue.getProperty)((0,ma.unescapeJsonPointer)(c))}`,a=(0,ue._)`${a} && ${i}`);return a;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}Ss.getData=UV});var oE=Q(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});var Dx=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kx.default=Dx});var Rf=Q(Bx=>{"use strict";Object.defineProperty(Bx,"__esModule",{value:!0});var Fx=vf(),Ux=class extends Error{constructor(e,t,n,o){super(o||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Fx.resolveUrl)(e,t,n),this.missingSchema=(0,Fx.normalizeId)((0,Fx.getFullPath)(e,this.missingRef))}};Bx.default=Ux});var aE=Q(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.resolveSchema=_o.getCompilingSchema=_o.resolveRef=_o.compileSchema=_o.SchemaEnv=void 0;var Ko=Be(),Ffe=oE(),Wl=da(),Yo=vf(),BV=lt(),Ufe=Cf(),Sd=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Yo.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};_o.SchemaEnv=Sd;function $x(r){let e=zV.call(this,r);if(e)return e;let t=(0,Yo.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,a=new Ko.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),s;r.$async&&(s=a.scopeValue("Error",{ref:Ffe.default,code:(0,Ko._)`require("ajv/dist/runtime/validation_error").default`}));let l=a.scopeName("validate");r.validateName=l;let c={gen:a,allErrors:this.opts.allErrors,data:Wl.default.data,parentData:Wl.default.parentData,parentDataProperty:Wl.default.parentDataProperty,dataNames:[Wl.default.data],dataPathArr:[Ko.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Ko.stringify)(r.schema)}:{ref:r.schema}),validateName:l,ValidationError:s,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Ko.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ko._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,Ufe.validateFunctionCode)(c),a.optimize(this.opts.code.optimize);let d=a.toString();u=`${a.scopeRefs(Wl.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${Wl.default.self}`,`${Wl.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:d,scopeValues:a._values}),this.opts.unevaluated){let{props:f,items:h}=c;p.evaluated={props:f instanceof Ko.Name?void 0:f,items:h instanceof Ko.Name?void 0:h,dynamicProps:f instanceof Ko.Name,dynamicItems:h instanceof Ko.Name},p.source&&(p.source.evaluated=(0,Ko.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}_o.compileSchema=$x;function Bfe(r,e,t){var n;t=(0,Yo.resolveUrl)(this.opts.uriResolver,e,t);let o=r.refs[t];if(o)return o;let i=Hfe.call(this,r,t);if(i===void 0){let a=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:s}=this.opts;a&&(i=new Sd({schema:a,schemaId:s,root:r,baseId:e}))}if(i!==void 0)return r.refs[t]=zfe.call(this,i)}_o.resolveRef=Bfe;function zfe(r){return(0,Yo.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:$x.call(this,r)}function zV(r){for(let e of this._compilations)if($fe(e,r))return e}_o.getCompilingSchema=zV;function $fe(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function Hfe(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||iE.call(this,r,e)}function iE(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Yo._getFullPath)(this.opts.uriResolver,t),o=(0,Yo.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===o)return zx.call(this,t,r);let i=(0,Yo.normalizeId)(n),a=this.refs[i]||this.schemas[i];if(typeof a=="string"){let s=iE.call(this,r,a);return typeof s?.schema!="object"?void 0:zx.call(this,t,s)}if(typeof a?.schema=="object"){if(a.validate||$x.call(this,a),i===(0,Yo.normalizeId)(e)){let{schema:s}=a,{schemaId:l}=this.opts,c=s[l];return c&&(o=(0,Yo.resolveUrl)(this.opts.uriResolver,o,c)),new Sd({schema:s,schemaId:l,root:r,baseId:o})}return zx.call(this,t,a)}}_o.resolveSchema=iE;var jfe=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zx(r,{baseId:e,schema:t,root:n}){var o;if(((o=r.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let s of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let l=t[(0,BV.unescapeFragment)(s)];if(l===void 0)return;t=l;let c=typeof t=="object"&&t[this.opts.schemaId];!jfe.has(s)&&c&&(e=(0,Yo.resolveUrl)(this.opts.uriResolver,e,c))}let i;if(typeof t!="boolean"&&t.$ref&&!(0,BV.schemaHasRulesButRef)(t,this.RULES)){let s=(0,Yo.resolveUrl)(this.opts.uriResolver,e,t.$ref);i=iE.call(this,n,s)}let{schemaId:a}=this.opts;if(i=i||new Sd({schema:t,schemaId:a,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var $V=Q((N$t,Gfe)=>{Gfe.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var jV=Q((L$t,HV)=>{"use strict";var Wfe={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};HV.exports={HEX:Wfe}});var JV=Q((D$t,XV)=>{"use strict";var{HEX:Vfe}=jV(),qfe=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function qV(r){if(YV(r,".")<3)return{host:r,isIPV4:!1};let e=r.match(qfe)||[],[t]=e;return t?{host:Yfe(t,"."),isIPV4:!0}:{host:r,isIPV4:!1}}function Hx(r,e=!1){let t="",n=!0;for(let o of r){if(Vfe[o]===void 0)return;o!=="0"&&n===!0&&(n=!1),n||(t+=o)}return e&&t.length===0&&(t="0"),t}function Kfe(r){let e=0,t={error:!1,address:"",zone:""},n=[],o=[],i=!1,a=!1,s=!1;function l(){if(o.length){if(i===!1){let c=Hx(o);if(c!==void 0)n.push(c);else return t.error=!0,!1}o.length=0}return!0}for(let c=0;c<r.length;c++){let u=r[c];if(!(u==="["||u==="]"))if(u===":"){if(a===!0&&(s=!0),!l())break;if(e++,n.push(":"),e>7){t.error=!0;break}c-1>=0&&r[c-1]===":"&&(a=!0);continue}else if(u==="%"){if(!l())break;i=!0}else{o.push(u);continue}}return o.length&&(i?t.zone=o.join(""):s?n.push(o.join("")):n.push(Hx(o))),t.address=n.join(""),t}function KV(r){if(YV(r,":")<2)return{host:r,isIPV6:!1};let e=Kfe(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,escapedHost:n,isIPV6:!0}}}function Yfe(r,e){let t="",n=!0,o=r.length;for(let i=0;i<o;i++){let a=r[i];a==="0"&&n?(i+1<=o&&r[i+1]===e||i+1===o)&&(t+=a,n=!1):(a===e?n=!0:n=!1,t+=a)}return t}function YV(r,e){let t=0;for(let n=0;n<r.length;n++)r[n]===e&&t++;return t}var GV=/^\.\.?\//u,WV=/^\/\.(?:\/|$)/u,VV=/^\/\.\.(?:\/|$)/u,Xfe=/^\/?(?:.|\n)*?(?=\/|$)/u;function Jfe(r){let e=[];for(;r.length;)if(r.match(GV))r=r.replace(GV,"");else if(r.match(WV))r=r.replace(WV,"/");else if(r.match(VV))r=r.replace(VV,"/"),e.pop();else if(r==="."||r==="..")r="";else{let t=r.match(Xfe);if(t){let n=t[0];r=r.slice(n.length),e.push(n)}else throw new Error("Unexpected dot segment condition")}return e.join("")}function Zfe(r,e){let t=e!==!0?escape:unescape;return r.scheme!==void 0&&(r.scheme=t(r.scheme)),r.userinfo!==void 0&&(r.userinfo=t(r.userinfo)),r.host!==void 0&&(r.host=t(r.host)),r.path!==void 0&&(r.path=t(r.path)),r.query!==void 0&&(r.query=t(r.query)),r.fragment!==void 0&&(r.fragment=t(r.fragment)),r}function Qfe(r){let e=[];if(r.userinfo!==void 0&&(e.push(r.userinfo),e.push("@")),r.host!==void 0){let t=unescape(r.host),n=qV(t);if(n.isIPV4)t=n.host;else{let o=KV(n.host);o.isIPV6===!0?t=`[${o.escapedHost}]`:t=r.host}e.push(t)}return(typeof r.port=="number"||typeof r.port=="string")&&(e.push(":"),e.push(String(r.port))),e.length?e.join(""):void 0}XV.exports={recomposeAuthority:Qfe,normalizeComponentEncoding:Zfe,removeDotSegments:Jfe,normalizeIPv4:qV,normalizeIPv6:KV,stringArrayToHexStripped:Hx}});var nq=Q((k$t,rq)=>{"use strict";var ehe=/^[\da-f]{8}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{12}$/iu,the=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function ZV(r){return typeof r.secure=="boolean"?r.secure:String(r.scheme).toLowerCase()==="wss"}function QV(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function eq(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function rhe(r){return r.secure=ZV(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function nhe(r){if((r.port===(ZV(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function ohe(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(the);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let o=`${n}:${e.nid||r.nid}`,i=jx[o];r.path=void 0,i&&(r=i.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ihe(r,e){let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),o=`${t}:${e.nid||n}`,i=jx[o];i&&(r=i.serialize(r,e));let a=r,s=r.nss;return a.path=`${n||e.nid}:${s}`,e.skipEscape=!0,a}function ahe(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!ehe.test(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function she(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var tq={scheme:"http",domainHost:!0,parse:QV,serialize:eq},lhe={scheme:"https",domainHost:tq.domainHost,parse:QV,serialize:eq},sE={scheme:"ws",domainHost:!0,parse:rhe,serialize:nhe},che={scheme:"wss",domainHost:sE.domainHost,parse:sE.parse,serialize:sE.serialize},uhe={scheme:"urn",parse:ohe,serialize:ihe,skipNormalize:!0},dhe={scheme:"urn:uuid",parse:ahe,serialize:she,skipNormalize:!0},jx={http:tq,https:lhe,ws:sE,wss:che,urn:uhe,"urn:uuid":dhe};rq.exports=jx});var iq=Q((F$t,cE)=>{"use strict";var{normalizeIPv6:mhe,normalizeIPv4:phe,removeDotSegments:xf,recomposeAuthority:fhe,normalizeComponentEncoding:lE}=JV(),Gx=nq();function hhe(r,e){return typeof r=="string"?r=Oi(pa(r,e),e):typeof r=="object"&&(r=pa(Oi(r,e),e)),r}function ghe(r,e,t){let n=Object.assign({scheme:"null"},t),o=oq(pa(r,n),pa(e,n),n,!0);return Oi(o,{...n,skipEscape:!0})}function oq(r,e,t,n){let o={};return n||(r=pa(Oi(r,t),t),e=pa(Oi(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=xf(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=xf(e.path||""),o.query=e.query):(e.path?(e.path.charAt(0)==="/"?o.path=xf(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?o.path="/"+e.path:r.path?o.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=xf(o.path)),o.query=e.query):(o.path=r.path,e.query!==void 0?o.query=e.query:o.query=r.query),o.userinfo=r.userinfo,o.host=r.host,o.port=r.port),o.scheme=r.scheme),o.fragment=e.fragment,o}function yhe(r,e,t){return typeof r=="string"?(r=unescape(r),r=Oi(lE(pa(r,t),!0),{...t,skipEscape:!0})):typeof r=="object"&&(r=Oi(lE(r,!0),{...t,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Oi(lE(pa(e,t),!0),{...t,skipEscape:!0})):typeof e=="object"&&(e=Oi(lE(e,!0),{...t,skipEscape:!0})),r.toLowerCase()===e.toLowerCase()}function Oi(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),o=[],i=Gx[(n.scheme||t.scheme||"").toLowerCase()];i?.serialize&&i.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&o.push(t.scheme,":");let a=fhe(t);if(a!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(a),t.path&&t.path.charAt(0)!=="/"&&o.push("/")),t.path!==void 0){let s=t.path;!n.absolutePath&&(!i||!i.absolutePath)&&(s=xf(s)),a===void 0&&(s=s.replace(/^\/\//u,"/%2F")),o.push(s)}return t.query!==void 0&&o.push("?",t.query),t.fragment!==void 0&&o.push("#",t.fragment),o.join("")}var She=Array.from({length:127},(r,e)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(e)));function bhe(r){let e=0;for(let t=0,n=r.length;t<n;++t)if(e=r.charCodeAt(t),e>126||She[e])return!0;return!1}var Ehe=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function pa(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=r.indexOf("%")!==-1,i=!1;t.reference==="suffix"&&(r=(t.scheme?t.scheme+":":"")+"//"+r);let a=r.match(Ehe);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host){let l=phe(n.host);if(l.isIPV4===!1){let c=mhe(l.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else n.host=l.host,i=!0}n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&!n.path&&n.query===void 0?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let s=Gx[(t.scheme||n.scheme||"").toLowerCase()];if(!t.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(t.domainHost||s?.domainHost)&&i===!1&&bhe(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}(!s||s&&!s.skipNormalize)&&(o&&n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),o&&n.host!==void 0&&(n.host=unescape(n.host)),n.path?.length&&(n.path=escape(unescape(n.path))),n.fragment?.length&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s?.parse&&s.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var Wx={SCHEMES:Gx,normalize:hhe,resolve:ghe,resolveComponents:oq,equal:yhe,serialize:Oi,parse:pa};cE.exports=Wx;cE.exports.default=Wx;cE.exports.fastUri=Wx});var sq=Q(Vx=>{"use strict";Object.defineProperty(Vx,"__esModule",{value:!0});var aq=iq();aq.code='require("ajv/dist/runtime/uri").default';Vx.default=aq});var hq=Q(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.CodeGen=Ur.Name=Ur.nil=Ur.stringify=Ur.str=Ur._=Ur.KeywordCxt=void 0;var The=Cf();Object.defineProperty(Ur,"KeywordCxt",{enumerable:!0,get:function(){return The.KeywordCxt}});var bd=Be();Object.defineProperty(Ur,"_",{enumerable:!0,get:function(){return bd._}});Object.defineProperty(Ur,"str",{enumerable:!0,get:function(){return bd.str}});Object.defineProperty(Ur,"stringify",{enumerable:!0,get:function(){return bd.stringify}});Object.defineProperty(Ur,"nil",{enumerable:!0,get:function(){return bd.nil}});Object.defineProperty(Ur,"Name",{enumerable:!0,get:function(){return bd.Name}});Object.defineProperty(Ur,"CodeGen",{enumerable:!0,get:function(){return bd.CodeGen}});var vhe=oE(),mq=Rf(),Ahe=vx(),_f=aE(),whe=Be(),Mf=vf(),uE=Tf(),Kx=lt(),lq=$V(),Che=sq(),pq=(r,e)=>new RegExp(r,e);pq.code="new RegExp";var Rhe=["removeAdditional","useDefaults","coerceTypes"],xhe=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_he={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Mhe={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cq=200;function Phe(r){var e,t,n,o,i,a,s,l,c,u,d,m,p,f,h,g,y,b,E,v,w,L,I,A,_;let O=r.strict,k=(e=r.code)===null||e===void 0?void 0:e.optimize,D=k===!0||k===void 0?1:k||0,j=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:pq,$=(o=r.uriResolver)!==null&&o!==void 0?o:Che.default;return{strictSchema:(a=(i=r.strictSchema)!==null&&i!==void 0?i:O)!==null&&a!==void 0?a:!0,strictNumbers:(l=(s=r.strictNumbers)!==null&&s!==void 0?s:O)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=r.strictTypes)!==null&&c!==void 0?c:O)!==null&&u!==void 0?u:"log",strictTuples:(m=(d=r.strictTuples)!==null&&d!==void 0?d:O)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=r.strictRequired)!==null&&p!==void 0?p:O)!==null&&f!==void 0?f:!1,code:r.code?{...r.code,optimize:D,regExp:j}:{optimize:D,regExp:j},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:cq,loopEnum:(g=r.loopEnum)!==null&&g!==void 0?g:cq,meta:(y=r.meta)!==null&&y!==void 0?y:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(E=r.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(v=r.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(w=r.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(L=r.validateSchema)!==null&&L!==void 0?L:!0,validateFormats:(I=r.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(A=r.unicodeRegExp)!==null&&A!==void 0?A:!0,int32range:(_=r.int32range)!==null&&_!==void 0?_:!0,uriResolver:$}}var Pf=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Phe(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new whe.ValueScope({scope:{},prefixes:xhe,es5:t,lines:n}),this.logger=khe(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ahe.getRules)(),uq.call(this,_he,e,"NOT SUPPORTED"),uq.call(this,Mhe,e,"DEPRECATED","warn"),this._metaOpts=Lhe.call(this),e.formats&&Ohe.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Nhe.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ihe.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,o=lq;n==="id"&&(o={...lq},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(t);return"$async"in n||(this.errors=n.errors),o}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,t);async function o(u,d){await i.call(this,u.$schema);let m=this._addSchema(u,d);return m.validate||a.call(this,m)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function a(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof mq.default))throw d;return s.call(this,d),await l.call(this,d.missingSchema),a.call(this,u)}}function s({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let a of e)this.addSchema(a,void 0,n,o);return this}let i;if(typeof e=="object"){let{schemaId:a}=this.opts;if(i=e[a],i!==void 0&&typeof i!="string")throw new Error(`schema ${a} must be string`)}return t=(0,Mf.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,o,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&t){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let t;for(;typeof(t=dq.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,o=new _f.SchemaEnv({schema:{},schemaId:n});if(t=_f.resolveSchema.call(this,o,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=dq.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,Mf.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Uhe.call(this,n,t),!t)return(0,Kx.eachItem)(n,i=>qx.call(this,i)),this;zhe.call(this,t);let o={...t,type:(0,uE.getJSONTypes)(t.type),schemaType:(0,uE.getJSONTypes)(t.schemaType)};return(0,Kx.eachItem)(n,o.type.length===0?i=>qx.call(this,i,o):i=>o.type.forEach(a=>qx.call(this,i,o,a))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let o=n.rules.findIndex(i=>i.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+t+i)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of t){let i=o.split("/").slice(1),a=e;for(let s of i)a=a[s];for(let s in n){let l=n[s];if(typeof l!="object")continue;let{$data:c}=l.definition,u=a[s];c&&u&&(a[s]=fq(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let o=e[n];(!t||t.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,t,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e=="object")a=e[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,Mf.normalizeId)(a||n);let c=Mf.getSchemaRefs.call(this,e,n);return l=new _f.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:c}),this._cache.set(l.schema,l),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):_f.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{_f.compileSchema.call(this,e)}finally{this.opts=t}}};Pf.ValidationError=vhe.default;Pf.MissingRefError=mq.default;Ur.default=Pf;function uq(r,e,t,n="error"){for(let o in r){let i=o;i in e&&this.logger[n](`${t}: option ${o}. ${r[i]}`)}}function dq(r){return r=(0,Mf.normalizeId)(r),this.schemas[r]||this.refs[r]}function Ihe(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function Ohe(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function Nhe(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function Lhe(){let r={...this.opts};for(let e of Rhe)delete r[e];return r}var Dhe={log(){},warn(){},error(){}};function khe(r){if(r===!1)return Dhe;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var Fhe=/^[a-z_$][a-z0-9_$:-]*$/i;function Uhe(r,e){let{RULES:t}=this;if((0,Kx.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Fhe.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function qx(r,e,t){var n;let o=e?.post;if(t&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,a=o?i.post:i.rules.find(({type:l})=>l===t);if(a||(a={type:t,rules:[]},i.rules.push(a)),i.keywords[r]=!0,!e)return;let s={keyword:r,definition:{...e,type:(0,uE.getJSONTypes)(e.type),schemaType:(0,uE.getJSONTypes)(e.schemaType)}};e.before?Bhe.call(this,a,s,e.before):a.rules.push(s),i.all[r]=s,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function Bhe(r,e,t){let n=r.rules.findIndex(o=>o.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function zhe(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=fq(e)),r.validateSchema=this.compile(e,!0))}var $he={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fq(r){return{anyOf:[r,$he]}}});var gq=Q(Yx=>{"use strict";Object.defineProperty(Yx,"__esModule",{value:!0});var Hhe={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Yx.default=Hhe});var Eq=Q(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});Vl.callRef=Vl.getValidate=void 0;var jhe=Rf(),yq=xo(),Ln=Be(),Ed=da(),Sq=aE(),dE=lt(),Ghe={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:o,schemaEnv:i,validateName:a,opts:s,self:l}=n,{root:c}=i;if((t==="#"||t==="#/")&&o===c.baseId)return d();let u=Sq.resolveRef.call(l,c,o,t);if(u===void 0)throw new jhe.default(n.opts.uriResolver,o,t);if(u instanceof Sq.SchemaEnv)return m(u);return p(u);function d(){if(i===c)return mE(r,a,i,i.$async);let f=e.scopeValue("root",{ref:c});return mE(r,(0,Ln._)`${f}.validate`,c,c.$async)}function m(f){let h=bq(r,f);mE(r,h,f,f.$async)}function p(f){let h=e.scopeValue("schema",s.code.source===!0?{ref:f,code:(0,Ln.stringify)(f)}:{ref:f}),g=e.name("valid"),y=r.subschema({schema:f,dataTypes:[],schemaPath:Ln.nil,topSchemaRef:h,errSchemaPath:t},g);r.mergeEvaluated(y),r.ok(g)}}};function bq(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ln._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Vl.getValidate=bq;function mE(r,e,t,n){let{gen:o,it:i}=r,{allErrors:a,schemaEnv:s,opts:l}=i,c=l.passContext?Ed.default.this:Ln.nil;n?u():d();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Ln._)`await ${(0,yq.callValidateCode)(r,e,c)}`),p(e),a||o.assign(f,!0)},h=>{o.if((0,Ln._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),m(h),a||o.assign(f,!1)}),r.ok(f)}function d(){r.result((0,yq.callValidateCode)(r,e,c),()=>p(e),()=>m(e))}function m(f){let h=(0,Ln._)`${f}.errors`;o.assign(Ed.default.vErrors,(0,Ln._)`${Ed.default.vErrors} === null ? ${h} : ${Ed.default.vErrors}.concat(${h})`),o.assign(Ed.default.errors,(0,Ln._)`${Ed.default.vErrors}.length`)}function p(f){var h;if(!i.opts.unevaluated)return;let g=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=dE.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,Ln._)`${f}.evaluated.props`);i.props=dE.mergeEvaluated.props(o,y,i.props,Ln.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=dE.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,Ln._)`${f}.evaluated.items`);i.items=dE.mergeEvaluated.items(o,y,i.items,Ln.Name)}}}Vl.callRef=mE;Vl.default=Ghe});var Tq=Q(Xx=>{"use strict";Object.defineProperty(Xx,"__esModule",{value:!0});var Whe=gq(),Vhe=Eq(),qhe=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Whe.default,Vhe.default];Xx.default=qhe});var vq=Q(Jx=>{"use strict";Object.defineProperty(Jx,"__esModule",{value:!0});var pE=Be(),bs=pE.operators,fE={maximum:{okStr:"<=",ok:bs.LTE,fail:bs.GT},minimum:{okStr:">=",ok:bs.GTE,fail:bs.LT},exclusiveMaximum:{okStr:"<",ok:bs.LT,fail:bs.GTE},exclusiveMinimum:{okStr:">",ok:bs.GT,fail:bs.LTE}},Khe={message:({keyword:r,schemaCode:e})=>(0,pE.str)`must be ${fE[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,pE._)`{comparison: ${fE[r].okStr}, limit: ${e}}`},Yhe={keyword:Object.keys(fE),type:"number",schemaType:"number",$data:!0,error:Khe,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,pE._)`${t} ${fE[e].fail} ${n} || isNaN(${t})`)}};Jx.default=Yhe});var Aq=Q(Zx=>{"use strict";Object.defineProperty(Zx,"__esModule",{value:!0});var If=Be(),Xhe={message:({schemaCode:r})=>(0,If.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,If._)`{multipleOf: ${r}}`},Jhe={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Xhe,code(r){let{gen:e,data:t,schemaCode:n,it:o}=r,i=o.opts.multipleOfPrecision,a=e.let("res"),s=i?(0,If._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${i}`:(0,If._)`${a} !== parseInt(${a})`;r.fail$data((0,If._)`(${n} === 0 || (${a} = ${t}/${n}, ${s}))`)}};Zx.default=Jhe});var Cq=Q(Qx=>{"use strict";Object.defineProperty(Qx,"__esModule",{value:!0});function wq(r){let e=r.length,t=0,n=0,o;for(;n<e;)t++,o=r.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=r.charCodeAt(n),(o&64512)===56320&&n++);return t}Qx.default=wq;wq.code='require("ajv/dist/runtime/ucs2length").default'});var Rq=Q(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var ql=Be(),Zhe=lt(),Qhe=Cq(),ege={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,ql.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,ql._)`{limit: ${r}}`},tge={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ege,code(r){let{keyword:e,data:t,schemaCode:n,it:o}=r,i=e==="maxLength"?ql.operators.GT:ql.operators.LT,a=o.opts.unicode===!1?(0,ql._)`${t}.length`:(0,ql._)`${(0,Zhe.useFunc)(r.gen,Qhe.default)}(${t})`;r.fail$data((0,ql._)`${a} ${i} ${n}`)}};e_.default=tge});var xq=Q(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var rge=xo(),nge=lt(),Td=Be(),oge={message:({schemaCode:r})=>(0,Td.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Td._)`{pattern: ${r}}`},ige={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:oge,code(r){let{gen:e,data:t,$data:n,schema:o,schemaCode:i,it:a}=r,s=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=a.opts.code,c=l.code==="new RegExp"?(0,Td._)`new RegExp`:(0,nge.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Td._)`${c}(${i}, ${s}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Td._)`!${u}`)}else{let l=(0,rge.usePattern)(r,o);r.fail$data((0,Td._)`!${l}.test(${t})`)}}};t_.default=ige});var _q=Q(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var Of=Be(),age={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,Of.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,Of._)`{limit: ${r}}`},sge={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:age,code(r){let{keyword:e,data:t,schemaCode:n}=r,o=e==="maxProperties"?Of.operators.GT:Of.operators.LT;r.fail$data((0,Of._)`Object.keys(${t}).length ${o} ${n}`)}};r_.default=sge});var Mq=Q(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Nf=xo(),Lf=Be(),lge=lt(),cge={message:({params:{missingProperty:r}})=>(0,Lf.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Lf._)`{missingProperty: ${r}}`},uge={keyword:"required",type:"object",schemaType:"array",$data:!0,error:cge,code(r){let{gen:e,schema:t,schemaCode:n,data:o,$data:i,it:a}=r,{opts:s}=a;if(!i&&t.length===0)return;let l=t.length>=s.loopRequired;if(a.allErrors?c():u(),s.strictRequired){let p=r.parentSchema.properties,{definedProperties:f}=r.it;for(let h of t)if(p?.[h]===void 0&&!f.has(h)){let g=a.schemaEnv.baseId+a.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,lge.checkStrictMode)(a,y,a.opts.strictRequired)}}function c(){if(l||i)r.block$data(Lf.nil,d);else for(let p of t)(0,Nf.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(l||i){let f=e.let("valid",!0);r.block$data(f,()=>m(p,f)),r.ok(f)}else e.if((0,Nf.checkMissingProp)(r,t,p)),(0,Nf.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,Nf.noPropertyInData)(e,o,p,s.ownProperties),()=>r.error())})}function m(p,f){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,Nf.propertyInData)(e,o,p,s.ownProperties)),e.if((0,Lf.not)(f),()=>{r.error(),e.break()})},Lf.nil)}}};n_.default=uge});var Pq=Q(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var Df=Be(),dge={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,Df.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,Df._)`{limit: ${r}}`},mge={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:dge,code(r){let{keyword:e,data:t,schemaCode:n}=r,o=e==="maxItems"?Df.operators.GT:Df.operators.LT;r.fail$data((0,Df._)`${t}.length ${o} ${n}`)}};o_.default=mge});var hE=Q(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var Iq=Px();Iq.code='require("ajv/dist/runtime/equal").default';i_.default=Iq});var Oq=Q(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var a_=Tf(),Br=Be(),pge=lt(),fge=hE(),hge={message:({params:{i:r,j:e}})=>(0,Br.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Br._)`{i: ${r}, j: ${e}}`},gge={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hge,code(r){let{gen:e,data:t,$data:n,schema:o,parentSchema:i,schemaCode:a,it:s}=r;if(!n&&!o)return;let l=e.let("valid"),c=i.items?(0,a_.getSchemaTypes)(i.items):[];r.block$data(l,u,(0,Br._)`${a} === false`),r.ok(l);function u(){let f=e.let("i",(0,Br._)`${t}.length`),h=e.let("j");r.setParams({i:f,j:h}),e.assign(l,!0),e.if((0,Br._)`${f} > 1`,()=>(d()?m:p)(f,h))}function d(){return c.length>0&&!c.some(f=>f==="object"||f==="array")}function m(f,h){let g=e.name("item"),y=(0,a_.checkDataTypes)(c,g,s.opts.strictNumbers,a_.DataType.Wrong),b=e.const("indices",(0,Br._)`{}`);e.for((0,Br._)`;${f}--;`,()=>{e.let(g,(0,Br._)`${t}[${f}]`),e.if(y,(0,Br._)`continue`),c.length>1&&e.if((0,Br._)`typeof ${g} == "string"`,(0,Br._)`${g} += "_"`),e.if((0,Br._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(h,(0,Br._)`${b}[${g}]`),r.error(),e.assign(l,!1).break()}).code((0,Br._)`${b}[${g}] = ${f}`)})}function p(f,h){let g=(0,pge.useFunc)(e,fge.default),y=e.name("outer");e.label(y).for((0,Br._)`;${f}--;`,()=>e.for((0,Br._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Br._)`${g}(${t}[${f}], ${t}[${h}])`,()=>{r.error(),e.assign(l,!1).break(y)})))}}};s_.default=gge});var Nq=Q(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var l_=Be(),yge=lt(),Sge=hE(),bge={message:"must be equal to constant",params:({schemaCode:r})=>(0,l_._)`{allowedValue: ${r}}`},Ege={keyword:"const",$data:!0,error:bge,code(r){let{gen:e,data:t,$data:n,schemaCode:o,schema:i}=r;n||i&&typeof i=="object"?r.fail$data((0,l_._)`!${(0,yge.useFunc)(e,Sge.default)}(${t}, ${o})`):r.fail((0,l_._)`${i} !== ${t}`)}};c_.default=Ege});var Lq=Q(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});var kf=Be(),Tge=lt(),vge=hE(),Age={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,kf._)`{allowedValues: ${r}}`},wge={keyword:"enum",schemaType:"array",$data:!0,error:Age,code(r){let{gen:e,data:t,$data:n,schema:o,schemaCode:i,it:a}=r;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let s=o.length>=a.opts.loopEnum,l,c=()=>l??(l=(0,Tge.useFunc)(e,vge.default)),u;if(s||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,kf.or)(...o.map((f,h)=>m(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,kf._)`${c()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function m(p,f){let h=o[f];return typeof h=="object"&&h!==null?(0,kf._)`${c()}(${t}, ${p}[${f}])`:(0,kf._)`${t} === ${h}`}}};u_.default=wge});var Dq=Q(d_=>{"use strict";Object.defineProperty(d_,"__esModule",{value:!0});var Cge=vq(),Rge=Aq(),xge=Rq(),_ge=xq(),Mge=_q(),Pge=Mq(),Ige=Pq(),Oge=Oq(),Nge=Nq(),Lge=Lq(),Dge=[Cge.default,Rge.default,xge.default,_ge.default,Mge.default,Pge.default,Ige.default,Oge.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Nge.default,Lge.default];d_.default=Dge});var p_=Q(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});Ff.validateAdditionalItems=void 0;var Kl=Be(),m_=lt(),kge={message:({params:{len:r}})=>(0,Kl.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Kl._)`{limit: ${r}}`},Fge={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:kge,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,m_.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}kq(r,n)}};function kq(r,e){let{gen:t,schema:n,data:o,keyword:i,it:a}=r;a.items=!0;let s=t.const("len",(0,Kl._)`${o}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Kl._)`${s} <= ${e.length}`);else if(typeof n=="object"&&!(0,m_.alwaysValidSchema)(a,n)){let c=t.var("valid",(0,Kl._)`${s} <= ${e.length}`);t.if((0,Kl.not)(c),()=>l(c)),r.ok(c)}function l(c){t.forRange("i",e.length,s,u=>{r.subschema({keyword:i,dataProp:u,dataPropType:m_.Type.Num},c),a.allErrors||t.if((0,Kl.not)(c),()=>t.break())})}}Ff.validateAdditionalItems=kq;Ff.default=Fge});var f_=Q(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});Uf.validateTuple=void 0;var Fq=Be(),gE=lt(),Uge=xo(),Bge={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Uq(r,"additionalItems",e);t.items=!0,!(0,gE.alwaysValidSchema)(t,e)&&r.ok((0,Uge.validateArray)(r))}};function Uq(r,e,t=r.schema){let{gen:n,parentSchema:o,data:i,keyword:a,it:s}=r;u(o),s.opts.unevaluated&&t.length&&s.items!==!0&&(s.items=gE.mergeEvaluated.items(n,t.length,s.items));let l=n.name("valid"),c=n.const("len",(0,Fq._)`${i}.length`);t.forEach((d,m)=>{(0,gE.alwaysValidSchema)(s,d)||(n.if((0,Fq._)`${c} > ${m}`,()=>r.subschema({keyword:a,schemaProp:m,dataProp:m},l)),r.ok(l))});function u(d){let{opts:m,errSchemaPath:p}=s,f=t.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!h){let g=`"${a}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,gE.checkStrictMode)(s,g,m.strictTuples)}}}Uf.validateTuple=Uq;Uf.default=Bge});var Bq=Q(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var zge=f_(),$ge={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,zge.validateTuple)(r,"items")};h_.default=$ge});var $q=Q(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});var zq=Be(),Hge=lt(),jge=xo(),Gge=p_(),Wge={message:({params:{len:r}})=>(0,zq.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,zq._)`{limit: ${r}}`},Vge={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Wge,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:o}=t;n.items=!0,!(0,Hge.alwaysValidSchema)(n,e)&&(o?(0,Gge.validateAdditionalItems)(r,o):r.ok((0,jge.validateArray)(r)))}};g_.default=Vge});var Hq=Q(y_=>{"use strict";Object.defineProperty(y_,"__esModule",{value:!0});var Mo=Be(),yE=lt(),qge={message:({params:{min:r,max:e}})=>e===void 0?(0,Mo.str)`must contain at least ${r} valid item(s)`:(0,Mo.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Mo._)`{minContains: ${r}}`:(0,Mo._)`{minContains: ${r}, maxContains: ${e}}`},Kge={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:qge,code(r){let{gen:e,schema:t,parentSchema:n,data:o,it:i}=r,a,s,{minContains:l,maxContains:c}=n;i.opts.next?(a=l===void 0?1:l,s=c):a=1;let u=e.const("len",(0,Mo._)`${o}.length`);if(r.setParams({min:a,max:s}),s===void 0&&a===0){(0,yE.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&a>s){(0,yE.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,yE.alwaysValidSchema)(i,t)){let h=(0,Mo._)`${u} >= ${a}`;s!==void 0&&(h=(0,Mo._)`${h} && ${u} <= ${s}`),r.pass(h);return}i.items=!0;let d=e.name("valid");s===void 0&&a===1?p(d,()=>e.if(d,()=>e.break())):a===0?(e.let(d,!0),s!==void 0&&e.if((0,Mo._)`${o}.length > 0`,m)):(e.let(d,!1),m()),r.result(d,()=>r.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);p(h,()=>e.if(h,()=>f(g)))}function p(h,g){e.forRange("i",0,u,y=>{r.subschema({keyword:"contains",dataProp:y,dataPropType:yE.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,Mo._)`${h}++`),s===void 0?e.if((0,Mo._)`${h} >= ${a}`,()=>e.assign(d,!0).break()):(e.if((0,Mo._)`${h} > ${s}`,()=>e.assign(d,!1).break()),a===1?e.assign(d,!0):e.if((0,Mo._)`${h} >= ${a}`,()=>e.assign(d,!0)))}}};y_.default=Kge});var Wq=Q(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.validateSchemaDeps=Ni.validatePropertyDeps=Ni.error=void 0;var S_=Be(),Yge=lt(),Bf=xo();Ni.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,S_.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,S_._)`{property: ${r},
8
+ || ${a} === "boolean" || ${o} === null`).assign(s,(0,De._)`[${o}]`)}}}function Ppe({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,De._)`${e} !== undefined`,()=>r.assign((0,De._)`${e}[${t}]`,n))}function wx(r,e,t,n=hd.Correct){let o=n===hd.Correct?De.operators.EQ:De.operators.NEQ,i;switch(r){case"null":return(0,De._)`${e} ${o} null`;case"array":i=(0,De._)`Array.isArray(${e})`;break;case"object":i=(0,De._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=a((0,De._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=a();break;default:return(0,De._)`typeof ${e} ${o} ${r}`}return n===hd.Correct?i:(0,De.not)(i);function a(s=De.nil){return(0,De.and)((0,De._)`typeof ${e} == "number"`,s,t?(0,De._)`isFinite(${e})`:De.nil)}}en.checkDataType=wx;function Cx(r,e,t,n){if(r.length===1)return wx(r[0],e,t,n);let o,i=(0,sV.toHash)(r);if(i.array&&i.object){let a=(0,De._)`typeof ${e} != "object"`;o=i.null?a:(0,De._)`!${e} || ${a}`,delete i.null,delete i.array,delete i.object}else o=De.nil;i.number&&delete i.integer;for(let a in i)o=(0,De.and)(o,wx(a,e,t,n));return o}en.checkDataTypes=Cx;var Ipe={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,De._)`{type: ${r}}`:(0,De._)`{type: ${e}}`};function Rx(r){let e=Ope(r);(0,Cpe.reportError)(e,Ipe)}en.reportTypeError=Rx;function Ope(r){let{gen:e,data:t,schema:n}=r,o=(0,sV.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:r}}});var dV=Q(eE=>{"use strict";Object.defineProperty(eE,"__esModule",{value:!0});eE.assignDefaults=void 0;var gd=Be(),Npe=lt();function Lpe(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let o in t)uV(r,o,t[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,i)=>uV(r,i,o.default))}eE.assignDefaults=Lpe;function uV(r,e,t){let{gen:n,compositeRule:o,data:i,opts:a}=r;if(t===void 0)return;let s=(0,gd._)`${i}${(0,gd.getProperty)(e)}`;if(o){(0,Npe.checkStrictMode)(r,`default is ignored for: ${s}`);return}let l=(0,gd._)`${s} === undefined`;a.useDefaults==="empty"&&(l=(0,gd._)`${l} || ${s} === null || ${s} === ""`),n.if(l,(0,gd._)`${s} = ${(0,gd.stringify)(t)}`)}});var xo=Q(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.validateUnion=wt.validateArray=wt.usePattern=wt.callValidateCode=wt.schemaProperties=wt.allSchemaProperties=wt.noPropertyInData=wt.propertyInData=wt.isOwnProperty=wt.hasPropFunc=wt.reportMissingProp=wt.checkMissingProp=wt.checkReportMissingProp=void 0;var Ft=Be(),xx=lt(),hs=da(),Dpe=lt();function kpe(r,e){let{gen:t,data:n,it:o}=r;t.if(Mx(t,n,e,o.opts.ownProperties),()=>{r.setParams({missingProperty:(0,Ft._)`${e}`},!0),r.error()})}wt.checkReportMissingProp=kpe;function Fpe({gen:r,data:e,it:{opts:t}},n,o){return(0,Ft.or)(...n.map(i=>(0,Ft.and)(Mx(r,e,i,t.ownProperties),(0,Ft._)`${o} = ${i}`)))}wt.checkMissingProp=Fpe;function Upe(r,e){r.setParams({missingProperty:e},!0),r.error()}wt.reportMissingProp=Upe;function mV(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ft._)`Object.prototype.hasOwnProperty`})}wt.hasPropFunc=mV;function _x(r,e,t){return(0,Ft._)`${mV(r)}.call(${e}, ${t})`}wt.isOwnProperty=_x;function Bpe(r,e,t,n){let o=(0,Ft._)`${e}${(0,Ft.getProperty)(t)} !== undefined`;return n?(0,Ft._)`${o} && ${_x(r,e,t)}`:o}wt.propertyInData=Bpe;function Mx(r,e,t,n){let o=(0,Ft._)`${e}${(0,Ft.getProperty)(t)} === undefined`;return n?(0,Ft.or)(o,(0,Ft.not)(_x(r,e,t))):o}wt.noPropertyInData=Mx;function pV(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}wt.allSchemaProperties=pV;function zpe(r,e){return pV(e).filter(t=>!(0,xx.alwaysValidSchema)(r,e[t]))}wt.schemaProperties=zpe;function $pe({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:o,errorPath:i},it:a},s,l,c){let u=c?(0,Ft._)`${r}, ${e}, ${n}${o}`:e,d=[[hs.default.instancePath,(0,Ft.strConcat)(hs.default.instancePath,i)],[hs.default.parentData,a.parentData],[hs.default.parentDataProperty,a.parentDataProperty],[hs.default.rootData,hs.default.rootData]];a.opts.dynamicRef&&d.push([hs.default.dynamicAnchors,hs.default.dynamicAnchors]);let m=(0,Ft._)`${u}, ${t.object(...d)}`;return l!==Ft.nil?(0,Ft._)`${s}.call(${l}, ${m})`:(0,Ft._)`${s}(${m})`}wt.callValidateCode=$pe;var Hpe=(0,Ft._)`new RegExp`;function jpe({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(t,n);return r.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Ft._)`${o.code==="new RegExp"?Hpe:(0,Dpe.useFunc)(r,o)}(${t}, ${n})`})}wt.usePattern=jpe;function Gpe(r){let{gen:e,data:t,keyword:n,it:o}=r,i=e.name("valid");if(o.allErrors){let s=e.let("valid",!0);return a(()=>e.assign(s,!1)),s}return e.var(i,!0),a(()=>e.break()),i;function a(s){let l=e.const("len",(0,Ft._)`${t}.length`);e.forRange("i",0,l,c=>{r.subschema({keyword:n,dataProp:c,dataPropType:xx.Type.Num},i),e.if((0,Ft.not)(i),s)})}}wt.validateArray=Gpe;function Wpe(r){let{gen:e,schema:t,keyword:n,it:o}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(l=>(0,xx.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let a=e.let("valid",!1),s=e.name("_valid");e.block(()=>t.forEach((l,c)=>{let u=r.subschema({keyword:n,schemaProp:c,compositeRule:!0},s);e.assign(a,(0,Ft._)`${a} || ${s}`),r.mergeValidEvaluated(u,s)||e.if((0,Ft.not)(a))})),r.result(a,()=>r.reset(),()=>r.error(!0))}wt.validateUnion=Wpe});var gV=Q(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.validateKeywordUsage=Pi.validSchemaType=Pi.funcKeywordCode=Pi.macroKeywordCode=void 0;var En=Be(),Gl=da(),Vpe=xo(),qpe=Ef();function Kpe(r,e){let{gen:t,keyword:n,schema:o,parentSchema:i,it:a}=r,s=e.macro.call(a.self,o,i,a),l=hV(t,n,s);a.opts.validateSchema!==!1&&a.self.validateSchema(s,!0);let c=t.name("valid");r.subschema({schema:s,schemaPath:En.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),r.pass(c,()=>r.error(!0))}Pi.macroKeywordCode=Kpe;function Ype(r,e){var t;let{gen:n,keyword:o,schema:i,parentSchema:a,$data:s,it:l}=r;Jpe(l,e);let c=!s&&e.compile?e.compile.call(l.self,i,a,l):e.validate,u=hV(n,o,c),d=n.let("valid");r.block$data(d,m),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function m(){if(e.errors===!1)h(),e.modifying&&fV(r),g(()=>r.error());else{let y=e.async?p():f();e.modifying&&fV(r),g(()=>Xpe(r,y))}}function p(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,En._)`await `),b=>n.assign(d,!1).if((0,En._)`${b} instanceof ${l.ValidationError}`,()=>n.assign(y,(0,En._)`${b}.errors`),()=>n.throw(b))),y}function f(){let y=(0,En._)`${u}.errors`;return n.assign(y,null),h(En.nil),y}function h(y=e.async?(0,En._)`await `:En.nil){let b=l.opts.passContext?Gl.default.this:Gl.default.self,E=!("compile"in e&&!s||e.schema===!1);n.assign(d,(0,En._)`${y}${(0,Vpe.callValidateCode)(r,u,b,E)}`,e.modifying)}function g(y){var b;n.if((0,En.not)((b=e.valid)!==null&&b!==void 0?b:d),y)}}Pi.funcKeywordCode=Ype;function fV(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,En._)`${n.parentData}[${n.parentDataProperty}]`))}function Xpe(r,e){let{gen:t}=r;t.if((0,En._)`Array.isArray(${e})`,()=>{t.assign(Gl.default.vErrors,(0,En._)`${Gl.default.vErrors} === null ? ${e} : ${Gl.default.vErrors}.concat(${e})`).assign(Gl.default.errors,(0,En._)`${Gl.default.vErrors}.length`),(0,qpe.extendErrors)(r)},()=>r.error())}function Jpe({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function hV(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,En.stringify)(t)})}function Zpe(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}Pi.validSchemaType=Zpe;function Qpe({schema:r,opts:e,self:t,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let a=o.dependencies;if(a?.some(s=>!Object.prototype.hasOwnProperty.call(r,s)))throw new Error(`parent schema must have dependencies of ${i}: ${a.join(",")}`);if(o.validateSchema&&!o.validateSchema(r[i])){let l=`keyword "${i}" value is invalid at path "${n}": `+t.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(l);else throw new Error(l)}}Pi.validateKeywordUsage=Qpe});var SV=Q(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.extendSubschemaMode=gs.extendSubschemaData=gs.getSubschema=void 0;var Ii=Be(),yV=lt();function efe(r,{keyword:e,schemaProp:t,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:a}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let s=r.schema[e];return t===void 0?{schema:s,schemaPath:(0,Ii._)`${r.schemaPath}${(0,Ii.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:s[t],schemaPath:(0,Ii._)`${r.schemaPath}${(0,Ii.getProperty)(e)}${(0,Ii.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,yV.escapeFragment)(t)}`}}if(n!==void 0){if(o===void 0||i===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:a,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}gs.getSubschema=efe;function tfe(r,e,{dataProp:t,dataPropType:n,data:o,dataTypes:i,propertyName:a}){if(o!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=e;if(t!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=e,m=s.let("data",(0,Ii._)`${e.data}${(0,Ii.getProperty)(t)}`,!0);l(m),r.errorPath=(0,Ii.str)`${c}${(0,yV.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,Ii._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(o!==void 0){let c=o instanceof Ii.Name?o:s.let("data",o,!0);l(c),a!==void 0&&(r.propertyName=a)}i&&(r.dataTypes=i);function l(c){r.data=c,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,c]}}gs.extendSubschemaData=tfe;function rfe(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(r.compositeRule=n),o!==void 0&&(r.createErrors=o),i!==void 0&&(r.allErrors=i),r.jtdDiscriminator=e,r.jtdMetadata=t}gs.extendSubschemaMode=rfe});var Px=Q((_$t,bV)=>{"use strict";bV.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,o,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(o=n;o--!==0;)if(!r(e[o],t[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[o]))return!1;for(o=n;o--!==0;){var a=i[o];if(!r(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}});var TV=Q((M$t,EV)=>{"use strict";var ys=EV.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},o=t.post||function(){};tE(e,n,o,r,"",r)};ys.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ys.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ys.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ys.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function tE(r,e,t,n,o,i,a,s,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,i,a,s,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in ys.arrayKeywords)for(var m=0;m<d.length;m++)tE(r,e,t,d[m],o+"/"+u+"/"+m,i,o,u,n,m)}else if(u in ys.propsKeywords){if(d&&typeof d=="object")for(var p in d)tE(r,e,t,d[p],o+"/"+u+"/"+nfe(p),i,o,u,n,p)}else(u in ys.keywords||r.allKeys&&!(u in ys.skipKeywords))&&tE(r,e,t,d,o+"/"+u,i,o,u,n)}t(n,o,i,a,s,l,c)}}function nfe(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}});var vf=Q(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.getSchemaRefs=Nn.resolveUrl=Nn.normalizeId=Nn._getFullPath=Nn.getFullPath=Nn.inlineRef=void 0;var ofe=lt(),ife=Px(),afe=TV(),sfe=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function lfe(r,e=!0){return typeof r=="boolean"?!0:e===!0?!Ix(r):e?vV(r)<=e:!1}Nn.inlineRef=lfe;var cfe=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ix(r){for(let e in r){if(cfe.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(Ix)||typeof t=="object"&&Ix(t))return!0}return!1}function vV(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!sfe.has(t)&&(typeof r[t]=="object"&&(0,ofe.eachItem)(r[t],n=>e+=vV(n)),e===1/0))return 1/0}return e}function AV(r,e="",t){t!==!1&&(e=yd(e));let n=r.parse(e);return wV(r,n)}Nn.getFullPath=AV;function wV(r,e){return r.serialize(e).split("#")[0]+"#"}Nn._getFullPath=wV;var ufe=/#\/?$/;function yd(r){return r?r.replace(ufe,""):""}Nn.normalizeId=yd;function dfe(r,e,t){return t=yd(t),r.resolve(e,t)}Nn.resolveUrl=dfe;var mfe=/^[a-z_][-a-z0-9._]*$/i;function pfe(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,o=yd(r[t]||e),i={"":o},a=AV(n,o,!1),s={},l=new Set;return afe(r,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let h=a+m,g=i[f];typeof d[t]=="string"&&(g=y.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[m]=g;function y(E){let v=this.opts.uriResolver.resolve;if(E=yd(g?v(g,E):E),l.has(E))throw u(E);l.add(E);let w=this.refs[E];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?c(d,w.schema,E):E!==yd(h)&&(E[0]==="#"?(c(d,s[E],E),s[E]=d):this.refs[E]=h),E}function b(E){if(typeof E=="string"){if(!mfe.test(E))throw new Error(`invalid anchor "${E}"`);y.call(this,`#${E}`)}}}),s;function c(d,m,p){if(m!==void 0&&!ife(d,m))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Nn.getSchemaRefs=pfe});var Cf=Q(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.getData=Ss.KeywordCxt=Ss.validateFunctionCode=void 0;var MV=oV(),CV=Tf(),Nx=Ax(),rE=Tf(),ffe=dV(),wf=gV(),Ox=SV(),ue=Be(),Re=da(),hfe=vf(),ma=lt(),Af=Ef();function gfe(r){if(OV(r)&&(NV(r),IV(r))){bfe(r);return}PV(r,()=>(0,MV.topBoolOrEmptySchema)(r))}Ss.validateFunctionCode=gfe;function PV({gen:r,validateName:e,schema:t,schemaEnv:n,opts:o},i){o.code.es5?r.func(e,(0,ue._)`${Re.default.data}, ${Re.default.valCxt}`,n.$async,()=>{r.code((0,ue._)`"use strict"; ${RV(t,o)}`),Sfe(r,o),r.code(i)}):r.func(e,(0,ue._)`${Re.default.data}, ${yfe(o)}`,n.$async,()=>r.code(RV(t,o)).code(i))}function yfe(r){return(0,ue._)`{${Re.default.instancePath}="", ${Re.default.parentData}, ${Re.default.parentDataProperty}, ${Re.default.rootData}=${Re.default.data}${r.dynamicRef?(0,ue._)`, ${Re.default.dynamicAnchors}={}`:ue.nil}}={}`}function Sfe(r,e){r.if(Re.default.valCxt,()=>{r.var(Re.default.instancePath,(0,ue._)`${Re.default.valCxt}.${Re.default.instancePath}`),r.var(Re.default.parentData,(0,ue._)`${Re.default.valCxt}.${Re.default.parentData}`),r.var(Re.default.parentDataProperty,(0,ue._)`${Re.default.valCxt}.${Re.default.parentDataProperty}`),r.var(Re.default.rootData,(0,ue._)`${Re.default.valCxt}.${Re.default.rootData}`),e.dynamicRef&&r.var(Re.default.dynamicAnchors,(0,ue._)`${Re.default.valCxt}.${Re.default.dynamicAnchors}`)},()=>{r.var(Re.default.instancePath,(0,ue._)`""`),r.var(Re.default.parentData,(0,ue._)`undefined`),r.var(Re.default.parentDataProperty,(0,ue._)`undefined`),r.var(Re.default.rootData,Re.default.data),e.dynamicRef&&r.var(Re.default.dynamicAnchors,(0,ue._)`{}`)})}function bfe(r){let{schema:e,opts:t,gen:n}=r;PV(r,()=>{t.$comment&&e.$comment&&DV(r),wfe(r),n.let(Re.default.vErrors,null),n.let(Re.default.errors,0),t.unevaluated&&Efe(r),LV(r),xfe(r)})}function Efe(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,ue._)`${t}.evaluated`),e.if((0,ue._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,ue._)`${r.evaluated}.props`,(0,ue._)`undefined`)),e.if((0,ue._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,ue._)`${r.evaluated}.items`,(0,ue._)`undefined`))}function RV(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,ue._)`/*# sourceURL=${t} */`:ue.nil}function Tfe(r,e){if(OV(r)&&(NV(r),IV(r))){vfe(r,e);return}(0,MV.boolOrEmptySchema)(r,e)}function IV({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function OV(r){return typeof r.schema!="boolean"}function vfe(r,e){let{schema:t,gen:n,opts:o}=r;o.$comment&&t.$comment&&DV(r),Cfe(r),Rfe(r);let i=n.const("_errs",Re.default.errors);LV(r,i),n.var(e,(0,ue._)`${i} === ${Re.default.errors}`)}function NV(r){(0,ma.checkUnknownRules)(r),Afe(r)}function LV(r,e){if(r.opts.jtd)return xV(r,[],!1,e);let t=(0,CV.getSchemaTypes)(r.schema),n=(0,CV.coerceAndCheckDataType)(r,t);xV(r,t,!n,e)}function Afe(r){let{schema:e,errSchemaPath:t,opts:n,self:o}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,ma.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function wfe(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,ma.checkStrictMode)(r,"default is ignored in the schema root")}function Cfe(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,hfe.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function Rfe(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function DV({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:o}){let i=t.$comment;if(o.$comment===!0)r.code((0,ue._)`${Re.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let a=(0,ue.str)`${n}/$comment`,s=r.scopeValue("root",{ref:e.root});r.code((0,ue._)`${Re.default.self}.opts.$comment(${i}, ${a}, ${s}.schema)`)}}function xfe(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:o,opts:i}=r;t.$async?e.if((0,ue._)`${Re.default.errors} === 0`,()=>e.return(Re.default.data),()=>e.throw((0,ue._)`new ${o}(${Re.default.vErrors})`)):(e.assign((0,ue._)`${n}.errors`,Re.default.vErrors),i.unevaluated&&_fe(r),e.return((0,ue._)`${Re.default.errors} === 0`))}function _fe({gen:r,evaluated:e,props:t,items:n}){t instanceof ue.Name&&r.assign((0,ue._)`${e}.props`,t),n instanceof ue.Name&&r.assign((0,ue._)`${e}.items`,n)}function xV(r,e,t,n){let{gen:o,schema:i,data:a,allErrors:s,opts:l,self:c}=r,{RULES:u}=c;if(i.$ref&&(l.ignoreKeywordsWithRef||!(0,ma.schemaHasRulesButRef)(i,u))){o.block(()=>FV(r,"$ref",u.all.$ref.definition));return}l.jtd||Mfe(r,e),o.block(()=>{for(let m of u.rules)d(m);d(u.post)});function d(m){(0,Nx.shouldUseGroup)(i,m)&&(m.type?(o.if((0,rE.checkDataType)(m.type,a,l.strictNumbers)),_V(r,m),e.length===1&&e[0]===m.type&&t&&(o.else(),(0,rE.reportTypeError)(r)),o.endIf()):_V(r,m),s||o.if((0,ue._)`${Re.default.errors} === ${n||0}`))}}function _V(r,e){let{gen:t,schema:n,opts:{useDefaults:o}}=r;o&&(0,ffe.assignDefaults)(r,e.type),t.block(()=>{for(let i of e.rules)(0,Nx.shouldUseRule)(n,i)&&FV(r,i.keyword,i.definition,e.type)})}function Mfe(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(Pfe(r,e),r.opts.allowUnionTypes||Ife(r,e),Ofe(r,r.dataTypes))}function Pfe(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{kV(r.dataTypes,t)||Lx(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),Lfe(r,e)}}function Ife(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Lx(r,"use allowUnionTypes to allow union type keyword")}function Ofe(r,e){let t=r.self.RULES.all;for(let n in t){let o=t[n];if(typeof o=="object"&&(0,Nx.shouldUseRule)(r.schema,o)){let{type:i}=o.definition;i.length&&!i.some(a=>Nfe(e,a))&&Lx(r,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Nfe(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function kV(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function Lfe(r,e){let t=[];for(let n of r.dataTypes)kV(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function Lx(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,ma.checkStrictMode)(r,e,r.opts.strictTypes)}var nE=class{constructor(e,t,n){if((0,wf.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ma.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",UV(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,wf.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Re.default.errors))}result(e,t,n){this.failResult((0,ue.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,ue.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,ue._)`${t} !== undefined && (${(0,ue.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Af.reportExtraError:Af.reportError)(this,this.def.error,t)}$dataError(){(0,Af.reportError)(this,this.def.$dataError||Af.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Af.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=ue.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=ue.nil,t=ue.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:a}=this;n.if((0,ue.or)((0,ue._)`${o} === undefined`,t)),e!==ue.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==ue.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:o,it:i}=this;return(0,ue.or)(a(),s());function a(){if(n.length){if(!(t instanceof ue.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,ue._)`${(0,rE.checkDataTypes)(l,t,i.opts.strictNumbers,rE.DataType.Wrong)}`}return ue.nil}function s(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,ue._)`!${l}(${t})`}return ue.nil}}subschema(e,t){let n=(0,Ox.getSubschema)(this.it,e);(0,Ox.extendSubschemaData)(n,this.it,e),(0,Ox.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Tfe(o,t),o}mergeEvaluated(e,t){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ma.mergeEvaluated.props(o,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=ma.mergeEvaluated.items(o,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(t,()=>this.mergeEvaluated(e,ue.Name)),!0}};Ss.KeywordCxt=nE;function FV(r,e,t,n){let o=new nE(r,t,e);"code"in t?t.code(o,n):o.$data&&t.validate?(0,wf.funcKeywordCode)(o,t):"macro"in t?(0,wf.macroKeywordCode)(o,t):(t.compile||t.validate)&&(0,wf.funcKeywordCode)(o,t)}var Dfe=/^\/(?:[^~]|~0|~1)*$/,kfe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function UV(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let o,i;if(r==="")return Re.default.rootData;if(r[0]==="/"){if(!Dfe.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);o=r,i=Re.default.rootData}else{let c=kfe.exec(r);if(!c)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+c[1];if(o=c[2],o==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(i=t[e-u],!o)return i}let a=i,s=o.split("/");for(let c of s)c&&(i=(0,ue._)`${i}${(0,ue.getProperty)((0,ma.unescapeJsonPointer)(c))}`,a=(0,ue._)`${a} && ${i}`);return a;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}Ss.getData=UV});var oE=Q(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});var Dx=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kx.default=Dx});var Rf=Q(Bx=>{"use strict";Object.defineProperty(Bx,"__esModule",{value:!0});var Fx=vf(),Ux=class extends Error{constructor(e,t,n,o){super(o||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Fx.resolveUrl)(e,t,n),this.missingSchema=(0,Fx.normalizeId)((0,Fx.getFullPath)(e,this.missingRef))}};Bx.default=Ux});var aE=Q(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.resolveSchema=_o.getCompilingSchema=_o.resolveRef=_o.compileSchema=_o.SchemaEnv=void 0;var Ko=Be(),Ffe=oE(),Wl=da(),Yo=vf(),BV=lt(),Ufe=Cf(),Sd=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Yo.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};_o.SchemaEnv=Sd;function $x(r){let e=zV.call(this,r);if(e)return e;let t=(0,Yo.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,a=new Ko.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),s;r.$async&&(s=a.scopeValue("Error",{ref:Ffe.default,code:(0,Ko._)`require("ajv/dist/runtime/validation_error").default`}));let l=a.scopeName("validate");r.validateName=l;let c={gen:a,allErrors:this.opts.allErrors,data:Wl.default.data,parentData:Wl.default.parentData,parentDataProperty:Wl.default.parentDataProperty,dataNames:[Wl.default.data],dataPathArr:[Ko.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Ko.stringify)(r.schema)}:{ref:r.schema}),validateName:l,ValidationError:s,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Ko.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ko._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,Ufe.validateFunctionCode)(c),a.optimize(this.opts.code.optimize);let d=a.toString();u=`${a.scopeRefs(Wl.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${Wl.default.self}`,`${Wl.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:d,scopeValues:a._values}),this.opts.unevaluated){let{props:f,items:h}=c;p.evaluated={props:f instanceof Ko.Name?void 0:f,items:h instanceof Ko.Name?void 0:h,dynamicProps:f instanceof Ko.Name,dynamicItems:h instanceof Ko.Name},p.source&&(p.source.evaluated=(0,Ko.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}_o.compileSchema=$x;function Bfe(r,e,t){var n;t=(0,Yo.resolveUrl)(this.opts.uriResolver,e,t);let o=r.refs[t];if(o)return o;let i=Hfe.call(this,r,t);if(i===void 0){let a=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:s}=this.opts;a&&(i=new Sd({schema:a,schemaId:s,root:r,baseId:e}))}if(i!==void 0)return r.refs[t]=zfe.call(this,i)}_o.resolveRef=Bfe;function zfe(r){return(0,Yo.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:$x.call(this,r)}function zV(r){for(let e of this._compilations)if($fe(e,r))return e}_o.getCompilingSchema=zV;function $fe(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function Hfe(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||iE.call(this,r,e)}function iE(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Yo._getFullPath)(this.opts.uriResolver,t),o=(0,Yo.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===o)return zx.call(this,t,r);let i=(0,Yo.normalizeId)(n),a=this.refs[i]||this.schemas[i];if(typeof a=="string"){let s=iE.call(this,r,a);return typeof s?.schema!="object"?void 0:zx.call(this,t,s)}if(typeof a?.schema=="object"){if(a.validate||$x.call(this,a),i===(0,Yo.normalizeId)(e)){let{schema:s}=a,{schemaId:l}=this.opts,c=s[l];return c&&(o=(0,Yo.resolveUrl)(this.opts.uriResolver,o,c)),new Sd({schema:s,schemaId:l,root:r,baseId:o})}return zx.call(this,t,a)}}_o.resolveSchema=iE;var jfe=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zx(r,{baseId:e,schema:t,root:n}){var o;if(((o=r.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let s of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let l=t[(0,BV.unescapeFragment)(s)];if(l===void 0)return;t=l;let c=typeof t=="object"&&t[this.opts.schemaId];!jfe.has(s)&&c&&(e=(0,Yo.resolveUrl)(this.opts.uriResolver,e,c))}let i;if(typeof t!="boolean"&&t.$ref&&!(0,BV.schemaHasRulesButRef)(t,this.RULES)){let s=(0,Yo.resolveUrl)(this.opts.uriResolver,e,t.$ref);i=iE.call(this,n,s)}let{schemaId:a}=this.opts;if(i=i||new Sd({schema:t,schemaId:a,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var $V=Q((D$t,Gfe)=>{Gfe.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var jV=Q((k$t,HV)=>{"use strict";var Wfe={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};HV.exports={HEX:Wfe}});var JV=Q((F$t,XV)=>{"use strict";var{HEX:Vfe}=jV(),qfe=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function qV(r){if(YV(r,".")<3)return{host:r,isIPV4:!1};let e=r.match(qfe)||[],[t]=e;return t?{host:Yfe(t,"."),isIPV4:!0}:{host:r,isIPV4:!1}}function Hx(r,e=!1){let t="",n=!0;for(let o of r){if(Vfe[o]===void 0)return;o!=="0"&&n===!0&&(n=!1),n||(t+=o)}return e&&t.length===0&&(t="0"),t}function Kfe(r){let e=0,t={error:!1,address:"",zone:""},n=[],o=[],i=!1,a=!1,s=!1;function l(){if(o.length){if(i===!1){let c=Hx(o);if(c!==void 0)n.push(c);else return t.error=!0,!1}o.length=0}return!0}for(let c=0;c<r.length;c++){let u=r[c];if(!(u==="["||u==="]"))if(u===":"){if(a===!0&&(s=!0),!l())break;if(e++,n.push(":"),e>7){t.error=!0;break}c-1>=0&&r[c-1]===":"&&(a=!0);continue}else if(u==="%"){if(!l())break;i=!0}else{o.push(u);continue}}return o.length&&(i?t.zone=o.join(""):s?n.push(o.join("")):n.push(Hx(o))),t.address=n.join(""),t}function KV(r){if(YV(r,":")<2)return{host:r,isIPV6:!1};let e=Kfe(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,escapedHost:n,isIPV6:!0}}}function Yfe(r,e){let t="",n=!0,o=r.length;for(let i=0;i<o;i++){let a=r[i];a==="0"&&n?(i+1<=o&&r[i+1]===e||i+1===o)&&(t+=a,n=!1):(a===e?n=!0:n=!1,t+=a)}return t}function YV(r,e){let t=0;for(let n=0;n<r.length;n++)r[n]===e&&t++;return t}var GV=/^\.\.?\//u,WV=/^\/\.(?:\/|$)/u,VV=/^\/\.\.(?:\/|$)/u,Xfe=/^\/?(?:.|\n)*?(?=\/|$)/u;function Jfe(r){let e=[];for(;r.length;)if(r.match(GV))r=r.replace(GV,"");else if(r.match(WV))r=r.replace(WV,"/");else if(r.match(VV))r=r.replace(VV,"/"),e.pop();else if(r==="."||r==="..")r="";else{let t=r.match(Xfe);if(t){let n=t[0];r=r.slice(n.length),e.push(n)}else throw new Error("Unexpected dot segment condition")}return e.join("")}function Zfe(r,e){let t=e!==!0?escape:unescape;return r.scheme!==void 0&&(r.scheme=t(r.scheme)),r.userinfo!==void 0&&(r.userinfo=t(r.userinfo)),r.host!==void 0&&(r.host=t(r.host)),r.path!==void 0&&(r.path=t(r.path)),r.query!==void 0&&(r.query=t(r.query)),r.fragment!==void 0&&(r.fragment=t(r.fragment)),r}function Qfe(r){let e=[];if(r.userinfo!==void 0&&(e.push(r.userinfo),e.push("@")),r.host!==void 0){let t=unescape(r.host),n=qV(t);if(n.isIPV4)t=n.host;else{let o=KV(n.host);o.isIPV6===!0?t=`[${o.escapedHost}]`:t=r.host}e.push(t)}return(typeof r.port=="number"||typeof r.port=="string")&&(e.push(":"),e.push(String(r.port))),e.length?e.join(""):void 0}XV.exports={recomposeAuthority:Qfe,normalizeComponentEncoding:Zfe,removeDotSegments:Jfe,normalizeIPv4:qV,normalizeIPv6:KV,stringArrayToHexStripped:Hx}});var nq=Q((U$t,rq)=>{"use strict";var ehe=/^[\da-f]{8}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{12}$/iu,the=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function ZV(r){return typeof r.secure=="boolean"?r.secure:String(r.scheme).toLowerCase()==="wss"}function QV(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function eq(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function rhe(r){return r.secure=ZV(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function nhe(r){if((r.port===(ZV(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function ohe(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(the);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let o=`${n}:${e.nid||r.nid}`,i=jx[o];r.path=void 0,i&&(r=i.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ihe(r,e){let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),o=`${t}:${e.nid||n}`,i=jx[o];i&&(r=i.serialize(r,e));let a=r,s=r.nss;return a.path=`${n||e.nid}:${s}`,e.skipEscape=!0,a}function ahe(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!ehe.test(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function she(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var tq={scheme:"http",domainHost:!0,parse:QV,serialize:eq},lhe={scheme:"https",domainHost:tq.domainHost,parse:QV,serialize:eq},sE={scheme:"ws",domainHost:!0,parse:rhe,serialize:nhe},che={scheme:"wss",domainHost:sE.domainHost,parse:sE.parse,serialize:sE.serialize},uhe={scheme:"urn",parse:ohe,serialize:ihe,skipNormalize:!0},dhe={scheme:"urn:uuid",parse:ahe,serialize:she,skipNormalize:!0},jx={http:tq,https:lhe,ws:sE,wss:che,urn:uhe,"urn:uuid":dhe};rq.exports=jx});var iq=Q((B$t,cE)=>{"use strict";var{normalizeIPv6:mhe,normalizeIPv4:phe,removeDotSegments:xf,recomposeAuthority:fhe,normalizeComponentEncoding:lE}=JV(),Gx=nq();function hhe(r,e){return typeof r=="string"?r=Oi(pa(r,e),e):typeof r=="object"&&(r=pa(Oi(r,e),e)),r}function ghe(r,e,t){let n=Object.assign({scheme:"null"},t),o=oq(pa(r,n),pa(e,n),n,!0);return Oi(o,{...n,skipEscape:!0})}function oq(r,e,t,n){let o={};return n||(r=pa(Oi(r,t),t),e=pa(Oi(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=xf(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=xf(e.path||""),o.query=e.query):(e.path?(e.path.charAt(0)==="/"?o.path=xf(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?o.path="/"+e.path:r.path?o.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=xf(o.path)),o.query=e.query):(o.path=r.path,e.query!==void 0?o.query=e.query:o.query=r.query),o.userinfo=r.userinfo,o.host=r.host,o.port=r.port),o.scheme=r.scheme),o.fragment=e.fragment,o}function yhe(r,e,t){return typeof r=="string"?(r=unescape(r),r=Oi(lE(pa(r,t),!0),{...t,skipEscape:!0})):typeof r=="object"&&(r=Oi(lE(r,!0),{...t,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Oi(lE(pa(e,t),!0),{...t,skipEscape:!0})):typeof e=="object"&&(e=Oi(lE(e,!0),{...t,skipEscape:!0})),r.toLowerCase()===e.toLowerCase()}function Oi(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),o=[],i=Gx[(n.scheme||t.scheme||"").toLowerCase()];i?.serialize&&i.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&o.push(t.scheme,":");let a=fhe(t);if(a!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(a),t.path&&t.path.charAt(0)!=="/"&&o.push("/")),t.path!==void 0){let s=t.path;!n.absolutePath&&(!i||!i.absolutePath)&&(s=xf(s)),a===void 0&&(s=s.replace(/^\/\//u,"/%2F")),o.push(s)}return t.query!==void 0&&o.push("?",t.query),t.fragment!==void 0&&o.push("#",t.fragment),o.join("")}var She=Array.from({length:127},(r,e)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(e)));function bhe(r){let e=0;for(let t=0,n=r.length;t<n;++t)if(e=r.charCodeAt(t),e>126||She[e])return!0;return!1}var Ehe=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function pa(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=r.indexOf("%")!==-1,i=!1;t.reference==="suffix"&&(r=(t.scheme?t.scheme+":":"")+"//"+r);let a=r.match(Ehe);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host){let l=phe(n.host);if(l.isIPV4===!1){let c=mhe(l.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else n.host=l.host,i=!0}n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&!n.path&&n.query===void 0?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let s=Gx[(t.scheme||n.scheme||"").toLowerCase()];if(!t.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(t.domainHost||s?.domainHost)&&i===!1&&bhe(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}(!s||s&&!s.skipNormalize)&&(o&&n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),o&&n.host!==void 0&&(n.host=unescape(n.host)),n.path?.length&&(n.path=escape(unescape(n.path))),n.fragment?.length&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s?.parse&&s.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var Wx={SCHEMES:Gx,normalize:hhe,resolve:ghe,resolveComponents:oq,equal:yhe,serialize:Oi,parse:pa};cE.exports=Wx;cE.exports.default=Wx;cE.exports.fastUri=Wx});var sq=Q(Vx=>{"use strict";Object.defineProperty(Vx,"__esModule",{value:!0});var aq=iq();aq.code='require("ajv/dist/runtime/uri").default';Vx.default=aq});var hq=Q(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.CodeGen=Ur.Name=Ur.nil=Ur.stringify=Ur.str=Ur._=Ur.KeywordCxt=void 0;var The=Cf();Object.defineProperty(Ur,"KeywordCxt",{enumerable:!0,get:function(){return The.KeywordCxt}});var bd=Be();Object.defineProperty(Ur,"_",{enumerable:!0,get:function(){return bd._}});Object.defineProperty(Ur,"str",{enumerable:!0,get:function(){return bd.str}});Object.defineProperty(Ur,"stringify",{enumerable:!0,get:function(){return bd.stringify}});Object.defineProperty(Ur,"nil",{enumerable:!0,get:function(){return bd.nil}});Object.defineProperty(Ur,"Name",{enumerable:!0,get:function(){return bd.Name}});Object.defineProperty(Ur,"CodeGen",{enumerable:!0,get:function(){return bd.CodeGen}});var vhe=oE(),mq=Rf(),Ahe=vx(),_f=aE(),whe=Be(),Mf=vf(),uE=Tf(),Kx=lt(),lq=$V(),Che=sq(),pq=(r,e)=>new RegExp(r,e);pq.code="new RegExp";var Rhe=["removeAdditional","useDefaults","coerceTypes"],xhe=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_he={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Mhe={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cq=200;function Phe(r){var e,t,n,o,i,a,s,l,c,u,d,m,p,f,h,g,y,b,E,v,w,L,I,A,_;let O=r.strict,k=(e=r.code)===null||e===void 0?void 0:e.optimize,D=k===!0||k===void 0?1:k||0,j=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:pq,$=(o=r.uriResolver)!==null&&o!==void 0?o:Che.default;return{strictSchema:(a=(i=r.strictSchema)!==null&&i!==void 0?i:O)!==null&&a!==void 0?a:!0,strictNumbers:(l=(s=r.strictNumbers)!==null&&s!==void 0?s:O)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=r.strictTypes)!==null&&c!==void 0?c:O)!==null&&u!==void 0?u:"log",strictTuples:(m=(d=r.strictTuples)!==null&&d!==void 0?d:O)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=r.strictRequired)!==null&&p!==void 0?p:O)!==null&&f!==void 0?f:!1,code:r.code?{...r.code,optimize:D,regExp:j}:{optimize:D,regExp:j},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:cq,loopEnum:(g=r.loopEnum)!==null&&g!==void 0?g:cq,meta:(y=r.meta)!==null&&y!==void 0?y:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(E=r.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(v=r.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(w=r.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(L=r.validateSchema)!==null&&L!==void 0?L:!0,validateFormats:(I=r.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(A=r.unicodeRegExp)!==null&&A!==void 0?A:!0,int32range:(_=r.int32range)!==null&&_!==void 0?_:!0,uriResolver:$}}var Pf=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Phe(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new whe.ValueScope({scope:{},prefixes:xhe,es5:t,lines:n}),this.logger=khe(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ahe.getRules)(),uq.call(this,_he,e,"NOT SUPPORTED"),uq.call(this,Mhe,e,"DEPRECATED","warn"),this._metaOpts=Lhe.call(this),e.formats&&Ohe.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Nhe.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ihe.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,o=lq;n==="id"&&(o={...lq},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(t);return"$async"in n||(this.errors=n.errors),o}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,t);async function o(u,d){await i.call(this,u.$schema);let m=this._addSchema(u,d);return m.validate||a.call(this,m)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function a(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof mq.default))throw d;return s.call(this,d),await l.call(this,d.missingSchema),a.call(this,u)}}function s({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let a of e)this.addSchema(a,void 0,n,o);return this}let i;if(typeof e=="object"){let{schemaId:a}=this.opts;if(i=e[a],i!==void 0&&typeof i!="string")throw new Error(`schema ${a} must be string`)}return t=(0,Mf.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,o,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&t){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let t;for(;typeof(t=dq.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,o=new _f.SchemaEnv({schema:{},schemaId:n});if(t=_f.resolveSchema.call(this,o,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=dq.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,Mf.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Uhe.call(this,n,t),!t)return(0,Kx.eachItem)(n,i=>qx.call(this,i)),this;zhe.call(this,t);let o={...t,type:(0,uE.getJSONTypes)(t.type),schemaType:(0,uE.getJSONTypes)(t.schemaType)};return(0,Kx.eachItem)(n,o.type.length===0?i=>qx.call(this,i,o):i=>o.type.forEach(a=>qx.call(this,i,o,a))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let o=n.rules.findIndex(i=>i.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+t+i)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of t){let i=o.split("/").slice(1),a=e;for(let s of i)a=a[s];for(let s in n){let l=n[s];if(typeof l!="object")continue;let{$data:c}=l.definition,u=a[s];c&&u&&(a[s]=fq(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let o=e[n];(!t||t.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,t,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e=="object")a=e[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,Mf.normalizeId)(a||n);let c=Mf.getSchemaRefs.call(this,e,n);return l=new _f.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:c}),this._cache.set(l.schema,l),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):_f.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{_f.compileSchema.call(this,e)}finally{this.opts=t}}};Pf.ValidationError=vhe.default;Pf.MissingRefError=mq.default;Ur.default=Pf;function uq(r,e,t,n="error"){for(let o in r){let i=o;i in e&&this.logger[n](`${t}: option ${o}. ${r[i]}`)}}function dq(r){return r=(0,Mf.normalizeId)(r),this.schemas[r]||this.refs[r]}function Ihe(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function Ohe(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function Nhe(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function Lhe(){let r={...this.opts};for(let e of Rhe)delete r[e];return r}var Dhe={log(){},warn(){},error(){}};function khe(r){if(r===!1)return Dhe;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var Fhe=/^[a-z_$][a-z0-9_$:-]*$/i;function Uhe(r,e){let{RULES:t}=this;if((0,Kx.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Fhe.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function qx(r,e,t){var n;let o=e?.post;if(t&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,a=o?i.post:i.rules.find(({type:l})=>l===t);if(a||(a={type:t,rules:[]},i.rules.push(a)),i.keywords[r]=!0,!e)return;let s={keyword:r,definition:{...e,type:(0,uE.getJSONTypes)(e.type),schemaType:(0,uE.getJSONTypes)(e.schemaType)}};e.before?Bhe.call(this,a,s,e.before):a.rules.push(s),i.all[r]=s,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function Bhe(r,e,t){let n=r.rules.findIndex(o=>o.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function zhe(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=fq(e)),r.validateSchema=this.compile(e,!0))}var $he={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fq(r){return{anyOf:[r,$he]}}});var gq=Q(Yx=>{"use strict";Object.defineProperty(Yx,"__esModule",{value:!0});var Hhe={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Yx.default=Hhe});var Eq=Q(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});Vl.callRef=Vl.getValidate=void 0;var jhe=Rf(),yq=xo(),Ln=Be(),Ed=da(),Sq=aE(),dE=lt(),Ghe={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:o,schemaEnv:i,validateName:a,opts:s,self:l}=n,{root:c}=i;if((t==="#"||t==="#/")&&o===c.baseId)return d();let u=Sq.resolveRef.call(l,c,o,t);if(u===void 0)throw new jhe.default(n.opts.uriResolver,o,t);if(u instanceof Sq.SchemaEnv)return m(u);return p(u);function d(){if(i===c)return mE(r,a,i,i.$async);let f=e.scopeValue("root",{ref:c});return mE(r,(0,Ln._)`${f}.validate`,c,c.$async)}function m(f){let h=bq(r,f);mE(r,h,f,f.$async)}function p(f){let h=e.scopeValue("schema",s.code.source===!0?{ref:f,code:(0,Ln.stringify)(f)}:{ref:f}),g=e.name("valid"),y=r.subschema({schema:f,dataTypes:[],schemaPath:Ln.nil,topSchemaRef:h,errSchemaPath:t},g);r.mergeEvaluated(y),r.ok(g)}}};function bq(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ln._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Vl.getValidate=bq;function mE(r,e,t,n){let{gen:o,it:i}=r,{allErrors:a,schemaEnv:s,opts:l}=i,c=l.passContext?Ed.default.this:Ln.nil;n?u():d();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Ln._)`await ${(0,yq.callValidateCode)(r,e,c)}`),p(e),a||o.assign(f,!0)},h=>{o.if((0,Ln._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),m(h),a||o.assign(f,!1)}),r.ok(f)}function d(){r.result((0,yq.callValidateCode)(r,e,c),()=>p(e),()=>m(e))}function m(f){let h=(0,Ln._)`${f}.errors`;o.assign(Ed.default.vErrors,(0,Ln._)`${Ed.default.vErrors} === null ? ${h} : ${Ed.default.vErrors}.concat(${h})`),o.assign(Ed.default.errors,(0,Ln._)`${Ed.default.vErrors}.length`)}function p(f){var h;if(!i.opts.unevaluated)return;let g=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=dE.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,Ln._)`${f}.evaluated.props`);i.props=dE.mergeEvaluated.props(o,y,i.props,Ln.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=dE.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,Ln._)`${f}.evaluated.items`);i.items=dE.mergeEvaluated.items(o,y,i.items,Ln.Name)}}}Vl.callRef=mE;Vl.default=Ghe});var Tq=Q(Xx=>{"use strict";Object.defineProperty(Xx,"__esModule",{value:!0});var Whe=gq(),Vhe=Eq(),qhe=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Whe.default,Vhe.default];Xx.default=qhe});var vq=Q(Jx=>{"use strict";Object.defineProperty(Jx,"__esModule",{value:!0});var pE=Be(),bs=pE.operators,fE={maximum:{okStr:"<=",ok:bs.LTE,fail:bs.GT},minimum:{okStr:">=",ok:bs.GTE,fail:bs.LT},exclusiveMaximum:{okStr:"<",ok:bs.LT,fail:bs.GTE},exclusiveMinimum:{okStr:">",ok:bs.GT,fail:bs.LTE}},Khe={message:({keyword:r,schemaCode:e})=>(0,pE.str)`must be ${fE[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,pE._)`{comparison: ${fE[r].okStr}, limit: ${e}}`},Yhe={keyword:Object.keys(fE),type:"number",schemaType:"number",$data:!0,error:Khe,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,pE._)`${t} ${fE[e].fail} ${n} || isNaN(${t})`)}};Jx.default=Yhe});var Aq=Q(Zx=>{"use strict";Object.defineProperty(Zx,"__esModule",{value:!0});var If=Be(),Xhe={message:({schemaCode:r})=>(0,If.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,If._)`{multipleOf: ${r}}`},Jhe={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Xhe,code(r){let{gen:e,data:t,schemaCode:n,it:o}=r,i=o.opts.multipleOfPrecision,a=e.let("res"),s=i?(0,If._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${i}`:(0,If._)`${a} !== parseInt(${a})`;r.fail$data((0,If._)`(${n} === 0 || (${a} = ${t}/${n}, ${s}))`)}};Zx.default=Jhe});var Cq=Q(Qx=>{"use strict";Object.defineProperty(Qx,"__esModule",{value:!0});function wq(r){let e=r.length,t=0,n=0,o;for(;n<e;)t++,o=r.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=r.charCodeAt(n),(o&64512)===56320&&n++);return t}Qx.default=wq;wq.code='require("ajv/dist/runtime/ucs2length").default'});var Rq=Q(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var ql=Be(),Zhe=lt(),Qhe=Cq(),ege={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,ql.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,ql._)`{limit: ${r}}`},tge={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ege,code(r){let{keyword:e,data:t,schemaCode:n,it:o}=r,i=e==="maxLength"?ql.operators.GT:ql.operators.LT,a=o.opts.unicode===!1?(0,ql._)`${t}.length`:(0,ql._)`${(0,Zhe.useFunc)(r.gen,Qhe.default)}(${t})`;r.fail$data((0,ql._)`${a} ${i} ${n}`)}};e_.default=tge});var xq=Q(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var rge=xo(),nge=lt(),Td=Be(),oge={message:({schemaCode:r})=>(0,Td.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Td._)`{pattern: ${r}}`},ige={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:oge,code(r){let{gen:e,data:t,$data:n,schema:o,schemaCode:i,it:a}=r,s=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=a.opts.code,c=l.code==="new RegExp"?(0,Td._)`new RegExp`:(0,nge.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Td._)`${c}(${i}, ${s}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Td._)`!${u}`)}else{let l=(0,rge.usePattern)(r,o);r.fail$data((0,Td._)`!${l}.test(${t})`)}}};t_.default=ige});var _q=Q(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var Of=Be(),age={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,Of.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,Of._)`{limit: ${r}}`},sge={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:age,code(r){let{keyword:e,data:t,schemaCode:n}=r,o=e==="maxProperties"?Of.operators.GT:Of.operators.LT;r.fail$data((0,Of._)`Object.keys(${t}).length ${o} ${n}`)}};r_.default=sge});var Mq=Q(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Nf=xo(),Lf=Be(),lge=lt(),cge={message:({params:{missingProperty:r}})=>(0,Lf.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Lf._)`{missingProperty: ${r}}`},uge={keyword:"required",type:"object",schemaType:"array",$data:!0,error:cge,code(r){let{gen:e,schema:t,schemaCode:n,data:o,$data:i,it:a}=r,{opts:s}=a;if(!i&&t.length===0)return;let l=t.length>=s.loopRequired;if(a.allErrors?c():u(),s.strictRequired){let p=r.parentSchema.properties,{definedProperties:f}=r.it;for(let h of t)if(p?.[h]===void 0&&!f.has(h)){let g=a.schemaEnv.baseId+a.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,lge.checkStrictMode)(a,y,a.opts.strictRequired)}}function c(){if(l||i)r.block$data(Lf.nil,d);else for(let p of t)(0,Nf.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(l||i){let f=e.let("valid",!0);r.block$data(f,()=>m(p,f)),r.ok(f)}else e.if((0,Nf.checkMissingProp)(r,t,p)),(0,Nf.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,Nf.noPropertyInData)(e,o,p,s.ownProperties),()=>r.error())})}function m(p,f){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,Nf.propertyInData)(e,o,p,s.ownProperties)),e.if((0,Lf.not)(f),()=>{r.error(),e.break()})},Lf.nil)}}};n_.default=uge});var Pq=Q(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var Df=Be(),dge={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,Df.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,Df._)`{limit: ${r}}`},mge={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:dge,code(r){let{keyword:e,data:t,schemaCode:n}=r,o=e==="maxItems"?Df.operators.GT:Df.operators.LT;r.fail$data((0,Df._)`${t}.length ${o} ${n}`)}};o_.default=mge});var hE=Q(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var Iq=Px();Iq.code='require("ajv/dist/runtime/equal").default';i_.default=Iq});var Oq=Q(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var a_=Tf(),Br=Be(),pge=lt(),fge=hE(),hge={message:({params:{i:r,j:e}})=>(0,Br.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Br._)`{i: ${r}, j: ${e}}`},gge={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hge,code(r){let{gen:e,data:t,$data:n,schema:o,parentSchema:i,schemaCode:a,it:s}=r;if(!n&&!o)return;let l=e.let("valid"),c=i.items?(0,a_.getSchemaTypes)(i.items):[];r.block$data(l,u,(0,Br._)`${a} === false`),r.ok(l);function u(){let f=e.let("i",(0,Br._)`${t}.length`),h=e.let("j");r.setParams({i:f,j:h}),e.assign(l,!0),e.if((0,Br._)`${f} > 1`,()=>(d()?m:p)(f,h))}function d(){return c.length>0&&!c.some(f=>f==="object"||f==="array")}function m(f,h){let g=e.name("item"),y=(0,a_.checkDataTypes)(c,g,s.opts.strictNumbers,a_.DataType.Wrong),b=e.const("indices",(0,Br._)`{}`);e.for((0,Br._)`;${f}--;`,()=>{e.let(g,(0,Br._)`${t}[${f}]`),e.if(y,(0,Br._)`continue`),c.length>1&&e.if((0,Br._)`typeof ${g} == "string"`,(0,Br._)`${g} += "_"`),e.if((0,Br._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(h,(0,Br._)`${b}[${g}]`),r.error(),e.assign(l,!1).break()}).code((0,Br._)`${b}[${g}] = ${f}`)})}function p(f,h){let g=(0,pge.useFunc)(e,fge.default),y=e.name("outer");e.label(y).for((0,Br._)`;${f}--;`,()=>e.for((0,Br._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Br._)`${g}(${t}[${f}], ${t}[${h}])`,()=>{r.error(),e.assign(l,!1).break(y)})))}}};s_.default=gge});var Nq=Q(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var l_=Be(),yge=lt(),Sge=hE(),bge={message:"must be equal to constant",params:({schemaCode:r})=>(0,l_._)`{allowedValue: ${r}}`},Ege={keyword:"const",$data:!0,error:bge,code(r){let{gen:e,data:t,$data:n,schemaCode:o,schema:i}=r;n||i&&typeof i=="object"?r.fail$data((0,l_._)`!${(0,yge.useFunc)(e,Sge.default)}(${t}, ${o})`):r.fail((0,l_._)`${i} !== ${t}`)}};c_.default=Ege});var Lq=Q(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});var kf=Be(),Tge=lt(),vge=hE(),Age={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,kf._)`{allowedValues: ${r}}`},wge={keyword:"enum",schemaType:"array",$data:!0,error:Age,code(r){let{gen:e,data:t,$data:n,schema:o,schemaCode:i,it:a}=r;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let s=o.length>=a.opts.loopEnum,l,c=()=>l??(l=(0,Tge.useFunc)(e,vge.default)),u;if(s||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,kf.or)(...o.map((f,h)=>m(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,kf._)`${c()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function m(p,f){let h=o[f];return typeof h=="object"&&h!==null?(0,kf._)`${c()}(${t}, ${p}[${f}])`:(0,kf._)`${t} === ${h}`}}};u_.default=wge});var Dq=Q(d_=>{"use strict";Object.defineProperty(d_,"__esModule",{value:!0});var Cge=vq(),Rge=Aq(),xge=Rq(),_ge=xq(),Mge=_q(),Pge=Mq(),Ige=Pq(),Oge=Oq(),Nge=Nq(),Lge=Lq(),Dge=[Cge.default,Rge.default,xge.default,_ge.default,Mge.default,Pge.default,Ige.default,Oge.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Nge.default,Lge.default];d_.default=Dge});var p_=Q(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});Ff.validateAdditionalItems=void 0;var Kl=Be(),m_=lt(),kge={message:({params:{len:r}})=>(0,Kl.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Kl._)`{limit: ${r}}`},Fge={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:kge,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,m_.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}kq(r,n)}};function kq(r,e){let{gen:t,schema:n,data:o,keyword:i,it:a}=r;a.items=!0;let s=t.const("len",(0,Kl._)`${o}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Kl._)`${s} <= ${e.length}`);else if(typeof n=="object"&&!(0,m_.alwaysValidSchema)(a,n)){let c=t.var("valid",(0,Kl._)`${s} <= ${e.length}`);t.if((0,Kl.not)(c),()=>l(c)),r.ok(c)}function l(c){t.forRange("i",e.length,s,u=>{r.subschema({keyword:i,dataProp:u,dataPropType:m_.Type.Num},c),a.allErrors||t.if((0,Kl.not)(c),()=>t.break())})}}Ff.validateAdditionalItems=kq;Ff.default=Fge});var f_=Q(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});Uf.validateTuple=void 0;var Fq=Be(),gE=lt(),Uge=xo(),Bge={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Uq(r,"additionalItems",e);t.items=!0,!(0,gE.alwaysValidSchema)(t,e)&&r.ok((0,Uge.validateArray)(r))}};function Uq(r,e,t=r.schema){let{gen:n,parentSchema:o,data:i,keyword:a,it:s}=r;u(o),s.opts.unevaluated&&t.length&&s.items!==!0&&(s.items=gE.mergeEvaluated.items(n,t.length,s.items));let l=n.name("valid"),c=n.const("len",(0,Fq._)`${i}.length`);t.forEach((d,m)=>{(0,gE.alwaysValidSchema)(s,d)||(n.if((0,Fq._)`${c} > ${m}`,()=>r.subschema({keyword:a,schemaProp:m,dataProp:m},l)),r.ok(l))});function u(d){let{opts:m,errSchemaPath:p}=s,f=t.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!h){let g=`"${a}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,gE.checkStrictMode)(s,g,m.strictTuples)}}}Uf.validateTuple=Uq;Uf.default=Bge});var Bq=Q(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var zge=f_(),$ge={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,zge.validateTuple)(r,"items")};h_.default=$ge});var $q=Q(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});var zq=Be(),Hge=lt(),jge=xo(),Gge=p_(),Wge={message:({params:{len:r}})=>(0,zq.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,zq._)`{limit: ${r}}`},Vge={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Wge,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:o}=t;n.items=!0,!(0,Hge.alwaysValidSchema)(n,e)&&(o?(0,Gge.validateAdditionalItems)(r,o):r.ok((0,jge.validateArray)(r)))}};g_.default=Vge});var Hq=Q(y_=>{"use strict";Object.defineProperty(y_,"__esModule",{value:!0});var Mo=Be(),yE=lt(),qge={message:({params:{min:r,max:e}})=>e===void 0?(0,Mo.str)`must contain at least ${r} valid item(s)`:(0,Mo.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Mo._)`{minContains: ${r}}`:(0,Mo._)`{minContains: ${r}, maxContains: ${e}}`},Kge={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:qge,code(r){let{gen:e,schema:t,parentSchema:n,data:o,it:i}=r,a,s,{minContains:l,maxContains:c}=n;i.opts.next?(a=l===void 0?1:l,s=c):a=1;let u=e.const("len",(0,Mo._)`${o}.length`);if(r.setParams({min:a,max:s}),s===void 0&&a===0){(0,yE.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&a>s){(0,yE.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,yE.alwaysValidSchema)(i,t)){let h=(0,Mo._)`${u} >= ${a}`;s!==void 0&&(h=(0,Mo._)`${h} && ${u} <= ${s}`),r.pass(h);return}i.items=!0;let d=e.name("valid");s===void 0&&a===1?p(d,()=>e.if(d,()=>e.break())):a===0?(e.let(d,!0),s!==void 0&&e.if((0,Mo._)`${o}.length > 0`,m)):(e.let(d,!1),m()),r.result(d,()=>r.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);p(h,()=>e.if(h,()=>f(g)))}function p(h,g){e.forRange("i",0,u,y=>{r.subschema({keyword:"contains",dataProp:y,dataPropType:yE.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,Mo._)`${h}++`),s===void 0?e.if((0,Mo._)`${h} >= ${a}`,()=>e.assign(d,!0).break()):(e.if((0,Mo._)`${h} > ${s}`,()=>e.assign(d,!1).break()),a===1?e.assign(d,!0):e.if((0,Mo._)`${h} >= ${a}`,()=>e.assign(d,!0)))}}};y_.default=Kge});var Wq=Q(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.validateSchemaDeps=Ni.validatePropertyDeps=Ni.error=void 0;var S_=Be(),Yge=lt(),Bf=xo();Ni.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,S_.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,S_._)`{property: ${r},
9
9
  missingProperty: ${n},
10
10
  depsCount: ${e},
11
- deps: ${t}}`};var Xge={keyword:"dependencies",type:"object",schemaType:"object",error:Ni.error,code(r){let[e,t]=Jge(r);jq(r,e),Gq(r,t)}};function Jge({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let o=Array.isArray(r[n])?e:t;o[n]=r[n]}return[e,t]}function jq(r,e=r.schema){let{gen:t,data:n,it:o}=r;if(Object.keys(e).length===0)return;let i=t.let("missing");for(let a in e){let s=e[a];if(s.length===0)continue;let l=(0,Bf.propertyInData)(t,n,a,o.opts.ownProperties);r.setParams({property:a,depsCount:s.length,deps:s.join(", ")}),o.allErrors?t.if(l,()=>{for(let c of s)(0,Bf.checkReportMissingProp)(r,c)}):(t.if((0,S_._)`${l} && (${(0,Bf.checkMissingProp)(r,s,i)})`),(0,Bf.reportMissingProp)(r,i),t.else())}}Ni.validatePropertyDeps=jq;function Gq(r,e=r.schema){let{gen:t,data:n,keyword:o,it:i}=r,a=t.name("valid");for(let s in e)(0,Yge.alwaysValidSchema)(i,e[s])||(t.if((0,Bf.propertyInData)(t,n,s,i.opts.ownProperties),()=>{let l=r.subschema({keyword:o,schemaProp:s},a);r.mergeValidEvaluated(l,a)},()=>t.var(a,!0)),r.ok(a))}Ni.validateSchemaDeps=Gq;Ni.default=Xge});var qq=Q(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var Vq=Be(),Zge=lt(),Qge={message:"property name must be valid",params:({params:r})=>(0,Vq._)`{propertyName: ${r.propertyName}}`},eye={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qge,code(r){let{gen:e,schema:t,data:n,it:o}=r;if((0,Zge.alwaysValidSchema)(o,t))return;let i=e.name("valid");e.forIn("key",n,a=>{r.setParams({propertyName:a}),r.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},i),e.if((0,Vq.not)(i),()=>{r.error(!0),o.allErrors||e.break()})}),r.ok(i)}};b_.default=eye});var T_=Q(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var SE=xo(),Xo=Be(),tye=da(),bE=lt(),rye={message:"must NOT have additional properties",params:({params:r})=>(0,Xo._)`{additionalProperty: ${r.additionalProperty}}`},nye={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rye,code(r){let{gen:e,schema:t,parentSchema:n,data:o,errsCount:i,it:a}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:s,opts:l}=a;if(a.props=!0,l.removeAdditional!=="all"&&(0,bE.alwaysValidSchema)(a,t))return;let c=(0,SE.allSchemaProperties)(n.properties),u=(0,SE.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Xo._)`${i} === ${tye.default.errors}`);function d(){e.forIn("key",o,g=>{!c.length&&!u.length?f(g):e.if(m(g),()=>f(g))})}function m(g){let y;if(c.length>8){let b=(0,bE.schemaRefOrVal)(a,n.properties,"properties");y=(0,SE.isOwnProperty)(e,b,g)}else c.length?y=(0,Xo.or)(...c.map(b=>(0,Xo._)`${g} === ${b}`)):y=Xo.nil;return u.length&&(y=(0,Xo.or)(y,...u.map(b=>(0,Xo._)`${(0,SE.usePattern)(r,b)}.test(${g})`))),(0,Xo.not)(y)}function p(g){e.code((0,Xo._)`delete ${o}[${g}]`)}function f(g){if(l.removeAdditional==="all"||l.removeAdditional&&t===!1){p(g);return}if(t===!1){r.setParams({additionalProperty:g}),r.error(),s||e.break();return}if(typeof t=="object"&&!(0,bE.alwaysValidSchema)(a,t)){let y=e.name("valid");l.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Xo.not)(y),()=>{r.reset(),p(g)})):(h(g,y),s||e.if((0,Xo.not)(y),()=>e.break()))}}function h(g,y,b){let E={keyword:"additionalProperties",dataProp:g,dataPropType:bE.Type.Str};b===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(E,y)}}};E_.default=nye});var Xq=Q(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var oye=Cf(),Kq=xo(),v_=lt(),Yq=T_(),iye={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:o,it:i}=r;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Yq.default.code(new oye.KeywordCxt(i,Yq.default,"additionalProperties"));let a=(0,Kq.allSchemaProperties)(t);for(let d of a)i.definedProperties.add(d);i.opts.unevaluated&&a.length&&i.props!==!0&&(i.props=v_.mergeEvaluated.props(e,(0,v_.toHash)(a),i.props));let s=a.filter(d=>!(0,v_.alwaysValidSchema)(i,t[d]));if(s.length===0)return;let l=e.name("valid");for(let d of s)c(d)?u(d):(e.if((0,Kq.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(l,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(l);function c(d){return i.opts.useDefaults&&!i.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};A_.default=iye});var e2=Q(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var Jq=xo(),EE=Be(),Zq=lt(),Qq=lt(),aye={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:o,it:i}=r,{opts:a}=i,s=(0,Jq.allSchemaProperties)(t),l=s.filter(h=>(0,Zq.alwaysValidSchema)(i,t[h]));if(s.length===0||l.length===s.length&&(!i.opts.unevaluated||i.props===!0))return;let c=a.strictSchema&&!a.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof EE.Name)&&(i.props=(0,Qq.evaluatedPropsToName)(e,i.props));let{props:d}=i;m();function m(){for(let h of s)c&&p(h),i.allErrors?f(h):(e.var(u,!0),f(h),e.if(u))}function p(h){for(let g in c)new RegExp(h).test(g)&&(0,Zq.checkStrictMode)(i,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,g=>{e.if((0,EE._)`${(0,Jq.usePattern)(r,h)}.test(${g})`,()=>{let y=l.includes(h);y||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Qq.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,EE._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,EE.not)(u),()=>e.break())})})}}};w_.default=aye});var t2=Q(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var sye=lt(),lye={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,sye.alwaysValidSchema)(n,t)){r.fail();return}let o=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),r.failResult(o,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};C_.default=lye});var r2=Q(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});var cye=xo(),uye={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:cye.validateUnion,error:{message:"must match a schema in anyOf"}};R_.default=uye});var n2=Q(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});var TE=Be(),dye=lt(),mye={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,TE._)`{passingSchemas: ${r.passing}}`},pye={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mye,code(r){let{gen:e,schema:t,parentSchema:n,it:o}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=t,a=e.let("valid",!1),s=e.let("passing",null),l=e.name("_valid");r.setParams({passing:s}),e.block(c),r.result(a,()=>r.reset(),()=>r.error(!0));function c(){i.forEach((u,d)=>{let m;(0,dye.alwaysValidSchema)(o,u)?e.var(l,!0):m=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,TE._)`${l} && ${a}`).assign(a,!1).assign(s,(0,TE._)`[${s}, ${d}]`).else(),e.if(l,()=>{e.assign(a,!0),e.assign(s,d),m&&r.mergeEvaluated(m,TE.Name)})})}}};x_.default=pye});var o2=Q(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});var fye=lt(),hye={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let o=e.name("valid");t.forEach((i,a)=>{if((0,fye.alwaysValidSchema)(n,i))return;let s=r.subschema({keyword:"allOf",schemaProp:a},o);r.ok(o),r.mergeEvaluated(s)})}};__.default=hye});var s2=Q(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var vE=Be(),a2=lt(),gye={message:({params:r})=>(0,vE.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,vE._)`{failingKeyword: ${r.ifClause}}`},yye={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gye,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,a2.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=i2(n,"then"),i=i2(n,"else");if(!o&&!i)return;let a=e.let("valid",!0),s=e.name("_valid");if(l(),r.reset(),o&&i){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(s,c("then",u),c("else",u))}else o?e.if(s,c("then")):e.if((0,vE.not)(s),c("else"));r.pass(a,()=>r.error(!0));function l(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);r.mergeEvaluated(u)}function c(u,d){return()=>{let m=r.subschema({keyword:u},s);e.assign(a,s),r.mergeValidEvaluated(m,a),d?e.assign(d,(0,vE._)`${u}`):r.setParams({ifClause:u})}}}};function i2(r,e){let t=r.schema[e];return t!==void 0&&!(0,a2.alwaysValidSchema)(r,t)}M_.default=yye});var l2=Q(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var Sye=lt(),bye={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,Sye.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};P_.default=bye});var c2=Q(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var Eye=p_(),Tye=Bq(),vye=f_(),Aye=$q(),wye=Hq(),Cye=Wq(),Rye=qq(),xye=T_(),_ye=Xq(),Mye=e2(),Pye=t2(),Iye=r2(),Oye=n2(),Nye=o2(),Lye=s2(),Dye=l2();function kye(r=!1){let e=[Pye.default,Iye.default,Oye.default,Nye.default,Lye.default,Dye.default,Rye.default,xye.default,Cye.default,_ye.default,Mye.default];return r?e.push(Tye.default,Aye.default):e.push(Eye.default,vye.default),e.push(wye.default),e}I_.default=kye});var u2=Q(O_=>{"use strict";Object.defineProperty(O_,"__esModule",{value:!0});var cr=Be(),Fye={message:({schemaCode:r})=>(0,cr.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,cr._)`{format: ${r}}`},Uye={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Fye,code(r,e){let{gen:t,data:n,$data:o,schema:i,schemaCode:a,it:s}=r,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=s;if(!l.validateFormats)return;o?m():p();function m(){let f=t.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=t.const("fDef",(0,cr._)`${f}[${a}]`),g=t.let("fType"),y=t.let("format");t.if((0,cr._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(g,(0,cr._)`${h}.type || "string"`).assign(y,(0,cr._)`${h}.validate`),()=>t.assign(g,(0,cr._)`"string"`).assign(y,h)),r.fail$data((0,cr.or)(b(),E()));function b(){return l.strictSchema===!1?cr.nil:(0,cr._)`${a} && !${y}`}function E(){let v=u.$async?(0,cr._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,cr._)`${y}(${n})`,w=(0,cr._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${n}))`;return(0,cr._)`${y} && ${y} !== true && ${g} === ${e} && !${w}`}}function p(){let f=d.formats[i];if(!f){b();return}if(f===!0)return;let[h,g,y]=E(f);h===e&&r.pass(v());function b(){if(l.strictSchema===!1){d.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${i}" ignored in schema at path "${c}"`}}function E(w){let L=w instanceof RegExp?(0,cr.regexpCode)(w):l.code.formats?(0,cr._)`${l.code.formats}${(0,cr.getProperty)(i)}`:void 0,I=t.scopeValue("formats",{key:i,ref:w,code:L});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,cr._)`${I}.validate`]:["string",w,I]}function v(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,cr._)`await ${y}(${n})`}return typeof g=="function"?(0,cr._)`${y}(${n})`:(0,cr._)`${y}.test(${n})`}}}};O_.default=Uye});var d2=Q(N_=>{"use strict";Object.defineProperty(N_,"__esModule",{value:!0});var Bye=u2(),zye=[Bye.default];N_.default=zye});var m2=Q(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.contentVocabulary=vd.metadataVocabulary=void 0;vd.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];vd.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var f2=Q(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});var $ye=Tq(),Hye=Dq(),jye=c2(),Gye=d2(),p2=m2(),Wye=[$ye.default,Hye.default,(0,jye.default)(),Gye.default,p2.metadataVocabulary,p2.contentVocabulary];L_.default=Wye});var g2=Q(AE=>{"use strict";Object.defineProperty(AE,"__esModule",{value:!0});AE.DiscrError=void 0;var h2;(function(r){r.Tag="tag",r.Mapping="mapping"})(h2||(AE.DiscrError=h2={}))});var S2=Q(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var Ad=Be(),D_=g2(),y2=aE(),Vye=Rf(),qye=lt(),Kye={message:({params:{discrError:r,tagName:e}})=>r===D_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Ad._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},Yye={keyword:"discriminator",type:"object",schemaType:"object",error:Kye,code(r){let{gen:e,data:t,schema:n,parentSchema:o,it:i}=r,{oneOf:a}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),c=e.const("tag",(0,Ad._)`${t}${(0,Ad.getProperty)(s)}`);e.if((0,Ad._)`typeof ${c} == "string"`,()=>u(),()=>r.error(!1,{discrError:D_.DiscrError.Tag,tag:c,tagName:s})),r.ok(l);function u(){let p=m();e.if(!1);for(let f in p)e.elseIf((0,Ad._)`${c} === ${f}`),e.assign(l,d(p[f]));e.else(),r.error(!1,{discrError:D_.DiscrError.Mapping,tag:c,tagName:s}),e.endIf()}function d(p){let f=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},f);return r.mergeEvaluated(h,Ad.Name),f}function m(){var p;let f={},h=y(o),g=!0;for(let v=0;v<a.length;v++){let w=a[v];if(w?.$ref&&!(0,qye.schemaHasRulesButRef)(w,i.self.RULES)){let I=w.$ref;if(w=y2.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,I),w instanceof y2.SchemaEnv&&(w=w.schema),w===void 0)throw new Vye.default(i.opts.uriResolver,i.baseId,I)}let L=(p=w?.properties)===null||p===void 0?void 0:p[s];if(typeof L!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);g=g&&(h||y(w)),b(L,v)}if(!g)throw new Error(`discriminator: "${s}" must be required`);return f;function y({required:v}){return Array.isArray(v)&&v.includes(s)}function b(v,w){if(v.const)E(v.const,w);else if(v.enum)for(let L of v.enum)E(L,w);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function E(v,w){if(typeof v!="string"||v in f)throw new Error(`discriminator: "${s}" values must be unique strings`);f[v]=w}}}};k_.default=Yye});var b2=Q((CHt,Xye)=>{Xye.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var U_=Q((Ut,F_)=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.MissingRefError=Ut.ValidationError=Ut.CodeGen=Ut.Name=Ut.nil=Ut.stringify=Ut.str=Ut._=Ut.KeywordCxt=Ut.Ajv=void 0;var Jye=hq(),Zye=f2(),Qye=S2(),E2=b2(),eSe=["/properties"],wE="http://json-schema.org/draft-07/schema",wd=class extends Jye.default{_addVocabularies(){super._addVocabularies(),Zye.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Qye.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(E2,eSe):E2;this.addMetaSchema(e,wE,!1),this.refs["http://json-schema.org/schema"]=wE}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(wE)?wE:void 0)}};Ut.Ajv=wd;F_.exports=Ut=wd;F_.exports.Ajv=wd;Object.defineProperty(Ut,"__esModule",{value:!0});Ut.default=wd;var tSe=Cf();Object.defineProperty(Ut,"KeywordCxt",{enumerable:!0,get:function(){return tSe.KeywordCxt}});var Cd=Be();Object.defineProperty(Ut,"_",{enumerable:!0,get:function(){return Cd._}});Object.defineProperty(Ut,"str",{enumerable:!0,get:function(){return Cd.str}});Object.defineProperty(Ut,"stringify",{enumerable:!0,get:function(){return Cd.stringify}});Object.defineProperty(Ut,"nil",{enumerable:!0,get:function(){return Cd.nil}});Object.defineProperty(Ut,"Name",{enumerable:!0,get:function(){return Cd.Name}});Object.defineProperty(Ut,"CodeGen",{enumerable:!0,get:function(){return Cd.CodeGen}});var rSe=oE();Object.defineProperty(Ut,"ValidationError",{enumerable:!0,get:function(){return rSe.default}});var nSe=Rf();Object.defineProperty(Ut,"MissingRefError",{enumerable:!0,get:function(){return nSe.default}})});var _2=Q(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.formatNames=Di.fastFormats=Di.fullFormats=void 0;function Li(r,e){return{validate:r,compare:e}}Di.fullFormats={date:Li(w2,H_),time:Li(z_(!0),j_),"date-time":Li(T2(!0),R2),"iso-time":Li(z_(),C2),"iso-date-time":Li(T2(),x2),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:cSe,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:gSe,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:uSe,int32:{type:"number",validate:pSe},int64:{type:"number",validate:fSe},float:{type:"number",validate:A2},double:{type:"number",validate:A2},password:!0,binary:!0};Di.fastFormats={...Di.fullFormats,date:Li(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,H_),time:Li(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,j_),"date-time":Li(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,R2),"iso-time":Li(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,C2),"iso-date-time":Li(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,x2),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Di.formatNames=Object.keys(Di.fullFormats);function oSe(r){return r%4===0&&(r%100!==0||r%400===0)}var iSe=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aSe=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w2(r){let e=iSe.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&oSe(t)?29:aSe[n])}function H_(r,e){if(r&&e)return r>e?1:r<e?-1:0}var B_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function z_(r){return function(t){let n=B_.exec(t);if(!n)return!1;let o=+n[1],i=+n[2],a=+n[3],s=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||r&&!s)return!1;if(o<=23&&i<=59&&a<60)return!0;let d=i-u*l,m=o-c*l-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&a<61}}function j_(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function C2(r,e){if(!(r&&e))return;let t=B_.exec(r),n=B_.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r<e?-1:0}var $_=/t|\s/i;function T2(r){let e=z_(r);return function(n){let o=n.split($_);return o.length===2&&w2(o[0])&&e(o[1])}}function R2(r,e){if(!(r&&e))return;let t=new Date(r).valueOf(),n=new Date(e).valueOf();if(t&&n)return t-n}function x2(r,e){if(!(r&&e))return;let[t,n]=r.split($_),[o,i]=e.split($_),a=H_(t,o);if(a!==void 0)return a||j_(n,i)}var sSe=/\/|:/,lSe=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function cSe(r){return sSe.test(r)&&lSe.test(r)}var v2=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function uSe(r){return v2.lastIndex=0,v2.test(r)}var dSe=-(2**31),mSe=2**31-1;function pSe(r){return Number.isInteger(r)&&r<=mSe&&r>=dSe}function fSe(r){return Number.isInteger(r)}function A2(){return!0}var hSe=/[^\\]\\Z/;function gSe(r){if(hSe.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var M2=Q(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});Rd.formatLimitDefinition=void 0;var ySe=U_(),Jo=Be(),Es=Jo.operators,CE={formatMaximum:{okStr:"<=",ok:Es.LTE,fail:Es.GT},formatMinimum:{okStr:">=",ok:Es.GTE,fail:Es.LT},formatExclusiveMaximum:{okStr:"<",ok:Es.LT,fail:Es.GTE},formatExclusiveMinimum:{okStr:">",ok:Es.GT,fail:Es.LTE}},SSe={message:({keyword:r,schemaCode:e})=>(0,Jo.str)`should be ${CE[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Jo._)`{comparison: ${CE[r].okStr}, limit: ${e}}`};Rd.formatLimitDefinition={keyword:Object.keys(CE),type:"string",schemaType:"string",$data:!0,error:SSe,code(r){let{gen:e,data:t,schemaCode:n,keyword:o,it:i}=r,{opts:a,self:s}=i;if(!a.validateFormats)return;let l=new ySe.KeywordCxt(i,s.RULES.all.format.definition,"format");l.$data?c():u();function c(){let m=e.scopeValue("formats",{ref:s.formats,code:a.code.formats}),p=e.const("fmt",(0,Jo._)`${m}[${l.schemaCode}]`);r.fail$data((0,Jo.or)((0,Jo._)`typeof ${p} != "object"`,(0,Jo._)`${p} instanceof RegExp`,(0,Jo._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let m=l.schema,p=s.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:p,code:a.code.formats?(0,Jo._)`${a.code.formats}${(0,Jo.getProperty)(m)}`:void 0});r.fail$data(d(f))}function d(m){return(0,Jo._)`${m}.compare(${t}, ${n}) ${CE[o].fail} 0`}},dependencies:["format"]};var bSe=r=>(r.addKeyword(Rd.formatLimitDefinition),r);Rd.default=bSe});var N2=Q((zf,O2)=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var xd=_2(),ESe=M2(),G_=Be(),P2=new G_.Name("fullFormats"),TSe=new G_.Name("fastFormats"),W_=(r,e={keywords:!0})=>{if(Array.isArray(e))return I2(r,e,xd.fullFormats,P2),r;let[t,n]=e.mode==="fast"?[xd.fastFormats,TSe]:[xd.fullFormats,P2],o=e.formats||xd.formatNames;return I2(r,o,t,n),e.keywords&&(0,ESe.default)(r),r};W_.get=(r,e="full")=>{let n=(e==="fast"?xd.fastFormats:xd.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function I2(r,e,t,n){var o,i;(o=(i=r.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,G_._)`require("ajv-formats/dist/formats").${n}`);for(let a of e)r.addFormat(a,t[a])}O2.exports=zf=W_;Object.defineProperty(zf,"__esModule",{value:!0});zf.default=W_});var Z_=Q((jf,J_)=>{"use strict";(function(r,e){if(typeof jf=="object"&&typeof J_=="object")J_.exports=e();else if(typeof define=="function"&&define.amd)define([],e);else{var t=e();for(var n in t)(typeof jf=="object"?jf:r)[n]=t[n]}})(typeof self<"u"?self:jf,function(){return function(r){var e={};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=r,t.c=e,t.d=function(n,o,i){t.o(n,o)||Object.defineProperty(n,o,{enumerable:!0,get:i})},t.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,o){if(1&o&&(n=t(n)),8&o||4&o&&typeof n=="object"&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&o&&typeof n!="string")for(var a in n)t.d(i,a,function(s){return n[s]}.bind(null,a));return i},t.n=function(n){var o=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(o,"a",o),o},t.o=function(n,o){return Object.prototype.hasOwnProperty.call(n,o)},t.p="",t(t.s=0)}([function(r,e,t){"use strict";var n;t.r(e),function(y){y[y.Empty=0]="Empty",y[y.InsideToken=1]="InsideToken",y[y.InsideSingleQuotedToken=2]="InsideSingleQuotedToken",y[y.InsideDoubleQuotedToken=3]="InsideDoubleQuotedToken",y[y.AfterEscapeInsideToken=4]="AfterEscapeInsideToken",y[y.AfterEscapeInsideSingleQuotedToken=5]="AfterEscapeInsideSingleQuotedToken",y[y.AfterEscapeInsideDoubleQuotedToken=6]="AfterEscapeInsideDoubleQuotedToken"}(n||(n={}));var o=function(y){return[null,null]},i={onCharacter:o,onWhitespace:o,onDoubleQuote:o,onSingleQuote:o,onEscape:o},a=function(){return(a=Object.assign||function(y){for(var b,E=1,v=arguments.length;E<v;E++)for(var w in b=arguments[E])Object.prototype.hasOwnProperty.call(b,w)&&(y[w]=b[w]);return y}).apply(this,arguments)},s=a({},i,{stateHandle:n.AfterEscapeInsideDoubleQuotedToken,onCharacter:function(y){return["\\"+y,n.InsideDoubleQuotedToken]},onWhitespace:function(y){return["\\"+y,n.InsideDoubleQuotedToken]},onSingleQuote:function(y){return["\\"+y,n.InsideDoubleQuotedToken]},onDoubleQuote:function(y){return[y,n.InsideDoubleQuotedToken]},onEscape:function(y){return[y,n.InsideDoubleQuotedToken]}}),l=a({},i,{stateHandle:n.AfterEscapeInsideSingleQuotedToken,onCharacter:function(y){return["\\"+y,n.InsideSingleQuotedToken]},onWhitespace:function(y){return["\\"+y,n.InsideSingleQuotedToken]},onSingleQuote:function(y){return[y,n.InsideSingleQuotedToken]},onDoubleQuote:function(y){return["\\"+y,n.InsideSingleQuotedToken]},onEscape:function(y){return[y,n.InsideSingleQuotedToken]}}),c=a({},i,{stateHandle:n.AfterEscapeInsideToken,onCharacter:function(y){return[y,n.InsideToken]},onWhitespace:function(y){return[y,n.InsideToken]},onSingleQuote:function(y){return[y,n.InsideToken]},onDoubleQuote:function(y){return[y,n.InsideToken]},onEscape:function(y){return[y,n.InsideToken]}}),u=a({},i,{stateHandle:n.Empty,onCharacter:function(y){return[y,n.InsideToken]},onSingleQuote:function(){return[null,n.InsideSingleQuotedToken]},onDoubleQuote:function(){return[null,n.InsideDoubleQuotedToken]},onEscape:function(){return[null,n.AfterEscapeInsideToken]}}),d=a({},i,{stateHandle:n.InsideDoubleQuotedToken,onCharacter:function(y){return[y,null]},onWhitespace:function(y){return[y,null]},onSingleQuote:function(y){return[y,null]},onDoubleQuote:function(){return["",n.Empty]},onEscape:function(){return["",n.AfterEscapeInsideDoubleQuotedToken]}}),m=a({},i,{stateHandle:n.InsideSingleQuotedToken,onCharacter:function(y){return[y,null]},onWhitespace:function(y){return[y,null]},onSingleQuote:function(){return["",n.Empty]},onDoubleQuote:function(y){return[y,null]},onEscape:function(){return["",n.AfterEscapeInsideSingleQuotedToken]}}),p=[u,a({},i,{stateHandle:n.InsideToken,onCharacter:function(y){return[y,null]},onWhitespace:function(){return[null,n.Empty]},onSingleQuote:function(){return["",n.InsideSingleQuotedToken]},onDoubleQuote:function(){return["",n.InsideDoubleQuotedToken]},onEscape:function(){return["",n.AfterEscapeInsideToken]}}),m,d,c,l,s];function f(y){for(var b=0,E=p;b<E.length;b++){var v=E[b];if(v.stateHandle===y)return v}throw new Error("State with handle = "+y+" cannot be found")}var h=function(){function y(){this.currentState=f(n.Empty)}return y.prototype.handleCharacter=function(b){var E=this.performTransition(b),v=E[0],w=E[1];return w!==null&&(this.currentState=f(w)),v},y.prototype.performTransition=function(b){var E=this.currentState;switch(b){case" ":return E.onWhitespace(b);case"'":return E.onSingleQuote(b);case'"':return E.onDoubleQuote(b);case"\\":return E.onEscape(b);default:return E.onCharacter(b)}},y}();function g(y){for(var b=new h,E=[],v=0,w=0,L=y;w<L.length;w++){var I=L[w],A=b.handleCharacter(I);A!==null?E[v]=E[v]?E[v]+A:A:E[v]&&v++}return E}t.d(e,"default",function(){return g}),g.default=g}]).default})});import B$e,{multistream as $$e}from"pino";import j$e from"pino-pretty";import{z as JE}from"zod";var CEe=JE.object({input:JE.string(),agentConfigVersion:JE.string().optional()}),Zf="finish";import{z as gr}from"zod";var _Ee=gr.object({srcs:gr.array(gr.string()),urls:gr.array(gr.string()),desiredSrc:gr.string().optional(),desiredUrl:gr.string().optional()}),MM=gr.object({srcRegex:gr.string().optional(),urlRegex:gr.string().optional()}),PM=gr.object({x:gr.number(),y:gr.number(),correlation:gr.number()}),MEe=gr.object({searchImageBase64String:gr.string(),pageImageBase64String:gr.string(),id:gr.string().uuid(),timeoutMs:gr.number().max(1e4).min(0).optional()});import{z as U}from"zod";import*as W from"zod";import{extendZodWithOpenApi as k4}from"zod-openapi";import Id from"zod";var Od=Id.object({updatedAt:Id.coerce.date().optional()}),ec=Id.object({contentType:Id.enum(["image/jpeg","image/png"]),id:Id.string()});k4(W);var ei=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(ei||{}),F4=W.object({mPathSelectorTokens:W.string().array(),frameSrcRegex:W.string().optional(),frameUrlRegex:W.string().optional(),indices:W.number().array()}),Nd=W.object({result:W.number(),traceId:W.string()}).array(),Oo=W.object({type:W.literal("GCS_TRACES"),traces:Nd}),Tn=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(Tn||{}),IM=W.object({attributes:W.record(W.string(),W.string()).optional(),text:W.string().optional(),position:W.object({x1:W.number(),y1:W.number(),x2:W.number(),y2:W.number(),tolerance:W.nativeEnum(Tn)}).optional(),shape:W.object({width:W.number(),height:W.number(),tolerance:W.nativeEnum(Tn)}).optional(),boundingBox:W.object({x:W.number(),y:W.number(),width:W.number(),height:W.number()}).optional()}),U4=W.object({selectors:W.string().array(),requirements:IM.optional(),relativeAngleRadians:W.number().min(0).max(2*Math.PI).optional(),relativeDistance:W.number().optional()}),Fi=W.object({id:W.number().int(),dataMomenticId:W.number().int().optional(),selector:W.string().optional(),hybridSelector:W.object({textContent:W.string().nullish(),attributes:W.record(W.string(),W.string().optional()),tagName:W.string(),expandShadowRoot:W.boolean().optional(),classNames:W.string().array(),nthChild:W.number()}).array().optional(),generatedSelectors:W.string().array().optional(),requirements:IM.optional(),additionalElements:U4.array().optional(),role:W.string().optional(),name:W.string().optional(),numChildren:W.number().optional(),content:W.string().optional(),pathFromRoot:W.string().optional(),serializedHtml:W.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:W.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:W.string().url().optional().or(ec.optional()),boundingBox:W.object({x:W.number().optional(),y:W.number().optional(),width:W.number(),height:W.number()}).describe("css pixel bounding box").optional(),frameCache:F4.optional(),inputDescription:W.string().optional().describe("the description that generated this cache"),targetSource:W.nativeEnum(ei).optional(),targetUpdateTime:W.string().optional(),targetUpdateLoggerTags:W.record(W.string(),W.string()).optional(),cacheResolutionUpdateSource:W.string().optional(),cacheResolutionUpdateTime:W.string().optional(),cacheResolutionUpdateLoggerTags:W.record(W.string(),W.string()).optional(),memory:Oo.optional()}).openapi({ref:"ElementTargetCache"});function tc(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var B4=W.object({type:W.literal("description"),elementDescriptor:W.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),z4=W.object({x:W.number(),y:W.number()}),$4=W.object({type:W.literal("coordinates"),pixels:z4}).openapi({ref:"CoordinatesTarget"});function ha(r){return r.type==="description"}function ti(r){return r.type==="coordinates"}var zr=W.discriminatedUnion("type",[B4,$4]).openapi({ref:"ElementTarget"});function ZE(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function OM(r){return Oo.safeParse(r).success}import{v4 as ht}from"uuid";import*as x from"zod";import{extendZodWithOpenApi as Q4}from"zod-openapi";import{z as Ge}from"zod";import{extendZodWithOpenApi as H4}from"zod-openapi";import{z as Ld}from"zod";var Dd=Ld.object({result:Ld.boolean(),traceId:Ld.string()}).array(),Rs=Ld.object({type:Ld.literal("GCS_TRACES"),traces:Dd}),QE=Od.extend({memory:Rs.optional()});var rc=(v=>(v.MissingScript="missing-script",v.EvaluationError="evaluation-error",v.NoSelectors="no-selectors",v.NoSelectorsMatched="no-selectors-matched",v.NotEnoughSelectorsMatched="not-enough-selectors-matched",v.CandidateHasNoBoundingBox="candidate-has-no-bounding-box",v.AdditionalElementsDoNotExist="additional-elements-do-not-exist",v.BoundingBoxChanged="bounding-box-changed",v.FailedLdistCheck="failing-ldist",v.FailedTextRequirements="failed-text-requirements",v.FailedAttributeRequirements="failed-attribute-requirements",v.FailedBoundingBoxRequirements="failed-bounding-box-requirements",v.FailedPositionRequirements="failed-position-requirements",v.FailedShapeRequirements="failed-shape-requirements",v.NoWinnerFound="no-winner-found",v.AmbiguousWinner="ambiguous-winner",v.WeakWinner="weak-winner",v.SecondaryResolutionFailed="secondary-resolution-failed",v.CouldNotFindIframe="could-not-find-iframe",v.Unknown="unknown",v))(rc||{});H4(Ge);var NM=Ge.object({thoughts:Ge.string(),result:Ge.boolean(),relevantElements:Ge.array(Ge.number()).optional(),updatedMemory:Dd.optional()}),rn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(rn||{});var j4=Ge.object({type:Ge.literal("ELEMENT_NAME"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),value:Ge.string()}).openapi({ref:"ElementNameAssertion"}),G4=Ge.object({type:Ge.literal("ELEMENT_STYLE"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),property:Ge.string(),value:Ge.string()}).openapi({ref:"ElementStyleAssertion"}),W4=Ge.object({type:Ge.literal("ELEMENT_CONTENT"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),value:Ge.string()}).openapi({ref:"ElementContentAssertion"}),V4=Ge.object({type:Ge.literal("ELEMENT_ATTRIBUTE"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),attr:Ge.string(),value:Ge.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Dn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Dn||{});var q4=Ge.object({type:Ge.literal("ELEMENT_EXISTENCE"),negated:Ge.boolean().optional(),condition:Ge.nativeEnum(Dn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Qf=Ge.discriminatedUnion("type",[W4,V4,q4,j4,G4]).openapi({ref:"ManualElementAssertion"});var K4=Ge.object({type:Ge.literal("CONTENT"),negated:Ge.boolean().optional(),value:Ge.string()}).openapi({ref:"PageContentAssertion"}),LM=Ge.discriminatedUnion("type",[K4]).openapi({ref:"ManualPageAssertion"});import nn from"zod";var kd=nn.discriminatedUnion("type",[nn.object({type:nn.literal("SUBSTRING"),url:nn.string()}),nn.object({type:nn.literal("GLOB"),glob:nn.string()}),nn.object({type:nn.literal("REGEX"),regex:nn.string()}),nn.object({type:nn.literal("DOMAIN"),domain:nn.string()})]),Fd=nn.object({urlMatcher:kd,method:nn.string().optional()});import{z as it}from"zod";var Y4=it.object({type:it.literal("json"),content:it.string().describe("The JSON content to send in the request body")}),X4=it.object({type:it.literal("form-urlencoded"),content:it.record(it.string(),it.string()).describe("The form fields to send in the request body")}),J4=it.discriminatedUnion("type",[Y4,X4]),Z4=["GET","POST","PUT","DELETE","PATCH"],Ud=it.enum(Z4),xs=it.object({url:it.string(),method:Ud,headers:it.record(it.string(),it.string()).optional(),params:it.record(it.string(),it.string()).optional(),body:J4.optional(),timeout:it.number().int().optional().describe("Max seconds to wait for the request to complete")}),DM=it.object({url:it.string(),headers:it.record(it.string(),it.string()).optional(),query:it.string(),variables:it.string().optional(),timeout:it.number().int().optional().describe("Max seconds to wait for the request to complete")}),eh=it.object({code:it.string(),fragment:it.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:it.union([it.literal("NODE"),it.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:it.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Lt=(ge=>(ge.AI_EXTRACT="AI_EXTRACT",ge.AI_ASSERTION="AI_ASSERTION",ge.AUTH_LOAD="AUTH_LOAD",ge.AUTH_SAVE="AUTH_SAVE",ge.BLUR="BLUR",ge.CAPTCHA="CAPTCHA",ge.CLICK="CLICK",ge.COOKIE="COOKIE",ge.COPY="COPY",ge.DIALOG="DIALOG",ge.DRAG="DRAG",ge.ELEMENT_CHECK="ELEMENT_CHECK",ge.FILE_UPLOAD="FILE_UPLOAD",ge.FOCUS="FOCUS",ge.GO_BACK="GO_BACK",ge.GO_FORWARD="GO_FORWARD",ge.HOVER="HOVER",ge.JAVASCRIPT="JAVASCRIPT",ge.LOCAL_STORAGE="LOCAL_STORAGE",ge.MOUSE_DRAG="MOUSE_DRAG",ge.NAVIGATE="NAVIGATE",ge.NEW_TAB="NEW_TAB",ge.PAGE_CHECK="PAGE_CHECK",ge.PASTE="PASTE",ge.PRESS="PRESS",ge.KEY_DOWN="KEY_DOWN",ge.KEY_UP="KEY_UP",ge.REFRESH="REFRESH",ge.REQUEST="REQUEST",ge.GRAPHQL_REQUEST="GRAPHQL_REQUEST",ge.SCROLL_DOWN="SCROLL_DOWN",ge.SCROLL_UP="SCROLL_UP",ge.SCROLL_LEFT="SCROLL_LEFT",ge.SCROLL_RIGHT="SCROLL_RIGHT",ge.SELECT_OPTION="SELECT_OPTION",ge.SWITCH_TAB="TAB",ge.TYPE="TYPE",ge.VISUAL_DIFF="VISUAL_DIFF",ge.WAIT="WAIT",ge.WAIT_FOR_URL="WAIT_FOR_URL",ge.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",ge.AWAIT_LISTENER="AWAIT_LISTENER",ge.RECORD_REQUESTS="RECORD_REQUESTS",ge.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",ge.SET_HEADER="SET_HEADER",ge.MOCK_ROUTE="MOCK_ROUTE",ge.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",ge.OFFLINE_MODE="OFFLINE_MODE",ge.SUCCESS="SUCCESS",ge))(Lt||{});Q4(x);var Se=x.object({thoughts:x.string().optional(),id:x.string().uuid().describe("unique identifier to this step, used for step cache")}),qn=x.object({useSelector:x.boolean().optional(),force:x.boolean().optional(),disableCache:x.boolean().optional().describe("disable element caching for this step"),iframeUrl:x.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Kn=Od.extend({target:Fi}).optional().openapi({ref:"SingleTargetCache"});function rh(r){return!!r&&Kn.safeParse(r).success}var nh=x.object({loadTimeout:x.number().int().max(60).optional().describe("Max seconds for the page to load")}),kM=Se.merge(nh).merge(x.object({type:x.literal("NAVIGATE"),url:x.string()})).openapi({ref:"NavigateCommand"}),oh=qn.merge(x.object({cache:Kn})),_s=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_UP"),deltaY:x.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Ms=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_DOWN"),deltaY:x.number().optional()}))).openapi({ref:"ScrollDownCommand"}),nc=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_LEFT"),deltaX:x.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),oc=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_RIGHT"),deltaX:x.number().optional()}))).openapi({ref:"ScrollRightCommand"}),uTe=x.discriminatedUnion("type",[_s,Ms,nc,oc]).openapi({ref:"AllScrollCommands"}),eY=Se.merge(x.object({type:x.literal("DIALOG"),action:x.union([x.literal("ACCEPT"),x.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),FM=Se.merge(x.object({type:x.literal("WAIT"),delay:x.number()})).openapi({ref:"WaitCommand"}),tY=x.object({caseInsensitive:x.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:x.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:x.number().int().optional().describe("Max seconds to wait for the URL to match")}),UM=Se.extend({type:x.literal("WAIT_FOR_URL"),matcher:kd}).merge(tY).openapi({ref:"WaitUrlCommand"}),BM=Se.merge(nh).merge(x.object({type:x.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),zM=Se.merge(x.object({type:x.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),$M=Se.merge(x.object({type:x.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),rY=Se.extend({type:x.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),nY=Se.extend({type:x.literal("AUTH_LOAD"),storageState:x.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),eT=Se.merge(qn).extend({type:x.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),HM=Se.extend({type:x.literal("COPY"),value:x.string()}).openapi({ref:"CopyCommand"}),jM=Se.extend({type:x.literal("PASTE")}).openapi({ref:"PasteCommand"}),GM=Se.merge(eh).extend({type:x.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),ic=Se.merge(qn).extend({type:x.literal("CLICK"),target:zr,doubleClick:x.boolean().optional(),rightClick:x.boolean().optional(),waitForDownload:x.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:x.number().optional(),downloadTimeoutMs:x.number().optional(),cache:Kn,relativePosition:x.object({x:x.number(),y:x.number()}).optional()}).openapi({ref:"ClickCommand"}),WM=Od.extend({fromTarget:Fi.optional(),toTarget:Fi.optional()}),ac=Se.merge(qn).merge(x.object({type:x.literal("DRAG"),fromTarget:zr,toTarget:zr,steps:x.number().optional(),hoverSeconds:x.number().optional().describe("Seconds to hover the object before dropping"),cache:WM.optional()})).openapi({ref:"DragCommand"}),sc=Se.merge(qn).merge(x.object({type:x.literal("MOUSE_DRAG"),target:zr.optional(),deltaX:x.string().describe("pixels to move horizontally, can be template"),deltaY:x.string().describe("pixels to move vertically, can be template"),steps:x.number().optional(),cache:Kn})).openapi({ref:"MouseDragCommand"}),lc=Se.merge(qn).merge(x.object({type:x.literal("HOVER"),target:zr,cache:Kn})).openapi({ref:"HoverCommand"}),Bd=Se.merge(qn).merge(x.object({type:x.literal("FOCUS"),target:zr,cache:Kn})).openapi({ref:"FocusCommand"}),zd=Se.merge(qn).extend({type:x.literal("BLUR"),target:zr.optional(),cache:Kn}).openapi({ref:"BlurCommand"}),oY=x.object({type:x.literal("URL"),url:x.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),iY=x.object({type:x.literal("USER_FILE"),name:x.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),aY=Se.extend({type:x.literal("FILE_UPLOAD"),fileSource:x.discriminatedUnion("type",[oY,iY]),filename:x.string().optional()}).openapi({ref:"FileUploadCommand"}),VM=x.discriminatedUnion("type",[x.object({type:x.literal("VALUE"),value:x.string()}),x.object({type:x.literal("LABEL"),label:x.string()}),x.object({type:x.literal("INDEX"),index:x.coerce.string()})]),cc=Se.merge(qn).extend({type:x.literal("SELECT_OPTION"),target:zr,cache:Kn,choice:VM.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),tT=x.union([x.literal("MULTIMODAL"),x.literal("VISION_ONLY")]),$d=Se.merge(x.object({type:x.literal("AI_ASSERTION"),assertion:x.string(),disableCache:x.boolean().optional(),iframeUrl:x.string().optional(),contextChoice:tT.optional(),timeout:x.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:QE.optional(),source:x.string().optional()})).openapi({ref:"AIAssertionCommand"}),ur=5,Ps=600,uc=Se.merge(qn).extend({type:x.literal("ELEMENT_CHECK"),target:zr,assertion:Qf,cache:Kn.or(QE).optional(),timeout:x.number().int().min(0).max(Ps).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),qM=Se.extend({type:x.literal("PAGE_CHECK"),assertion:LM,iframeUrl:x.string().optional().describe("url or url regex for the iframe"),timeout:x.number().int().min(0).max(Ps).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),KM=Se.merge(x.object({type:x.literal("AI_EXTRACT"),goal:x.string(),schema:x.string().optional(),envKey:x.string().optional(),disableCache:x.boolean().optional(),iframeUrl:x.string().optional()})).openapi({ref:"AIExtractCommand"}),sY=x.object({clearContent:x.boolean().optional(),forceClearContent:x.boolean().optional(),delay:x.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:x.boolean().optional(),pressEnter:x.boolean().optional(),relativePosition:x.object({x:x.number(),y:x.number()}).optional()}),YM=25,dc=Se.merge(qn).merge(sY).extend({type:x.literal("TYPE"),target:zr.optional(),value:x.string(),cache:Kn}).openapi({ref:"TypeCommand"}),XM=Se.merge(x.object({type:x.literal("PRESS"),value:x.string(),repeat:x.number().optional(),convertMeta:x.boolean().optional(),delayMs:x.number().optional()})).openapi({ref:"PressCommand"}),JM=Se.merge(x.object({type:x.literal("KEY_DOWN"),value:x.string(),convertMeta:x.boolean().optional()})).openapi({ref:"KeyDownCommand"}),ZM=Se.merge(x.object({type:x.literal("KEY_UP"),value:x.string(),convertMeta:x.boolean().optional()})).openapi({ref:"KeyUpCommand"}),lY=x.object({type:x.literal("SUBSTRING"),substring:x.string()}),cY=x.object({type:x.literal("REGEX"),pattern:x.string()}),uY=x.object({type:x.literal("INDEX"),index:x.coerce.string()}),dY=x.discriminatedUnion("type",[lY,cY,uY]),mY=Se.merge(nh).merge(x.object({type:x.literal("TAB"),action:dY})).openapi({ref:"TabCommand"}),QM=Se.merge(nh).merge(x.object({type:x.literal("NEW_TAB"),url:x.string()})).openapi({ref:"NewTabCommand"}),pY=Se.merge(x.object({type:x.literal("COOKIE"),value:x.string()})).openapi({ref:"CookieCommand"}),eP=Se.merge(x.object({type:x.literal("LOCAL_STORAGE"),key:x.string(),value:x.string()})).openapi({ref:"LocalStorageCommand"}),tP=Se.extend({type:x.literal("REQUEST")}).merge(xs).openapi({ref:"RequestCommand"}),Is=x.object({status:x.number().optional(),headers:x.record(x.string(),x.string()),json:x.unknown().optional(),text:x.string().optional(),cookies:x.record(x.string(),x.unknown()).array().optional(),request:x.object({url:x.string(),method:x.string(),headers:x.record(x.string(),x.string()),json:x.unknown().optional()})}),rP=Se.extend({type:x.literal("GRAPHQL_REQUEST")}).merge(DM).openapi({ref:"GraphQLRequestCommand"}),nP=Se.merge(x.object({type:x.literal("SUCCESS"),condition:$d.optional()})).openapi({ref:"SuccessCommand"}),oP=Se.merge(x.object({type:x.literal("FAILURE")})).openapi({ref:"FailureCommand"}),fY=x.object({data:x.union([x.string().describe("location at which to find a jpg - public URL or local"),ec]),width:x.number(),height:x.number()});var Hd=Se.merge(qn).merge(x.object({type:x.literal("VISUAL_DIFF"),threshold:x.number().optional().describe("default 0.1"),target:zr.optional(),screenshot:fY.optional(),cache:Kn})).openapi({ref:"VisualDiffCommand"}),iP=Se.merge(x.object({type:x.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Fd,key:x.string()})).openapi({ref:"RegisterRequestListenerCommand"}),hY=Se.merge(x.object({type:x.literal("AWAIT_LISTENER"),key:x.string(),timeout:x.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),aP=Se.merge(x.object({type:x.literal("RECORD_REQUESTS"),requestMatcher:Fd,key:x.string()})).openapi({ref:"RecordRequestsCommand"}),gY=Se.merge(x.object({type:x.literal("GET_RECORDED_REQUESTS"),key:x.string()})).openapi({ref:"GetRecordedRequestsCommand"}),sP=Se.merge(x.object({type:x.literal("SET_HEADER"),name:x.string(),value:x.string(),requestMatcher:Fd.optional()})).openapi({ref:"SetHeaderCommand"}),lP=Se.merge(x.object({type:x.literal("MOCK_ROUTE"),requestMatcher:Fd,responseGenerator:x.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:x.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:x.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),yY=Se.merge(x.object({type:x.literal("REMOVE_ROUTE_MOCK"),key:x.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),SY=Se.merge(x.object({type:x.literal("OFFLINE_MODE"),enable:x.boolean()})).openapi({ref:"OfflineModeCommand"}),bY=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],dTe=[...bY,"DRAG"],EY=x.discriminatedUnion("type",[ic,dc,XM,JM,ZM,cc,kM,Ms,_s,$d,zM,lc,FM]),TY=x.discriminatedUnion("type",[...EY.options,ac]),vY=x.discriminatedUnion("type",[...TY.options]),cP=x.discriminatedUnion("type",[...vY.options,nP]),rT=x.discriminatedUnion("type",[nP,ic,dc,XM,JM,ZM,cc,kM,Ms,_s,$d,zM,lc,FM,GM,uc,qM,QM,UM,KM,HM,$M,eP,ac,sc,jM,BM,tP,rP,sP,iP,aP,lP]),AY=x.discriminatedUnion("type",[KM,nY,rY,eT,pY,HM,eY,uc,aY,$M,GM,eP,sc,QM,qM,jM,BM,tP,rP,nc,oc,mY,Hd,Bd,zd,UM,iP,hY,aP,gY,sP,lP,yY,SY]),mc=x.discriminatedUnion("type",[...cP.options,...AY.options]).openapi({ref:"Command"}),ih=x.discriminatedUnion("type",[...cP.options,oP]),mTe=x.discriminatedUnion("type",[...rT.options,oP]);function Ui(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ht(),type:r};break;case"AUTH_LOAD":{e={id:ht(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ht(),type:r,goal:""};break;case"DIALOG":e={id:ht(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ht(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ht(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ht(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ht(),type:r,delay:1};break;case"BLUR":e={id:ht(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ht(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ht(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ht(),type:r,value:""};break;case"SELECT_OPTION":e={id:ht(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ht(),type:r,url:""};case"TAB":e={id:ht(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ht(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ht(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ht(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ht(),type:r,code:""};break;case"AI_ASSERTION":e={id:ht(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ht(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ht(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ht(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ht(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ht(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ht(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ht(),type:r,key:""};break}case"SET_HEADER":{e={id:ht(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ht(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ht(),type:r};break}case"OFFLINE_MODE":{e={id:ht(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}var gTe={AI_ASSERTION:"AI check",ELEMENT_CHECK:"Element check",JAVASCRIPT:"JavaScript",PAGE_CHECK:"Page check"};import{z as wY}from"zod";var TTe=wY.discriminatedUnion("type",[zd,eT,ic,ac,Bd,lc,sc,_s,Ms,nc,oc,cc,dc,Hd,uc]);import{z as CY}from"zod";import{z as on}from"zod";function pc(r){return on.object({key:on.string(),testId:on.string().optional(),environment:on.string().optional(),moduleId:on.string().optional(),organizationId:on.string(),value:r})}function Os(r){return on.object({key:on.string(),testId:on.string().optional(),environment:on.string().optional(),moduleId:on.string().optional(),organizationId:on.string(),value:r,uniqueKey:on.string()})}function uP(r){return on.record(on.string(),Os(r))}var an={type:!0,cache:!0},fc=CY.discriminatedUnion("type",[$d.pick(an),zd.pick(an),ic.pick(an),ac.pick(an),uc.pick(an),Bd.pick(an),lc.pick(an),sc.pick(an),_s.pick(an),Ms.pick(an),nc.pick(an),oc.pick(an),cc.pick(an),dc.pick(an),Hd.pick(an)]),nT=Object.values(Lt).filter(r=>fc.options.some(e=>e.shape.type.safeParse(r).success));mc.options.forEach(r=>{if("target"in r.shape&&!nT.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function ah(r){return nT.includes(r.type)}var dP=pc(fc),mP=Os(fc),MTe=uP(fc);import{v4 as Iwe}from"uuid";import{z as N}from"zod";var fP=Symbol("Let zodToJsonSchema decide on which parser to use");var pP={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},hP=r=>typeof r=="string"?{...pP,name:r}:{...pP,...r};var gP=r=>{let e=hP(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function oT(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function Je(r,e,t,n,o){r[e]=t,oT(r,e,n,o)}var sh=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as qe}from"zod";function Bt(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?sh(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as RY}from"zod";function yP(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==RY.ZodAny&&(t.items=Te(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&Je(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&Je(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(Je(t,"minItems",r.exactLength.value,r.exactLength.message,e),Je(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function SP(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Je(t,"minimum",n.value,n.message,e):Je(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),Je(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Je(t,"maximum",n.value,n.message,e):Je(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),Je(t,"maximum",n.value,n.message,e));break;case"multipleOf":Je(t,"multipleOf",n.value,n.message,e);break}return t}function bP(){return{type:"boolean"}}function lh(r,e){return Te(r.type._def,e)}var EP=(r,e)=>Te(r.innerType._def,e);function iT(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>iT(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xY(r,e)}}var xY=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":Je(t,"minimum",n.value,n.message,e);break;case"max":Je(t,"maximum",n.value,n.message,e);break}return t};function TP(r,e){return{...Te(r.innerType._def,e),default:r.defaultValue()}}function vP(r,e){return e.effectStrategy==="input"?Te(r.schema._def,e):Bt(e)}function AP(r){return{type:"string",enum:Array.from(r.values)}}var _Y=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function wP(r,e){let t=[Te(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Te(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(_Y(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...l}=i;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function CP(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as jd}from"zod";var aT,No={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(aT===void 0&&(aT=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),aT),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ch(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":Je(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":Je(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Lo(t,"email",n.message,e);break;case"format:idn-email":Lo(t,"idn-email",n.message,e);break;case"pattern:zod":sn(t,No.email,n.message,e);break}break;case"url":Lo(t,"uri",n.message,e);break;case"uuid":Lo(t,"uuid",n.message,e);break;case"regex":sn(t,n.regex,n.message,e);break;case"cuid":sn(t,No.cuid,n.message,e);break;case"cuid2":sn(t,No.cuid2,n.message,e);break;case"startsWith":sn(t,RegExp(`^${sT(n.value,e)}`),n.message,e);break;case"endsWith":sn(t,RegExp(`${sT(n.value,e)}$`),n.message,e);break;case"datetime":Lo(t,"date-time",n.message,e);break;case"date":Lo(t,"date",n.message,e);break;case"time":Lo(t,"time",n.message,e);break;case"duration":Lo(t,"duration",n.message,e);break;case"length":Je(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),Je(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{sn(t,RegExp(sT(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Lo(t,"ipv4",n.message,e),n.version!=="v4"&&Lo(t,"ipv6",n.message,e);break}case"base64url":sn(t,No.base64url,n.message,e);break;case"jwt":sn(t,No.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&sn(t,No.ipv4Cidr,n.message,e),n.version!=="v4"&&sn(t,No.ipv6Cidr,n.message,e);break}case"emoji":sn(t,No.emoji(),n.message,e);break;case"ulid":{sn(t,No.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Lo(t,"binary",n.message,e);break}case"contentEncoding:base64":{Je(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{sn(t,No.base64,n.message,e);break}}break}case"nanoid":sn(t,No.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function sT(r,e){return e.patternStrategy==="escape"?PY(r):r}var MY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function PY(r){let e="";for(let t=0;t<r.length;t++)MY.has(r[t])||(e+="\\"),e+=r[t];return e}function Lo(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):Je(r,"format",e,t,n)}function sn(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:RP(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):Je(r,"pattern",RP(e,n),t,n)}function RP(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let l=0;l<n.length;l++){if(i){o+=n[l],i=!1;continue}if(t.i){if(a){if(n[l].match(/[a-z]/)){s?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),s=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],s=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(t.m){if(n[l]==="^"){o+=`(^|(?<=[\r
11
+ deps: ${t}}`};var Xge={keyword:"dependencies",type:"object",schemaType:"object",error:Ni.error,code(r){let[e,t]=Jge(r);jq(r,e),Gq(r,t)}};function Jge({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let o=Array.isArray(r[n])?e:t;o[n]=r[n]}return[e,t]}function jq(r,e=r.schema){let{gen:t,data:n,it:o}=r;if(Object.keys(e).length===0)return;let i=t.let("missing");for(let a in e){let s=e[a];if(s.length===0)continue;let l=(0,Bf.propertyInData)(t,n,a,o.opts.ownProperties);r.setParams({property:a,depsCount:s.length,deps:s.join(", ")}),o.allErrors?t.if(l,()=>{for(let c of s)(0,Bf.checkReportMissingProp)(r,c)}):(t.if((0,S_._)`${l} && (${(0,Bf.checkMissingProp)(r,s,i)})`),(0,Bf.reportMissingProp)(r,i),t.else())}}Ni.validatePropertyDeps=jq;function Gq(r,e=r.schema){let{gen:t,data:n,keyword:o,it:i}=r,a=t.name("valid");for(let s in e)(0,Yge.alwaysValidSchema)(i,e[s])||(t.if((0,Bf.propertyInData)(t,n,s,i.opts.ownProperties),()=>{let l=r.subschema({keyword:o,schemaProp:s},a);r.mergeValidEvaluated(l,a)},()=>t.var(a,!0)),r.ok(a))}Ni.validateSchemaDeps=Gq;Ni.default=Xge});var qq=Q(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var Vq=Be(),Zge=lt(),Qge={message:"property name must be valid",params:({params:r})=>(0,Vq._)`{propertyName: ${r.propertyName}}`},eye={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qge,code(r){let{gen:e,schema:t,data:n,it:o}=r;if((0,Zge.alwaysValidSchema)(o,t))return;let i=e.name("valid");e.forIn("key",n,a=>{r.setParams({propertyName:a}),r.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},i),e.if((0,Vq.not)(i),()=>{r.error(!0),o.allErrors||e.break()})}),r.ok(i)}};b_.default=eye});var T_=Q(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var SE=xo(),Xo=Be(),tye=da(),bE=lt(),rye={message:"must NOT have additional properties",params:({params:r})=>(0,Xo._)`{additionalProperty: ${r.additionalProperty}}`},nye={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rye,code(r){let{gen:e,schema:t,parentSchema:n,data:o,errsCount:i,it:a}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:s,opts:l}=a;if(a.props=!0,l.removeAdditional!=="all"&&(0,bE.alwaysValidSchema)(a,t))return;let c=(0,SE.allSchemaProperties)(n.properties),u=(0,SE.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Xo._)`${i} === ${tye.default.errors}`);function d(){e.forIn("key",o,g=>{!c.length&&!u.length?f(g):e.if(m(g),()=>f(g))})}function m(g){let y;if(c.length>8){let b=(0,bE.schemaRefOrVal)(a,n.properties,"properties");y=(0,SE.isOwnProperty)(e,b,g)}else c.length?y=(0,Xo.or)(...c.map(b=>(0,Xo._)`${g} === ${b}`)):y=Xo.nil;return u.length&&(y=(0,Xo.or)(y,...u.map(b=>(0,Xo._)`${(0,SE.usePattern)(r,b)}.test(${g})`))),(0,Xo.not)(y)}function p(g){e.code((0,Xo._)`delete ${o}[${g}]`)}function f(g){if(l.removeAdditional==="all"||l.removeAdditional&&t===!1){p(g);return}if(t===!1){r.setParams({additionalProperty:g}),r.error(),s||e.break();return}if(typeof t=="object"&&!(0,bE.alwaysValidSchema)(a,t)){let y=e.name("valid");l.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Xo.not)(y),()=>{r.reset(),p(g)})):(h(g,y),s||e.if((0,Xo.not)(y),()=>e.break()))}}function h(g,y,b){let E={keyword:"additionalProperties",dataProp:g,dataPropType:bE.Type.Str};b===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(E,y)}}};E_.default=nye});var Xq=Q(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var oye=Cf(),Kq=xo(),v_=lt(),Yq=T_(),iye={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:o,it:i}=r;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Yq.default.code(new oye.KeywordCxt(i,Yq.default,"additionalProperties"));let a=(0,Kq.allSchemaProperties)(t);for(let d of a)i.definedProperties.add(d);i.opts.unevaluated&&a.length&&i.props!==!0&&(i.props=v_.mergeEvaluated.props(e,(0,v_.toHash)(a),i.props));let s=a.filter(d=>!(0,v_.alwaysValidSchema)(i,t[d]));if(s.length===0)return;let l=e.name("valid");for(let d of s)c(d)?u(d):(e.if((0,Kq.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(l,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(l);function c(d){return i.opts.useDefaults&&!i.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};A_.default=iye});var e2=Q(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var Jq=xo(),EE=Be(),Zq=lt(),Qq=lt(),aye={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:o,it:i}=r,{opts:a}=i,s=(0,Jq.allSchemaProperties)(t),l=s.filter(h=>(0,Zq.alwaysValidSchema)(i,t[h]));if(s.length===0||l.length===s.length&&(!i.opts.unevaluated||i.props===!0))return;let c=a.strictSchema&&!a.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof EE.Name)&&(i.props=(0,Qq.evaluatedPropsToName)(e,i.props));let{props:d}=i;m();function m(){for(let h of s)c&&p(h),i.allErrors?f(h):(e.var(u,!0),f(h),e.if(u))}function p(h){for(let g in c)new RegExp(h).test(g)&&(0,Zq.checkStrictMode)(i,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,g=>{e.if((0,EE._)`${(0,Jq.usePattern)(r,h)}.test(${g})`,()=>{let y=l.includes(h);y||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Qq.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,EE._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,EE.not)(u),()=>e.break())})})}}};w_.default=aye});var t2=Q(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var sye=lt(),lye={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,sye.alwaysValidSchema)(n,t)){r.fail();return}let o=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),r.failResult(o,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};C_.default=lye});var r2=Q(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});var cye=xo(),uye={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:cye.validateUnion,error:{message:"must match a schema in anyOf"}};R_.default=uye});var n2=Q(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});var TE=Be(),dye=lt(),mye={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,TE._)`{passingSchemas: ${r.passing}}`},pye={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mye,code(r){let{gen:e,schema:t,parentSchema:n,it:o}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=t,a=e.let("valid",!1),s=e.let("passing",null),l=e.name("_valid");r.setParams({passing:s}),e.block(c),r.result(a,()=>r.reset(),()=>r.error(!0));function c(){i.forEach((u,d)=>{let m;(0,dye.alwaysValidSchema)(o,u)?e.var(l,!0):m=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,TE._)`${l} && ${a}`).assign(a,!1).assign(s,(0,TE._)`[${s}, ${d}]`).else(),e.if(l,()=>{e.assign(a,!0),e.assign(s,d),m&&r.mergeEvaluated(m,TE.Name)})})}}};x_.default=pye});var o2=Q(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});var fye=lt(),hye={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let o=e.name("valid");t.forEach((i,a)=>{if((0,fye.alwaysValidSchema)(n,i))return;let s=r.subschema({keyword:"allOf",schemaProp:a},o);r.ok(o),r.mergeEvaluated(s)})}};__.default=hye});var s2=Q(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var vE=Be(),a2=lt(),gye={message:({params:r})=>(0,vE.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,vE._)`{failingKeyword: ${r.ifClause}}`},yye={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gye,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,a2.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=i2(n,"then"),i=i2(n,"else");if(!o&&!i)return;let a=e.let("valid",!0),s=e.name("_valid");if(l(),r.reset(),o&&i){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(s,c("then",u),c("else",u))}else o?e.if(s,c("then")):e.if((0,vE.not)(s),c("else"));r.pass(a,()=>r.error(!0));function l(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);r.mergeEvaluated(u)}function c(u,d){return()=>{let m=r.subschema({keyword:u},s);e.assign(a,s),r.mergeValidEvaluated(m,a),d?e.assign(d,(0,vE._)`${u}`):r.setParams({ifClause:u})}}}};function i2(r,e){let t=r.schema[e];return t!==void 0&&!(0,a2.alwaysValidSchema)(r,t)}M_.default=yye});var l2=Q(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var Sye=lt(),bye={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,Sye.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};P_.default=bye});var c2=Q(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var Eye=p_(),Tye=Bq(),vye=f_(),Aye=$q(),wye=Hq(),Cye=Wq(),Rye=qq(),xye=T_(),_ye=Xq(),Mye=e2(),Pye=t2(),Iye=r2(),Oye=n2(),Nye=o2(),Lye=s2(),Dye=l2();function kye(r=!1){let e=[Pye.default,Iye.default,Oye.default,Nye.default,Lye.default,Dye.default,Rye.default,xye.default,Cye.default,_ye.default,Mye.default];return r?e.push(Tye.default,Aye.default):e.push(Eye.default,vye.default),e.push(wye.default),e}I_.default=kye});var u2=Q(O_=>{"use strict";Object.defineProperty(O_,"__esModule",{value:!0});var cr=Be(),Fye={message:({schemaCode:r})=>(0,cr.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,cr._)`{format: ${r}}`},Uye={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Fye,code(r,e){let{gen:t,data:n,$data:o,schema:i,schemaCode:a,it:s}=r,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=s;if(!l.validateFormats)return;o?m():p();function m(){let f=t.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=t.const("fDef",(0,cr._)`${f}[${a}]`),g=t.let("fType"),y=t.let("format");t.if((0,cr._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(g,(0,cr._)`${h}.type || "string"`).assign(y,(0,cr._)`${h}.validate`),()=>t.assign(g,(0,cr._)`"string"`).assign(y,h)),r.fail$data((0,cr.or)(b(),E()));function b(){return l.strictSchema===!1?cr.nil:(0,cr._)`${a} && !${y}`}function E(){let v=u.$async?(0,cr._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,cr._)`${y}(${n})`,w=(0,cr._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${n}))`;return(0,cr._)`${y} && ${y} !== true && ${g} === ${e} && !${w}`}}function p(){let f=d.formats[i];if(!f){b();return}if(f===!0)return;let[h,g,y]=E(f);h===e&&r.pass(v());function b(){if(l.strictSchema===!1){d.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${i}" ignored in schema at path "${c}"`}}function E(w){let L=w instanceof RegExp?(0,cr.regexpCode)(w):l.code.formats?(0,cr._)`${l.code.formats}${(0,cr.getProperty)(i)}`:void 0,I=t.scopeValue("formats",{key:i,ref:w,code:L});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,cr._)`${I}.validate`]:["string",w,I]}function v(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,cr._)`await ${y}(${n})`}return typeof g=="function"?(0,cr._)`${y}(${n})`:(0,cr._)`${y}.test(${n})`}}}};O_.default=Uye});var d2=Q(N_=>{"use strict";Object.defineProperty(N_,"__esModule",{value:!0});var Bye=u2(),zye=[Bye.default];N_.default=zye});var m2=Q(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.contentVocabulary=vd.metadataVocabulary=void 0;vd.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];vd.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var f2=Q(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});var $ye=Tq(),Hye=Dq(),jye=c2(),Gye=d2(),p2=m2(),Wye=[$ye.default,Hye.default,(0,jye.default)(),Gye.default,p2.metadataVocabulary,p2.contentVocabulary];L_.default=Wye});var g2=Q(AE=>{"use strict";Object.defineProperty(AE,"__esModule",{value:!0});AE.DiscrError=void 0;var h2;(function(r){r.Tag="tag",r.Mapping="mapping"})(h2||(AE.DiscrError=h2={}))});var S2=Q(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var Ad=Be(),D_=g2(),y2=aE(),Vye=Rf(),qye=lt(),Kye={message:({params:{discrError:r,tagName:e}})=>r===D_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Ad._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},Yye={keyword:"discriminator",type:"object",schemaType:"object",error:Kye,code(r){let{gen:e,data:t,schema:n,parentSchema:o,it:i}=r,{oneOf:a}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),c=e.const("tag",(0,Ad._)`${t}${(0,Ad.getProperty)(s)}`);e.if((0,Ad._)`typeof ${c} == "string"`,()=>u(),()=>r.error(!1,{discrError:D_.DiscrError.Tag,tag:c,tagName:s})),r.ok(l);function u(){let p=m();e.if(!1);for(let f in p)e.elseIf((0,Ad._)`${c} === ${f}`),e.assign(l,d(p[f]));e.else(),r.error(!1,{discrError:D_.DiscrError.Mapping,tag:c,tagName:s}),e.endIf()}function d(p){let f=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},f);return r.mergeEvaluated(h,Ad.Name),f}function m(){var p;let f={},h=y(o),g=!0;for(let v=0;v<a.length;v++){let w=a[v];if(w?.$ref&&!(0,qye.schemaHasRulesButRef)(w,i.self.RULES)){let I=w.$ref;if(w=y2.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,I),w instanceof y2.SchemaEnv&&(w=w.schema),w===void 0)throw new Vye.default(i.opts.uriResolver,i.baseId,I)}let L=(p=w?.properties)===null||p===void 0?void 0:p[s];if(typeof L!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);g=g&&(h||y(w)),b(L,v)}if(!g)throw new Error(`discriminator: "${s}" must be required`);return f;function y({required:v}){return Array.isArray(v)&&v.includes(s)}function b(v,w){if(v.const)E(v.const,w);else if(v.enum)for(let L of v.enum)E(L,w);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function E(v,w){if(typeof v!="string"||v in f)throw new Error(`discriminator: "${s}" values must be unique strings`);f[v]=w}}}};k_.default=Yye});var b2=Q((xHt,Xye)=>{Xye.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var U_=Q((Ut,F_)=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.MissingRefError=Ut.ValidationError=Ut.CodeGen=Ut.Name=Ut.nil=Ut.stringify=Ut.str=Ut._=Ut.KeywordCxt=Ut.Ajv=void 0;var Jye=hq(),Zye=f2(),Qye=S2(),E2=b2(),eSe=["/properties"],wE="http://json-schema.org/draft-07/schema",wd=class extends Jye.default{_addVocabularies(){super._addVocabularies(),Zye.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Qye.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(E2,eSe):E2;this.addMetaSchema(e,wE,!1),this.refs["http://json-schema.org/schema"]=wE}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(wE)?wE:void 0)}};Ut.Ajv=wd;F_.exports=Ut=wd;F_.exports.Ajv=wd;Object.defineProperty(Ut,"__esModule",{value:!0});Ut.default=wd;var tSe=Cf();Object.defineProperty(Ut,"KeywordCxt",{enumerable:!0,get:function(){return tSe.KeywordCxt}});var Cd=Be();Object.defineProperty(Ut,"_",{enumerable:!0,get:function(){return Cd._}});Object.defineProperty(Ut,"str",{enumerable:!0,get:function(){return Cd.str}});Object.defineProperty(Ut,"stringify",{enumerable:!0,get:function(){return Cd.stringify}});Object.defineProperty(Ut,"nil",{enumerable:!0,get:function(){return Cd.nil}});Object.defineProperty(Ut,"Name",{enumerable:!0,get:function(){return Cd.Name}});Object.defineProperty(Ut,"CodeGen",{enumerable:!0,get:function(){return Cd.CodeGen}});var rSe=oE();Object.defineProperty(Ut,"ValidationError",{enumerable:!0,get:function(){return rSe.default}});var nSe=Rf();Object.defineProperty(Ut,"MissingRefError",{enumerable:!0,get:function(){return nSe.default}})});var _2=Q(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.formatNames=Di.fastFormats=Di.fullFormats=void 0;function Li(r,e){return{validate:r,compare:e}}Di.fullFormats={date:Li(w2,H_),time:Li(z_(!0),j_),"date-time":Li(T2(!0),R2),"iso-time":Li(z_(),C2),"iso-date-time":Li(T2(),x2),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:cSe,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:gSe,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:uSe,int32:{type:"number",validate:pSe},int64:{type:"number",validate:fSe},float:{type:"number",validate:A2},double:{type:"number",validate:A2},password:!0,binary:!0};Di.fastFormats={...Di.fullFormats,date:Li(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,H_),time:Li(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,j_),"date-time":Li(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,R2),"iso-time":Li(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,C2),"iso-date-time":Li(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,x2),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Di.formatNames=Object.keys(Di.fullFormats);function oSe(r){return r%4===0&&(r%100!==0||r%400===0)}var iSe=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aSe=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w2(r){let e=iSe.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&oSe(t)?29:aSe[n])}function H_(r,e){if(r&&e)return r>e?1:r<e?-1:0}var B_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function z_(r){return function(t){let n=B_.exec(t);if(!n)return!1;let o=+n[1],i=+n[2],a=+n[3],s=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||r&&!s)return!1;if(o<=23&&i<=59&&a<60)return!0;let d=i-u*l,m=o-c*l-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&a<61}}function j_(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function C2(r,e){if(!(r&&e))return;let t=B_.exec(r),n=B_.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r<e?-1:0}var $_=/t|\s/i;function T2(r){let e=z_(r);return function(n){let o=n.split($_);return o.length===2&&w2(o[0])&&e(o[1])}}function R2(r,e){if(!(r&&e))return;let t=new Date(r).valueOf(),n=new Date(e).valueOf();if(t&&n)return t-n}function x2(r,e){if(!(r&&e))return;let[t,n]=r.split($_),[o,i]=e.split($_),a=H_(t,o);if(a!==void 0)return a||j_(n,i)}var sSe=/\/|:/,lSe=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function cSe(r){return sSe.test(r)&&lSe.test(r)}var v2=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function uSe(r){return v2.lastIndex=0,v2.test(r)}var dSe=-(2**31),mSe=2**31-1;function pSe(r){return Number.isInteger(r)&&r<=mSe&&r>=dSe}function fSe(r){return Number.isInteger(r)}function A2(){return!0}var hSe=/[^\\]\\Z/;function gSe(r){if(hSe.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var M2=Q(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});Rd.formatLimitDefinition=void 0;var ySe=U_(),Jo=Be(),Es=Jo.operators,CE={formatMaximum:{okStr:"<=",ok:Es.LTE,fail:Es.GT},formatMinimum:{okStr:">=",ok:Es.GTE,fail:Es.LT},formatExclusiveMaximum:{okStr:"<",ok:Es.LT,fail:Es.GTE},formatExclusiveMinimum:{okStr:">",ok:Es.GT,fail:Es.LTE}},SSe={message:({keyword:r,schemaCode:e})=>(0,Jo.str)`should be ${CE[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Jo._)`{comparison: ${CE[r].okStr}, limit: ${e}}`};Rd.formatLimitDefinition={keyword:Object.keys(CE),type:"string",schemaType:"string",$data:!0,error:SSe,code(r){let{gen:e,data:t,schemaCode:n,keyword:o,it:i}=r,{opts:a,self:s}=i;if(!a.validateFormats)return;let l=new ySe.KeywordCxt(i,s.RULES.all.format.definition,"format");l.$data?c():u();function c(){let m=e.scopeValue("formats",{ref:s.formats,code:a.code.formats}),p=e.const("fmt",(0,Jo._)`${m}[${l.schemaCode}]`);r.fail$data((0,Jo.or)((0,Jo._)`typeof ${p} != "object"`,(0,Jo._)`${p} instanceof RegExp`,(0,Jo._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let m=l.schema,p=s.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:p,code:a.code.formats?(0,Jo._)`${a.code.formats}${(0,Jo.getProperty)(m)}`:void 0});r.fail$data(d(f))}function d(m){return(0,Jo._)`${m}.compare(${t}, ${n}) ${CE[o].fail} 0`}},dependencies:["format"]};var bSe=r=>(r.addKeyword(Rd.formatLimitDefinition),r);Rd.default=bSe});var N2=Q((zf,O2)=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var xd=_2(),ESe=M2(),G_=Be(),P2=new G_.Name("fullFormats"),TSe=new G_.Name("fastFormats"),W_=(r,e={keywords:!0})=>{if(Array.isArray(e))return I2(r,e,xd.fullFormats,P2),r;let[t,n]=e.mode==="fast"?[xd.fastFormats,TSe]:[xd.fullFormats,P2],o=e.formats||xd.formatNames;return I2(r,o,t,n),e.keywords&&(0,ESe.default)(r),r};W_.get=(r,e="full")=>{let n=(e==="fast"?xd.fastFormats:xd.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function I2(r,e,t,n){var o,i;(o=(i=r.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,G_._)`require("ajv-formats/dist/formats").${n}`);for(let a of e)r.addFormat(a,t[a])}O2.exports=zf=W_;Object.defineProperty(zf,"__esModule",{value:!0});zf.default=W_});var Z_=Q((jf,J_)=>{"use strict";(function(r,e){if(typeof jf=="object"&&typeof J_=="object")J_.exports=e();else if(typeof define=="function"&&define.amd)define([],e);else{var t=e();for(var n in t)(typeof jf=="object"?jf:r)[n]=t[n]}})(typeof self<"u"?self:jf,function(){return function(r){var e={};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=r,t.c=e,t.d=function(n,o,i){t.o(n,o)||Object.defineProperty(n,o,{enumerable:!0,get:i})},t.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,o){if(1&o&&(n=t(n)),8&o||4&o&&typeof n=="object"&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&o&&typeof n!="string")for(var a in n)t.d(i,a,function(s){return n[s]}.bind(null,a));return i},t.n=function(n){var o=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(o,"a",o),o},t.o=function(n,o){return Object.prototype.hasOwnProperty.call(n,o)},t.p="",t(t.s=0)}([function(r,e,t){"use strict";var n;t.r(e),function(y){y[y.Empty=0]="Empty",y[y.InsideToken=1]="InsideToken",y[y.InsideSingleQuotedToken=2]="InsideSingleQuotedToken",y[y.InsideDoubleQuotedToken=3]="InsideDoubleQuotedToken",y[y.AfterEscapeInsideToken=4]="AfterEscapeInsideToken",y[y.AfterEscapeInsideSingleQuotedToken=5]="AfterEscapeInsideSingleQuotedToken",y[y.AfterEscapeInsideDoubleQuotedToken=6]="AfterEscapeInsideDoubleQuotedToken"}(n||(n={}));var o=function(y){return[null,null]},i={onCharacter:o,onWhitespace:o,onDoubleQuote:o,onSingleQuote:o,onEscape:o},a=function(){return(a=Object.assign||function(y){for(var b,E=1,v=arguments.length;E<v;E++)for(var w in b=arguments[E])Object.prototype.hasOwnProperty.call(b,w)&&(y[w]=b[w]);return y}).apply(this,arguments)},s=a({},i,{stateHandle:n.AfterEscapeInsideDoubleQuotedToken,onCharacter:function(y){return["\\"+y,n.InsideDoubleQuotedToken]},onWhitespace:function(y){return["\\"+y,n.InsideDoubleQuotedToken]},onSingleQuote:function(y){return["\\"+y,n.InsideDoubleQuotedToken]},onDoubleQuote:function(y){return[y,n.InsideDoubleQuotedToken]},onEscape:function(y){return[y,n.InsideDoubleQuotedToken]}}),l=a({},i,{stateHandle:n.AfterEscapeInsideSingleQuotedToken,onCharacter:function(y){return["\\"+y,n.InsideSingleQuotedToken]},onWhitespace:function(y){return["\\"+y,n.InsideSingleQuotedToken]},onSingleQuote:function(y){return[y,n.InsideSingleQuotedToken]},onDoubleQuote:function(y){return["\\"+y,n.InsideSingleQuotedToken]},onEscape:function(y){return[y,n.InsideSingleQuotedToken]}}),c=a({},i,{stateHandle:n.AfterEscapeInsideToken,onCharacter:function(y){return[y,n.InsideToken]},onWhitespace:function(y){return[y,n.InsideToken]},onSingleQuote:function(y){return[y,n.InsideToken]},onDoubleQuote:function(y){return[y,n.InsideToken]},onEscape:function(y){return[y,n.InsideToken]}}),u=a({},i,{stateHandle:n.Empty,onCharacter:function(y){return[y,n.InsideToken]},onSingleQuote:function(){return[null,n.InsideSingleQuotedToken]},onDoubleQuote:function(){return[null,n.InsideDoubleQuotedToken]},onEscape:function(){return[null,n.AfterEscapeInsideToken]}}),d=a({},i,{stateHandle:n.InsideDoubleQuotedToken,onCharacter:function(y){return[y,null]},onWhitespace:function(y){return[y,null]},onSingleQuote:function(y){return[y,null]},onDoubleQuote:function(){return["",n.Empty]},onEscape:function(){return["",n.AfterEscapeInsideDoubleQuotedToken]}}),m=a({},i,{stateHandle:n.InsideSingleQuotedToken,onCharacter:function(y){return[y,null]},onWhitespace:function(y){return[y,null]},onSingleQuote:function(){return["",n.Empty]},onDoubleQuote:function(y){return[y,null]},onEscape:function(){return["",n.AfterEscapeInsideSingleQuotedToken]}}),p=[u,a({},i,{stateHandle:n.InsideToken,onCharacter:function(y){return[y,null]},onWhitespace:function(){return[null,n.Empty]},onSingleQuote:function(){return["",n.InsideSingleQuotedToken]},onDoubleQuote:function(){return["",n.InsideDoubleQuotedToken]},onEscape:function(){return["",n.AfterEscapeInsideToken]}}),m,d,c,l,s];function f(y){for(var b=0,E=p;b<E.length;b++){var v=E[b];if(v.stateHandle===y)return v}throw new Error("State with handle = "+y+" cannot be found")}var h=function(){function y(){this.currentState=f(n.Empty)}return y.prototype.handleCharacter=function(b){var E=this.performTransition(b),v=E[0],w=E[1];return w!==null&&(this.currentState=f(w)),v},y.prototype.performTransition=function(b){var E=this.currentState;switch(b){case" ":return E.onWhitespace(b);case"'":return E.onSingleQuote(b);case'"':return E.onDoubleQuote(b);case"\\":return E.onEscape(b);default:return E.onCharacter(b)}},y}();function g(y){for(var b=new h,E=[],v=0,w=0,L=y;w<L.length;w++){var I=L[w],A=b.handleCharacter(I);A!==null?E[v]=E[v]?E[v]+A:A:E[v]&&v++}return E}t.d(e,"default",function(){return g}),g.default=g}]).default})});import B$e,{multistream as $$e}from"pino";import j$e from"pino-pretty";import{z as JE}from"zod";var CEe=JE.object({input:JE.string(),agentConfigVersion:JE.string().optional()}),Zf="finish";import{z as gr}from"zod";var _Ee=gr.object({srcs:gr.array(gr.string()),urls:gr.array(gr.string()),desiredSrc:gr.string().optional(),desiredUrl:gr.string().optional()}),MM=gr.object({srcRegex:gr.string().optional(),urlRegex:gr.string().optional()}),PM=gr.object({x:gr.number(),y:gr.number(),correlation:gr.number()}),MEe=gr.object({searchImageBase64String:gr.string(),pageImageBase64String:gr.string(),id:gr.string().uuid(),timeoutMs:gr.number().max(1e4).min(0).optional()});import{z as U}from"zod";import*as W from"zod";import{extendZodWithOpenApi as k4}from"zod-openapi";import Id from"zod";var Od=Id.object({updatedAt:Id.coerce.date().optional()}),ec=Id.object({contentType:Id.enum(["image/jpeg","image/png"]),id:Id.string()});k4(W);var ei=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(ei||{}),F4=W.object({mPathSelectorTokens:W.string().array(),frameSrcRegex:W.string().optional(),frameUrlRegex:W.string().optional(),indices:W.number().array()}),Nd=W.object({result:W.number(),traceId:W.string()}).array(),Oo=W.object({type:W.literal("GCS_TRACES"),traces:Nd}),Tn=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(Tn||{}),IM=W.object({attributes:W.record(W.string(),W.string()).optional(),text:W.string().optional(),position:W.object({x1:W.number(),y1:W.number(),x2:W.number(),y2:W.number(),tolerance:W.nativeEnum(Tn)}).optional(),shape:W.object({width:W.number(),height:W.number(),tolerance:W.nativeEnum(Tn)}).optional(),boundingBox:W.object({x:W.number(),y:W.number(),width:W.number(),height:W.number()}).optional()}),U4=W.object({selectors:W.string().array(),requirements:IM.optional(),relativeAngleRadians:W.number().min(0).max(2*Math.PI).optional(),relativeDistance:W.number().optional()}),Fi=W.object({id:W.number().int(),dataMomenticId:W.number().int().optional(),selector:W.string().optional(),hybridSelector:W.object({textContent:W.string().nullish(),attributes:W.record(W.string(),W.string().optional()),tagName:W.string(),expandShadowRoot:W.boolean().optional(),classNames:W.string().array(),nthChild:W.number()}).array().optional(),generatedSelectors:W.string().array().optional(),requirements:IM.optional(),additionalElements:U4.array().optional(),role:W.string().optional(),name:W.string().optional(),numChildren:W.number().optional(),content:W.string().optional(),pathFromRoot:W.string().optional(),serializedHtml:W.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:W.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:W.string().url().optional().or(ec.optional()),boundingBox:W.object({x:W.number().optional(),y:W.number().optional(),width:W.number(),height:W.number()}).describe("css pixel bounding box").optional(),frameCache:F4.optional(),inputDescription:W.string().optional().describe("the description that generated this cache"),targetSource:W.nativeEnum(ei).optional(),targetUpdateTime:W.string().optional(),targetUpdateLoggerTags:W.record(W.string(),W.string()).optional(),cacheResolutionUpdateSource:W.string().optional(),cacheResolutionUpdateTime:W.string().optional(),cacheResolutionUpdateLoggerTags:W.record(W.string(),W.string()).optional(),memory:Oo.optional()}).openapi({ref:"ElementTargetCache"});function tc(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var B4=W.object({type:W.literal("description"),elementDescriptor:W.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),z4=W.object({x:W.number(),y:W.number()}),$4=W.object({type:W.literal("coordinates"),pixels:z4}).openapi({ref:"CoordinatesTarget"});function ha(r){return r.type==="description"}function ti(r){return r.type==="coordinates"}var zr=W.discriminatedUnion("type",[B4,$4]).openapi({ref:"ElementTarget"});function ZE(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function OM(r){return Oo.safeParse(r).success}import{v4 as ht}from"uuid";import*as x from"zod";import{extendZodWithOpenApi as Q4}from"zod-openapi";import{z as Ge}from"zod";import{extendZodWithOpenApi as H4}from"zod-openapi";import{z as Ld}from"zod";var Dd=Ld.object({result:Ld.boolean(),traceId:Ld.string()}).array(),Rs=Ld.object({type:Ld.literal("GCS_TRACES"),traces:Dd}),QE=Od.extend({memory:Rs.optional()});var rc=(v=>(v.MissingScript="missing-script",v.EvaluationError="evaluation-error",v.NoSelectors="no-selectors",v.NoSelectorsMatched="no-selectors-matched",v.NotEnoughSelectorsMatched="not-enough-selectors-matched",v.CandidateHasNoBoundingBox="candidate-has-no-bounding-box",v.AdditionalElementsDoNotExist="additional-elements-do-not-exist",v.BoundingBoxChanged="bounding-box-changed",v.FailedLdistCheck="failing-ldist",v.FailedTextRequirements="failed-text-requirements",v.FailedAttributeRequirements="failed-attribute-requirements",v.FailedBoundingBoxRequirements="failed-bounding-box-requirements",v.FailedPositionRequirements="failed-position-requirements",v.FailedShapeRequirements="failed-shape-requirements",v.NoWinnerFound="no-winner-found",v.AmbiguousWinner="ambiguous-winner",v.WeakWinner="weak-winner",v.SecondaryResolutionFailed="secondary-resolution-failed",v.CouldNotFindIframe="could-not-find-iframe",v.Unknown="unknown",v))(rc||{});H4(Ge);var NM=Ge.object({thoughts:Ge.string(),result:Ge.boolean(),relevantElements:Ge.array(Ge.number()).optional(),updatedMemory:Dd.optional()}),rn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(rn||{});var j4=Ge.object({type:Ge.literal("ELEMENT_NAME"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),value:Ge.string()}).openapi({ref:"ElementNameAssertion"}),G4=Ge.object({type:Ge.literal("ELEMENT_STYLE"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),property:Ge.string(),value:Ge.string()}).openapi({ref:"ElementStyleAssertion"}),W4=Ge.object({type:Ge.literal("ELEMENT_CONTENT"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),value:Ge.string()}).openapi({ref:"ElementContentAssertion"}),V4=Ge.object({type:Ge.literal("ELEMENT_ATTRIBUTE"),negated:Ge.boolean().optional(),operation:Ge.nativeEnum(rn),attr:Ge.string(),value:Ge.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Dn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Dn||{});var q4=Ge.object({type:Ge.literal("ELEMENT_EXISTENCE"),negated:Ge.boolean().optional(),condition:Ge.nativeEnum(Dn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Qf=Ge.discriminatedUnion("type",[W4,V4,q4,j4,G4]).openapi({ref:"ManualElementAssertion"});var K4=Ge.object({type:Ge.literal("CONTENT"),negated:Ge.boolean().optional(),value:Ge.string()}).openapi({ref:"PageContentAssertion"}),LM=Ge.discriminatedUnion("type",[K4]).openapi({ref:"ManualPageAssertion"});import nn from"zod";var kd=nn.discriminatedUnion("type",[nn.object({type:nn.literal("SUBSTRING"),url:nn.string()}),nn.object({type:nn.literal("GLOB"),glob:nn.string()}),nn.object({type:nn.literal("REGEX"),regex:nn.string()}),nn.object({type:nn.literal("DOMAIN"),domain:nn.string()})]),Fd=nn.object({urlMatcher:kd,method:nn.string().optional()});import{z as it}from"zod";var Y4=it.object({type:it.literal("json"),content:it.string().describe("The JSON content to send in the request body")}),X4=it.object({type:it.literal("form-urlencoded"),content:it.record(it.string(),it.string()).describe("The form fields to send in the request body")}),J4=it.discriminatedUnion("type",[Y4,X4]),Z4=["GET","POST","PUT","DELETE","PATCH"],Ud=it.enum(Z4),xs=it.object({url:it.string(),method:Ud,headers:it.record(it.string(),it.string()).optional(),params:it.record(it.string(),it.string()).optional(),body:J4.optional(),timeout:it.number().int().optional().describe("Max seconds to wait for the request to complete")}),DM=it.object({url:it.string(),headers:it.record(it.string(),it.string()).optional(),query:it.string(),variables:it.string().optional(),timeout:it.number().int().optional().describe("Max seconds to wait for the request to complete")}),eh=it.object({code:it.string(),fragment:it.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:it.union([it.literal("NODE"),it.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:it.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Lt=(ge=>(ge.AI_EXTRACT="AI_EXTRACT",ge.AI_ASSERTION="AI_ASSERTION",ge.AUTH_LOAD="AUTH_LOAD",ge.AUTH_SAVE="AUTH_SAVE",ge.BLUR="BLUR",ge.CAPTCHA="CAPTCHA",ge.CLICK="CLICK",ge.COOKIE="COOKIE",ge.COPY="COPY",ge.DIALOG="DIALOG",ge.DRAG="DRAG",ge.ELEMENT_CHECK="ELEMENT_CHECK",ge.FILE_UPLOAD="FILE_UPLOAD",ge.FOCUS="FOCUS",ge.GO_BACK="GO_BACK",ge.GO_FORWARD="GO_FORWARD",ge.HOVER="HOVER",ge.JAVASCRIPT="JAVASCRIPT",ge.LOCAL_STORAGE="LOCAL_STORAGE",ge.MOUSE_DRAG="MOUSE_DRAG",ge.NAVIGATE="NAVIGATE",ge.NEW_TAB="NEW_TAB",ge.PAGE_CHECK="PAGE_CHECK",ge.PASTE="PASTE",ge.PRESS="PRESS",ge.KEY_DOWN="KEY_DOWN",ge.KEY_UP="KEY_UP",ge.REFRESH="REFRESH",ge.REQUEST="REQUEST",ge.GRAPHQL_REQUEST="GRAPHQL_REQUEST",ge.SCROLL_DOWN="SCROLL_DOWN",ge.SCROLL_UP="SCROLL_UP",ge.SCROLL_LEFT="SCROLL_LEFT",ge.SCROLL_RIGHT="SCROLL_RIGHT",ge.SELECT_OPTION="SELECT_OPTION",ge.SWITCH_TAB="TAB",ge.TYPE="TYPE",ge.VISUAL_DIFF="VISUAL_DIFF",ge.WAIT="WAIT",ge.WAIT_FOR_URL="WAIT_FOR_URL",ge.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",ge.AWAIT_LISTENER="AWAIT_LISTENER",ge.RECORD_REQUESTS="RECORD_REQUESTS",ge.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",ge.SET_HEADER="SET_HEADER",ge.MOCK_ROUTE="MOCK_ROUTE",ge.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",ge.OFFLINE_MODE="OFFLINE_MODE",ge.SUCCESS="SUCCESS",ge))(Lt||{});Q4(x);var Se=x.object({thoughts:x.string().optional(),id:x.string().uuid().describe("unique identifier to this step, used for step cache")}),qn=x.object({useSelector:x.boolean().optional(),force:x.boolean().optional(),disableCache:x.boolean().optional().describe("disable element caching for this step"),iframeUrl:x.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Kn=Od.extend({target:Fi}).optional().openapi({ref:"SingleTargetCache"});function rh(r){return!!r&&Kn.safeParse(r).success}var nh=x.object({loadTimeout:x.number().int().max(60).optional().describe("Max seconds for the page to load")}),kM=Se.merge(nh).merge(x.object({type:x.literal("NAVIGATE"),url:x.string()})).openapi({ref:"NavigateCommand"}),oh=qn.merge(x.object({cache:Kn})),_s=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_UP"),deltaY:x.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Ms=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_DOWN"),deltaY:x.number().optional()}))).openapi({ref:"ScrollDownCommand"}),nc=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_LEFT"),deltaX:x.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),oc=Se.merge(oh.merge(x.object({target:zr.optional(),type:x.literal("SCROLL_RIGHT"),deltaX:x.number().optional()}))).openapi({ref:"ScrollRightCommand"}),uTe=x.discriminatedUnion("type",[_s,Ms,nc,oc]).openapi({ref:"AllScrollCommands"}),eY=Se.merge(x.object({type:x.literal("DIALOG"),action:x.union([x.literal("ACCEPT"),x.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),FM=Se.merge(x.object({type:x.literal("WAIT"),delay:x.number()})).openapi({ref:"WaitCommand"}),tY=x.object({caseInsensitive:x.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:x.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:x.number().int().optional().describe("Max seconds to wait for the URL to match")}),UM=Se.extend({type:x.literal("WAIT_FOR_URL"),matcher:kd}).merge(tY).openapi({ref:"WaitUrlCommand"}),BM=Se.merge(nh).merge(x.object({type:x.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),zM=Se.merge(x.object({type:x.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),$M=Se.merge(x.object({type:x.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),rY=Se.extend({type:x.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),nY=Se.extend({type:x.literal("AUTH_LOAD"),storageState:x.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),eT=Se.merge(qn).extend({type:x.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),HM=Se.extend({type:x.literal("COPY"),value:x.string()}).openapi({ref:"CopyCommand"}),jM=Se.extend({type:x.literal("PASTE")}).openapi({ref:"PasteCommand"}),GM=Se.merge(eh).extend({type:x.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),ic=Se.merge(qn).extend({type:x.literal("CLICK"),target:zr,doubleClick:x.boolean().optional(),rightClick:x.boolean().optional(),waitForDownload:x.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:x.number().optional(),downloadTimeoutMs:x.number().optional(),cache:Kn,relativePosition:x.object({x:x.number(),y:x.number()}).optional()}).openapi({ref:"ClickCommand"}),WM=Od.extend({fromTarget:Fi.optional(),toTarget:Fi.optional()}),ac=Se.merge(qn).merge(x.object({type:x.literal("DRAG"),fromTarget:zr,toTarget:zr,steps:x.number().optional(),hoverSeconds:x.number().optional().describe("Seconds to hover the object before dropping"),cache:WM.optional()})).openapi({ref:"DragCommand"}),sc=Se.merge(qn).merge(x.object({type:x.literal("MOUSE_DRAG"),target:zr.optional(),deltaX:x.string().describe("pixels to move horizontally, can be template"),deltaY:x.string().describe("pixels to move vertically, can be template"),steps:x.number().optional(),cache:Kn})).openapi({ref:"MouseDragCommand"}),lc=Se.merge(qn).merge(x.object({type:x.literal("HOVER"),target:zr,cache:Kn})).openapi({ref:"HoverCommand"}),Bd=Se.merge(qn).merge(x.object({type:x.literal("FOCUS"),target:zr,cache:Kn})).openapi({ref:"FocusCommand"}),zd=Se.merge(qn).extend({type:x.literal("BLUR"),target:zr.optional(),cache:Kn}).openapi({ref:"BlurCommand"}),oY=x.object({type:x.literal("URL"),url:x.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),iY=x.object({type:x.literal("USER_FILE"),name:x.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),aY=Se.extend({type:x.literal("FILE_UPLOAD"),fileSource:x.discriminatedUnion("type",[oY,iY]),filename:x.string().optional()}).openapi({ref:"FileUploadCommand"}),VM=x.discriminatedUnion("type",[x.object({type:x.literal("VALUE"),value:x.string()}),x.object({type:x.literal("LABEL"),label:x.string()}),x.object({type:x.literal("INDEX"),index:x.coerce.string()})]),cc=Se.merge(qn).extend({type:x.literal("SELECT_OPTION"),target:zr,cache:Kn,choice:VM.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),tT=x.union([x.literal("MULTIMODAL"),x.literal("VISION_ONLY")]),$d=Se.merge(x.object({type:x.literal("AI_ASSERTION"),assertion:x.string(),disableCache:x.boolean().optional(),iframeUrl:x.string().optional(),contextChoice:tT.optional(),timeout:x.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:QE.optional(),source:x.string().optional()})).openapi({ref:"AIAssertionCommand"}),ur=5,Ps=600,uc=Se.merge(qn).extend({type:x.literal("ELEMENT_CHECK"),target:zr,assertion:Qf,cache:Kn.or(QE).optional(),timeout:x.number().int().min(0).max(Ps).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),qM=Se.extend({type:x.literal("PAGE_CHECK"),assertion:LM,iframeUrl:x.string().optional().describe("url or url regex for the iframe"),timeout:x.number().int().min(0).max(Ps).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),KM=Se.merge(x.object({type:x.literal("AI_EXTRACT"),goal:x.string(),schema:x.string().optional(),envKey:x.string().optional(),disableCache:x.boolean().optional(),iframeUrl:x.string().optional()})).openapi({ref:"AIExtractCommand"}),sY=x.object({clearContent:x.boolean().optional(),forceClearContent:x.boolean().optional(),delay:x.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:x.boolean().optional(),pressEnter:x.boolean().optional(),relativePosition:x.object({x:x.number(),y:x.number()}).optional()}),YM=25,dc=Se.merge(qn).merge(sY).extend({type:x.literal("TYPE"),target:zr.optional(),value:x.string(),cache:Kn}).openapi({ref:"TypeCommand"}),XM=Se.merge(x.object({type:x.literal("PRESS"),value:x.string(),repeat:x.number().optional(),convertMeta:x.boolean().optional(),delayMs:x.number().optional()})).openapi({ref:"PressCommand"}),JM=Se.merge(x.object({type:x.literal("KEY_DOWN"),value:x.string(),convertMeta:x.boolean().optional()})).openapi({ref:"KeyDownCommand"}),ZM=Se.merge(x.object({type:x.literal("KEY_UP"),value:x.string(),convertMeta:x.boolean().optional()})).openapi({ref:"KeyUpCommand"}),lY=x.object({type:x.literal("SUBSTRING"),substring:x.string()}),cY=x.object({type:x.literal("REGEX"),pattern:x.string()}),uY=x.object({type:x.literal("INDEX"),index:x.coerce.string()}),dY=x.discriminatedUnion("type",[lY,cY,uY]),mY=Se.merge(nh).merge(x.object({type:x.literal("TAB"),action:dY})).openapi({ref:"TabCommand"}),QM=Se.merge(nh).merge(x.object({type:x.literal("NEW_TAB"),url:x.string()})).openapi({ref:"NewTabCommand"}),pY=Se.merge(x.object({type:x.literal("COOKIE"),value:x.string()})).openapi({ref:"CookieCommand"}),eP=Se.merge(x.object({type:x.literal("LOCAL_STORAGE"),key:x.string(),value:x.string()})).openapi({ref:"LocalStorageCommand"}),tP=Se.extend({type:x.literal("REQUEST")}).merge(xs).openapi({ref:"RequestCommand"}),Is=x.object({status:x.number().optional(),headers:x.record(x.string(),x.string()),json:x.unknown().optional(),text:x.string().optional(),cookies:x.record(x.string(),x.unknown()).array().optional(),request:x.object({url:x.string(),method:x.string(),headers:x.record(x.string(),x.string()),json:x.unknown().optional()})}),rP=Se.extend({type:x.literal("GRAPHQL_REQUEST")}).merge(DM).openapi({ref:"GraphQLRequestCommand"}),nP=Se.merge(x.object({type:x.literal("SUCCESS"),condition:$d.optional()})).openapi({ref:"SuccessCommand"}),oP=Se.merge(x.object({type:x.literal("FAILURE")})).openapi({ref:"FailureCommand"}),fY=x.object({data:x.union([x.string().describe("location at which to find a jpg - public URL or local"),ec]),width:x.number(),height:x.number()});var Hd=Se.merge(qn).merge(x.object({type:x.literal("VISUAL_DIFF"),threshold:x.number().optional().describe("default 0.1"),target:zr.optional(),screenshot:fY.optional(),cache:Kn})).openapi({ref:"VisualDiffCommand"}),iP=Se.merge(x.object({type:x.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Fd,key:x.string()})).openapi({ref:"RegisterRequestListenerCommand"}),hY=Se.merge(x.object({type:x.literal("AWAIT_LISTENER"),key:x.string(),timeout:x.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),aP=Se.merge(x.object({type:x.literal("RECORD_REQUESTS"),requestMatcher:Fd,key:x.string()})).openapi({ref:"RecordRequestsCommand"}),gY=Se.merge(x.object({type:x.literal("GET_RECORDED_REQUESTS"),key:x.string()})).openapi({ref:"GetRecordedRequestsCommand"}),sP=Se.merge(x.object({type:x.literal("SET_HEADER"),name:x.string(),value:x.string(),requestMatcher:Fd.optional()})).openapi({ref:"SetHeaderCommand"}),lP=Se.merge(x.object({type:x.literal("MOCK_ROUTE"),requestMatcher:Fd,responseGenerator:x.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:x.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:x.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),yY=Se.merge(x.object({type:x.literal("REMOVE_ROUTE_MOCK"),key:x.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),SY=Se.merge(x.object({type:x.literal("OFFLINE_MODE"),enable:x.boolean()})).openapi({ref:"OfflineModeCommand"}),bY=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],dTe=[...bY,"DRAG"],EY=x.discriminatedUnion("type",[ic,dc,XM,JM,ZM,cc,kM,Ms,_s,$d,zM,lc,FM]),TY=x.discriminatedUnion("type",[...EY.options,ac]),vY=x.discriminatedUnion("type",[...TY.options]),cP=x.discriminatedUnion("type",[...vY.options,nP]),rT=x.discriminatedUnion("type",[nP,ic,dc,XM,JM,ZM,cc,kM,Ms,_s,$d,zM,lc,FM,GM,uc,qM,QM,UM,KM,HM,$M,eP,ac,sc,jM,BM,tP,rP,sP,iP,aP,lP]),AY=x.discriminatedUnion("type",[KM,nY,rY,eT,pY,HM,eY,uc,aY,$M,GM,eP,sc,QM,qM,jM,BM,tP,rP,nc,oc,mY,Hd,Bd,zd,UM,iP,hY,aP,gY,sP,lP,yY,SY]),mc=x.discriminatedUnion("type",[...cP.options,...AY.options]).openapi({ref:"Command"}),ih=x.discriminatedUnion("type",[...cP.options,oP]),mTe=x.discriminatedUnion("type",[...rT.options,oP]);function Ui(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ht(),type:r};break;case"AUTH_LOAD":{e={id:ht(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ht(),type:r,goal:""};break;case"DIALOG":e={id:ht(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ht(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ht(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ht(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ht(),type:r,delay:1};break;case"BLUR":e={id:ht(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ht(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ht(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ht(),type:r,value:""};break;case"SELECT_OPTION":e={id:ht(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ht(),type:r,url:""};case"TAB":e={id:ht(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ht(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ht(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ht(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ht(),type:r,code:""};break;case"AI_ASSERTION":e={id:ht(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ht(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ht(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ht(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ht(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ht(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ht(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ht(),type:r,key:""};break}case"SET_HEADER":{e={id:ht(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ht(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ht(),type:r};break}case"OFFLINE_MODE":{e={id:ht(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}var gTe={AI_ASSERTION:"AI check",ELEMENT_CHECK:"Element check",JAVASCRIPT:"JavaScript",PAGE_CHECK:"Page check"};import{z as wY}from"zod";var TTe=wY.discriminatedUnion("type",[zd,eT,ic,ac,Bd,lc,sc,_s,Ms,nc,oc,cc,dc,Hd,uc]);import{z as CY}from"zod";import{z as on}from"zod";function pc(r){return on.object({key:on.string(),testId:on.string().optional(),environment:on.string().optional(),moduleId:on.string().optional(),organizationId:on.string(),value:r})}function Os(r){return on.object({key:on.string(),testId:on.string().optional(),environment:on.string().optional(),moduleId:on.string().optional(),organizationId:on.string(),value:r,uniqueKey:on.string()})}function uP(r){return on.record(on.string(),Os(r))}var an={type:!0,cache:!0},fc=CY.discriminatedUnion("type",[$d.pick(an),zd.pick(an),ic.pick(an),ac.pick(an),uc.pick(an),Bd.pick(an),lc.pick(an),sc.pick(an),_s.pick(an),Ms.pick(an),nc.pick(an),oc.pick(an),cc.pick(an),dc.pick(an),Hd.pick(an)]),nT=Object.values(Lt).filter(r=>fc.options.some(e=>e.shape.type.safeParse(r).success));mc.options.forEach(r=>{if("target"in r.shape&&!nT.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function ah(r){return nT.includes(r.type)}var dP=pc(fc),mP=Os(fc),MTe=uP(fc);import{v4 as Iwe}from"uuid";import{z as N}from"zod";var fP=Symbol("Let zodToJsonSchema decide on which parser to use");var pP={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},hP=r=>typeof r=="string"?{...pP,name:r}:{...pP,...r};var gP=r=>{let e=hP(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function oT(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function Je(r,e,t,n,o){r[e]=t,oT(r,e,n,o)}var sh=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as qe}from"zod";function Bt(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?sh(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as RY}from"zod";function yP(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==RY.ZodAny&&(t.items=Te(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&Je(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&Je(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(Je(t,"minItems",r.exactLength.value,r.exactLength.message,e),Je(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function SP(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Je(t,"minimum",n.value,n.message,e):Je(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),Je(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Je(t,"maximum",n.value,n.message,e):Je(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),Je(t,"maximum",n.value,n.message,e));break;case"multipleOf":Je(t,"multipleOf",n.value,n.message,e);break}return t}function bP(){return{type:"boolean"}}function lh(r,e){return Te(r.type._def,e)}var EP=(r,e)=>Te(r.innerType._def,e);function iT(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>iT(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xY(r,e)}}var xY=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":Je(t,"minimum",n.value,n.message,e);break;case"max":Je(t,"maximum",n.value,n.message,e);break}return t};function TP(r,e){return{...Te(r.innerType._def,e),default:r.defaultValue()}}function vP(r,e){return e.effectStrategy==="input"?Te(r.schema._def,e):Bt(e)}function AP(r){return{type:"string",enum:Array.from(r.values)}}var _Y=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function wP(r,e){let t=[Te(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Te(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(_Y(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...l}=i;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function CP(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as jd}from"zod";var aT,No={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(aT===void 0&&(aT=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),aT),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ch(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":Je(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":Je(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Lo(t,"email",n.message,e);break;case"format:idn-email":Lo(t,"idn-email",n.message,e);break;case"pattern:zod":sn(t,No.email,n.message,e);break}break;case"url":Lo(t,"uri",n.message,e);break;case"uuid":Lo(t,"uuid",n.message,e);break;case"regex":sn(t,n.regex,n.message,e);break;case"cuid":sn(t,No.cuid,n.message,e);break;case"cuid2":sn(t,No.cuid2,n.message,e);break;case"startsWith":sn(t,RegExp(`^${sT(n.value,e)}`),n.message,e);break;case"endsWith":sn(t,RegExp(`${sT(n.value,e)}$`),n.message,e);break;case"datetime":Lo(t,"date-time",n.message,e);break;case"date":Lo(t,"date",n.message,e);break;case"time":Lo(t,"time",n.message,e);break;case"duration":Lo(t,"duration",n.message,e);break;case"length":Je(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),Je(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{sn(t,RegExp(sT(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Lo(t,"ipv4",n.message,e),n.version!=="v4"&&Lo(t,"ipv6",n.message,e);break}case"base64url":sn(t,No.base64url,n.message,e);break;case"jwt":sn(t,No.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&sn(t,No.ipv4Cidr,n.message,e),n.version!=="v4"&&sn(t,No.ipv6Cidr,n.message,e);break}case"emoji":sn(t,No.emoji(),n.message,e);break;case"ulid":{sn(t,No.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Lo(t,"binary",n.message,e);break}case"contentEncoding:base64":{Je(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{sn(t,No.base64,n.message,e);break}}break}case"nanoid":sn(t,No.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function sT(r,e){return e.patternStrategy==="escape"?PY(r):r}var MY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function PY(r){let e="";for(let t=0;t<r.length;t++)MY.has(r[t])||(e+="\\"),e+=r[t];return e}function Lo(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):Je(r,"format",e,t,n)}function sn(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:RP(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):Je(r,"pattern",RP(e,n),t,n)}function RP(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let l=0;l<n.length;l++){if(i){o+=n[l],i=!1;continue}if(t.i){if(a){if(n[l].match(/[a-z]/)){s?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),s=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],s=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(t.m){if(n[l]==="^"){o+=`(^|(?<=[\r
12
12
  ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
13
13
  ]))`;continue}}if(t.s&&n[l]==="."){o+=a?`${n[l]}\r
14
14
  `:`[${n[l]}\r
@@ -31,11 +31,11 @@ ${this.decisions.map(e=>e.toString()).join(`
31
31
  To resolve the conflict:`,JA(c,e))),i=l):le.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
32
32
  `,`Details:
33
33
  `,XA(c,e),`To resolve the conflict:
34
- `,JA(c,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var lF=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();Rt();Rt();var cF=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Bo}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){le.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===zn.INT&&!Number.isInteger(e)&&(le.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var uF=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!pp(e)){var o=this._buffer.get(e);if(o==null&&(o=new Bo,this._buffer.set(e,o)),typeof t!="number"){le.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===zn.INT&&!Number.isInteger(t)&&(le.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var QA=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},ew=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},dF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mF=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},pF=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(pp));if(n.size===0){le.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(pp)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return QA(this,void 0,void 0,function(){var n,o,i,a;return ew(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,dk(mF(mF([],dF(n),!1),dF(o),!1))];case 1:return i=s.sent(),a=i.filter(mk).map(function(l){return l.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return QA(n,void 0,void 0,function(){var s,l;return ew(this,function(c){switch(c.label){case 0:return s=new cF(a._descriptor.name,a._descriptor.valueType),l=Promise.resolve(i(s)),t!=null&&(l=Ba(l,t)),[4,l];case 1:return c.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return QA(n,void 0,void 0,function(){var s,l;return ew(this,function(c){switch(c.label){case 0:return s=new uF,l=Promise.resolve(i(s)),t!=null&&(l=Ba(l,t)),[4,l];case 1:return c.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(m){m.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&pk(n.instruments,t)})},r}();var nQ=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),fF=function(r){nQ(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Kg(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Yg(n,i),s}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(qg);var hF=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),mu=function(){function r(){}return r.Noop=function(){return iQ},r}();var oQ=function(r){hF(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(mu);var gF=function(r){hF(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(mu);var iQ=new oQ;var aQ=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},sQ=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},lQ=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yF=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new sF,this.observableRegistry=new pF,this.meter=new nF(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,fF);return t.length===1?t[0]:new lF(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,aF);return t},r.prototype.collect=function(e,t,n){return aQ(this,void 0,void 0,function(){var o,i,a;return sQ(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(l){return l.collect(e,t)}).filter(ck),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(l){var c=gk(l,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(c);if(u!=null)return u;var d=l.aggregation.createAggregator(c),m=new t(c,d,l.attributesProcessor,n._meterProviderSharedState.metricCollectors,l.aggregationCardinalityLimit);return n.metricStorageRegistry.register(m),m});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(l){var c=lQ(l,2),u=c[0],d=c[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var p=d.createAggregator(e),f=u.selectCardinalityLimit(e.type),h=new t(e,p,mu.Noop(),[u],f);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var cQ=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},SF=function(){function r(e){this.resource=e,this.viewRegistry=new Yk,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=uk(e),n=this.meterSharedStates.get(t);return n==null&&(n=new yF(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=cQ(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(l){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var Xg=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},Jg=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},uQ=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dQ=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},bF=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Xg(this,void 0,void 0,function(){var t,n,o,i,a=this;return Jg(this,function(s){switch(s.label){case 0:return t=ll(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(l){return Xg(a,void 0,void 0,function(){var c;return Jg(this,function(u){switch(u.label){case 0:return[4,l.collect(this,t,e)];case 1:return c=u.sent(),c?.scopeMetrics!=null&&n.push(c.scopeMetrics),c?.errors!=null&&o.push.apply(o,dQ([],uQ(c.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Xg(this,void 0,void 0,function(){return Jg(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return Xg(this,void 0,void 0,function(){return Jg(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var EF=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},TF=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},vF=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function mQ(r,e){var t=e??Gg.empty();return r?Gg.default().merge(t):t}var tw=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new SF(mQ((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=vF(e.views),l=s.next();!l.done;l=s.next()){var c=l.value;this._sharedState.viewRegistry.addView(c)}}catch(p){t={error:p}}finally{try{l&&!l.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=vF(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(p){o={error:p}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(le.warn("A shutdown MeterProvider cannot provide a Meter"),aA()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new bF(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return EF(this,void 0,void 0,function(){return TF(this,function(t){switch(t.label){case 0:return this._shutdown?(le.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return EF(this,void 0,void 0,function(){return TF(this,function(t){switch(t.label){case 0:return this._shutdown?(le.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var pQ=/[\^$\\.+?()[\]{}|]/g,Zg=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(pQ,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var pu=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var AF=function(){function r(e){var t;this._nameFilter=new Zg((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new pu(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var wF=function(){function r(e){this._nameFilter=new pu(e?.name),this._versionFilter=new pu(e?.version),this._schemaUrlFilter=new pu(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function fQ(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Qg=function(){function r(e){var t;if(fQ(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Zg.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new gF(e.attributeKeys):this.attributesProcessor=mu.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:uo.Default(),this.instrumentSelector=new AF({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new wF({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var F4e=process.env.APP||"unknown";Rt();import{v4 as gQ}from"uuid";function yQ(){return new ak({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:al.DELTA})}var SQ=[new Qg({instrumentName:"test_event_duration",instrumentType:et.HISTOGRAM,aggregation:new mp([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)}),new Qg({instrumentName:"test_step_duration",instrumentType:et.HISTOGRAM,aggregation:new mp([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)})],ey=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new wA({[Sg]:e.serviceName,[rD]:t,[oD]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:gQ()}),o=yQ(),i=new KA({exporter:o,exportIntervalMillis:e.exportIntervalMs??6e4});this.provider=new tw({resource:n,readers:[i],views:SQ}),fg.setGlobalMeterProvider(this.provider),this.meter=fg.getMeter("momentic-serverless")}increment(e,t,n){try{let o=dg(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=dg(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var gt=new ug;function CF(r){r.disabled||(gt=new ey(r))}import{exec as bQ}from"child_process";import{platform as RF}from"os";var EQ=1e4;async function fp(r){return new Promise(e=>{bQ(r,{timeout:EQ},(t,n,o)=>{e({command:r,stdout:n,stderr:o,error:t?.message??null,timedOut:t?.killed??!1})})})}async function TQ(r){if(RF()==="win32")return fp(`tracert ${r}`);let t=await fp(`traceroute ${r}`);return t.stderr.includes("not found")||t.error?.includes("not found")?fp(`tracepath ${r}`):t}async function ty(r){let t=RF()==="win32",n=t?`ping -n 3 ${r}`:`ping -c 3 ${r}`,i=`curl -w "\\n\\ntime_namelookup: %{time_namelookup}s\\ntime_connect: %{time_connect}s\\ntime_appconnect: %{time_appconnect}s\\ntime_starttransfer: %{time_starttransfer}s\\ntime_total: %{time_total}s\\n" -o ${t?"NUL":"/dev/null"} -s ${r}`,[a,s,l]=await Promise.all([fp(n),TQ(r),fp(i)]);return{ping:a,traceroute:s,curl:l}}var rw=!1;try{let r=await import("@sentry/node");r.init({dsn:"https://67a6ef469598f8880478f33863d05873@o4506426201800704.ingest.us.sentry.io/4510914396291072",environment:"production",dist:"production",release:"mobile-cli-0.59.0",tracesSampleRate:0,sendDefaultPii:!0}),m0(r.captureException),rw=!0}catch{}import{Argument as Yf,Command as uEe,Option as qE}from"@commander-js/extra-typings";import{confirm as vQ,input as AQ}from"@inquirer/prompts";import{existsSync as LYe,mkdirSync as DYe,statSync as wQ}from"fs";var CQ=!1,xF=(()=>{try{return wQ("/.dockerenv"),!0}catch{return!1}})();async function ry(r){return tl||CQ||xF?!0:(await P.flush(),await new Promise(t=>setTimeout(t,100)),await vQ({message:r}))}async function _F(r,e){return tl||xF?e:(await AQ({message:r,default:e})).trim()||e}import hu,{supportsColor as xQ}from"chalk";import{Console as MF}from"console";import{format as hp}from"util";var nw=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},ny=class r extends MF{_buffer=[];_groupDepth=0;Console=MF;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new nw(void 0,r.write).stack;if(!i)return e;let a=i.split(`
34
+ `,JA(c,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var lF=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();Rt();Rt();var cF=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Bo}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){le.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===zn.INT&&!Number.isInteger(e)&&(le.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var uF=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!pp(e)){var o=this._buffer.get(e);if(o==null&&(o=new Bo,this._buffer.set(e,o)),typeof t!="number"){le.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===zn.INT&&!Number.isInteger(t)&&(le.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var QA=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},ew=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},dF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mF=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},pF=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(pp));if(n.size===0){le.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(pp)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return QA(this,void 0,void 0,function(){var n,o,i,a;return ew(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,dk(mF(mF([],dF(n),!1),dF(o),!1))];case 1:return i=s.sent(),a=i.filter(mk).map(function(l){return l.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return QA(n,void 0,void 0,function(){var s,l;return ew(this,function(c){switch(c.label){case 0:return s=new cF(a._descriptor.name,a._descriptor.valueType),l=Promise.resolve(i(s)),t!=null&&(l=Ba(l,t)),[4,l];case 1:return c.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return QA(n,void 0,void 0,function(){var s,l;return ew(this,function(c){switch(c.label){case 0:return s=new uF,l=Promise.resolve(i(s)),t!=null&&(l=Ba(l,t)),[4,l];case 1:return c.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(m){m.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&pk(n.instruments,t)})},r}();var nQ=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),fF=function(r){nQ(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Kg(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Yg(n,i),s}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(qg);var hF=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),mu=function(){function r(){}return r.Noop=function(){return iQ},r}();var oQ=function(r){hF(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(mu);var gF=function(r){hF(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(mu);var iQ=new oQ;var aQ=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},sQ=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},lQ=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yF=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new sF,this.observableRegistry=new pF,this.meter=new nF(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,fF);return t.length===1?t[0]:new lF(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,aF);return t},r.prototype.collect=function(e,t,n){return aQ(this,void 0,void 0,function(){var o,i,a;return sQ(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(l){return l.collect(e,t)}).filter(ck),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(l){var c=gk(l,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(c);if(u!=null)return u;var d=l.aggregation.createAggregator(c),m=new t(c,d,l.attributesProcessor,n._meterProviderSharedState.metricCollectors,l.aggregationCardinalityLimit);return n.metricStorageRegistry.register(m),m});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(l){var c=lQ(l,2),u=c[0],d=c[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var p=d.createAggregator(e),f=u.selectCardinalityLimit(e.type),h=new t(e,p,mu.Noop(),[u],f);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var cQ=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},SF=function(){function r(e){this.resource=e,this.viewRegistry=new Yk,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=uk(e),n=this.meterSharedStates.get(t);return n==null&&(n=new yF(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=cQ(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(l){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var Xg=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},Jg=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},uQ=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dQ=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},bF=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Xg(this,void 0,void 0,function(){var t,n,o,i,a=this;return Jg(this,function(s){switch(s.label){case 0:return t=ll(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(l){return Xg(a,void 0,void 0,function(){var c;return Jg(this,function(u){switch(u.label){case 0:return[4,l.collect(this,t,e)];case 1:return c=u.sent(),c?.scopeMetrics!=null&&n.push(c.scopeMetrics),c?.errors!=null&&o.push.apply(o,dQ([],uQ(c.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Xg(this,void 0,void 0,function(){return Jg(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return Xg(this,void 0,void 0,function(){return Jg(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var EF=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{c(n.next(u))}catch(d){a(d)}}function l(u){try{c(n.throw(u))}catch(d){a(d)}}function c(u){u.done?i(u.value):o(u.value).then(s,l)}c((n=n.apply(r,e||[])).next())})},TF=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t)}catch(u){c=[6,u],o=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},vF=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function mQ(r,e){var t=e??Gg.empty();return r?Gg.default().merge(t):t}var tw=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new SF(mQ((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=vF(e.views),l=s.next();!l.done;l=s.next()){var c=l.value;this._sharedState.viewRegistry.addView(c)}}catch(p){t={error:p}}finally{try{l&&!l.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=vF(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(p){o={error:p}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(le.warn("A shutdown MeterProvider cannot provide a Meter"),aA()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new bF(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return EF(this,void 0,void 0,function(){return TF(this,function(t){switch(t.label){case 0:return this._shutdown?(le.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return EF(this,void 0,void 0,function(){return TF(this,function(t){switch(t.label){case 0:return this._shutdown?(le.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var pQ=/[\^$\\.+?()[\]{}|]/g,Zg=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(pQ,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var pu=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var AF=function(){function r(e){var t;this._nameFilter=new Zg((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new pu(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var wF=function(){function r(e){this._nameFilter=new pu(e?.name),this._versionFilter=new pu(e?.version),this._schemaUrlFilter=new pu(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function fQ(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Qg=function(){function r(e){var t;if(fQ(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Zg.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new gF(e.attributeKeys):this.attributesProcessor=mu.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:uo.Default(),this.instrumentSelector=new AF({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new wF({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var F4e=process.env.APP||"unknown";Rt();import{v4 as gQ}from"uuid";function yQ(){return new ak({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:al.DELTA})}var SQ=[new Qg({instrumentName:"test_event_duration",instrumentType:et.HISTOGRAM,aggregation:new mp([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)}),new Qg({instrumentName:"test_step_duration",instrumentType:et.HISTOGRAM,aggregation:new mp([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)})],ey=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new wA({[Sg]:e.serviceName,[rD]:t,[oD]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:gQ()}),o=yQ(),i=new KA({exporter:o,exportIntervalMillis:e.exportIntervalMs??6e4});this.provider=new tw({resource:n,readers:[i],views:SQ}),fg.setGlobalMeterProvider(this.provider),this.meter=fg.getMeter("momentic-serverless")}increment(e,t,n){try{let o=dg(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=dg(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var gt=new ug;function CF(r){r.disabled||(gt=new ey(r))}import{exec as bQ}from"child_process";import{platform as RF}from"os";var EQ=1e4;async function fp(r){return new Promise(e=>{bQ(r,{timeout:EQ},(t,n,o)=>{e({command:r,stdout:n,stderr:o,error:t?.message??null,timedOut:t?.killed??!1})})})}async function TQ(r){if(RF()==="win32")return fp(`tracert ${r}`);let t=await fp(`traceroute ${r}`);return t.stderr.includes("not found")||t.error?.includes("not found")?fp(`tracepath ${r}`):t}async function ty(r){let t=RF()==="win32",n=t?`ping -n 3 ${r}`:`ping -c 3 ${r}`,i=`curl -w "\\n\\ntime_namelookup: %{time_namelookup}s\\ntime_connect: %{time_connect}s\\ntime_appconnect: %{time_appconnect}s\\ntime_starttransfer: %{time_starttransfer}s\\ntime_total: %{time_total}s\\n" -o ${t?"NUL":"/dev/null"} -s ${r}`,[a,s,l]=await Promise.all([fp(n),TQ(r),fp(i)]);return{ping:a,traceroute:s,curl:l}}var rw=!1;try{let r=await import("@sentry/node");r.init({dsn:"https://67a6ef469598f8880478f33863d05873@o4506426201800704.ingest.us.sentry.io/4510914396291072",environment:"production",dist:"production",release:"mobile-cli-0.59.1",tracesSampleRate:0,sendDefaultPii:!0}),m0(r.captureException),rw=!0}catch{}import{Argument as Yf,Command as uEe,Option as qE}from"@commander-js/extra-typings";import{confirm as vQ,input as AQ}from"@inquirer/prompts";import{existsSync as LYe,mkdirSync as DYe,statSync as wQ}from"fs";var CQ=!1,xF=(()=>{try{return wQ("/.dockerenv"),!0}catch{return!1}})();async function ry(r){return tl||CQ||xF?!0:(await P.flush(),await new Promise(t=>setTimeout(t,100)),await vQ({message:r}))}async function _F(r,e){return tl||xF?e:(await AQ({message:r,default:e})).trim()||e}import hu,{supportsColor as xQ}from"chalk";import{Console as MF}from"console";import{format as hp}from"util";var nw=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},ny=class r extends MF{_buffer=[];_groupDepth=0;Console=MF;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new nw(void 0,r.write).stack;if(!i)return e;let a=i.split(`
35
35
  `).slice(o).filter(Boolean).join(`
36
36
  `);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",hp(e,...t))}error(e,...t){this._log("error",hp(e,...t))}info(e,...t){this._log("info",hp(e,...t))}log(e,...t){this._log("log",hp(e,...t))}warn(e,...t){this._log("warn",hp(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function PF(r){let e=globalThis.console,t=new ny;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
37
37
  `);process.stderr.write(`${o}
38
- `),globalThis.console=e}}var fu=" ".repeat(6);import{hostname as RQ}from"os";var br=Zc({app:"cli",hostname:RQ(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:"0.59.0"});function ow(r){if(!r)return;r=r.toLowerCase();let e=Zh.safeParse(r);if(e.success)return P.setMinLevel(e.data),e.data}function IF({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),l=r.filter(u=>u.status==="FAILED"&&!u.quarantined),c=r.filter(u=>u.status==="CANCELLED");return PF(()=>{if(l.forEach(u=>{P.log(""),o(u)}),l.length){P.log("");let u=l.length===1?"":"s";P.error(`${l.length} ${t}${u} failed:`),l.forEach(d=>{P.dimmed(n(d))})}if(c.length){P.log("");let u=c.length===1?"":"s";P.warn(`${c.length} ${t}${u} cancelled:`),c.forEach(d=>{P.dimmed(n(d))})}if(a.length){P.log("");let u=a.length===1?"":"s";P.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{P.dimmed(n(d))})}if(s.length){P.log("");let u=s.length===1?"":"s";P.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{P.dimmed(n(d))})}if(i.length){P.log("");let u=i.length===1?"":"s";P.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{P.dimmed(n(d))})}P.log(""),P.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:l.length,cancelled:c.length}}var gp=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=hu.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=hu.bgGreen.white("PASS"),a=3):r.includes("START")?(i=hu.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=hu.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=hu.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=hu.bgMagenta.white("RUNNING"),a=0):(P.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),xQ||(i=`${i}`),P.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import _Q from"fs";import{platform as MQ,tmpdir as PQ}from"os";import IQ from"path";import{program as OQ}from"playwright-core/lib/cli/program";import{registry as yp}from"playwright-core/lib/server";import OF from"proper-lockfile";var NF=IQ.join(PQ(),"momenticBrowserInstallation");var oy=["chrome","chromium","chrome-for-testing","ffmpeg"],wXe=[...oy.filter(r=>r!=="ffmpeg")],NQ={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"};var LF={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function DF(r){if(r==="Org Default")return!1;let e=LF[NQ[r]??""]??"",t=yp.findExecutable(e);return!t||t.installType==="none"?!1:iw(t)}function iw(r){let e=r.executablePath();return _Q.existsSync(e)}function LQ(r,e){let t=LF[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=yp.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&iw(n)))return n}async function DQ({browser:r,force:e}){let t=LQ(r,e);if(!t){P.info(`Browser '${r}' is already installed, skipping...`);return}P.info(`Installing browser '${r}'...`);try{await yp.installDeps([t],!1),await yp.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){P.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=yp.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!iw(o);)P.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function kQ(){if(MQ()==="win32"){P.info("Installing Windows dependencies for Playwright...");try{await OQ.parseAsync(["","","install","winldd"])}catch(r){P.warn(`Failed to install Windows dependencies: ${r}. Continuing with browser installation...`)}}}async function iy({rawBrowsers:r,force:e=!1,all:t=!1}){await kQ();let n=t?oy:Array.from(new Set(r));try{await OF.lock(NF,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){P.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await DQ({browser:i,force:e})}catch(a){o=a,P.error(`Failed to install the ${i} browser: ${a}`)}}finally{await OF.unlock(NF,{realpath:!1})}if(o)throw o}import{createServer as FQ}from"http";async function zo(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await ay(o))return o}P.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function ay(r){return new Promise((e,t)=>{let n=FQ();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(P.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import PXe from"blocked-at";import OXe from"why-is-node-running";function kF(r){let e=r?.shardIndex??1,t=r?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(t<1)throw new Error("Shard count must be greater than 0.");if(e>t)throw new Error("Shard index cannot be greater than shard count")}function UQ(r,e,t,n){if(t>r.length&&(P.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let o=Math.floor((e-1)*(r.length/t)),i=Math.floor(e*(r.length/t));return(n?[...r].sort((s,l)=>n(s).localeCompare(n(l))):[...r].sort()).filter((s,l)=>l>=o&&l<i)}function FF(r){let{items:e,shardIndex:t,shardCount:n,sortKey:o}=r;return n>1?UQ(e,t,n,o):e}function sy({regenerateCache:r,saveCache:e,disableCache:t}){if(t){if(r)throw new Error("--disable-cache and --regenerate-cache cannot be used together.");if(e)throw new Error("--disable-cache and --save-cache cannot be used together.")}}function UF(r,e,t){return r instanceof Ls?(r.zodIssues.forEach(n=>{t.push({file:e,stepIndex:typeof n.path[0]=="number"?n.path[0]:void 0,field:n.path.slice(1).join(".")||n.path.join("."),issue:n.message})}),!0):!1}function aw({parsingErrors:r,parsingErrorDetails:e,failedTestFilePaths:t,failedModuleFilePaths:n}){if(P.error(`
38
+ `),globalThis.console=e}}var fu=" ".repeat(6);import{hostname as RQ}from"os";var br=Zc({app:"cli",hostname:RQ(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:"0.59.1"});function ow(r){if(!r)return;r=r.toLowerCase();let e=Zh.safeParse(r);if(e.success)return P.setMinLevel(e.data),e.data}function IF({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),l=r.filter(u=>u.status==="FAILED"&&!u.quarantined),c=r.filter(u=>u.status==="CANCELLED");return PF(()=>{if(l.forEach(u=>{P.log(""),o(u)}),l.length){P.log("");let u=l.length===1?"":"s";P.error(`${l.length} ${t}${u} failed:`),l.forEach(d=>{P.dimmed(n(d))})}if(c.length){P.log("");let u=c.length===1?"":"s";P.warn(`${c.length} ${t}${u} cancelled:`),c.forEach(d=>{P.dimmed(n(d))})}if(a.length){P.log("");let u=a.length===1?"":"s";P.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{P.dimmed(n(d))})}if(s.length){P.log("");let u=s.length===1?"":"s";P.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{P.dimmed(n(d))})}if(i.length){P.log("");let u=i.length===1?"":"s";P.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{P.dimmed(n(d))})}P.log(""),P.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:l.length,cancelled:c.length}}var gp=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=hu.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=hu.bgGreen.white("PASS"),a=3):r.includes("START")?(i=hu.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=hu.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=hu.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=hu.bgMagenta.white("RUNNING"),a=0):(P.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),xQ||(i=`${i}`),P.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import _Q from"fs";import{platform as MQ,tmpdir as PQ}from"os";import IQ from"path";import{program as OQ}from"playwright-core/lib/cli/program";import{registry as yp}from"playwright-core/lib/server";import OF from"proper-lockfile";var NF=IQ.join(PQ(),"momenticBrowserInstallation");var oy=["chrome","chromium","chrome-for-testing","ffmpeg"],wXe=[...oy.filter(r=>r!=="ffmpeg")],NQ={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"};var LF={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function DF(r){if(r==="Org Default")return!1;let e=LF[NQ[r]??""]??"",t=yp.findExecutable(e);return!t||t.installType==="none"?!1:iw(t)}function iw(r){let e=r.executablePath();return _Q.existsSync(e)}function LQ(r,e){let t=LF[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=yp.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&iw(n)))return n}async function DQ({browser:r,force:e}){let t=LQ(r,e);if(!t){P.info(`Browser '${r}' is already installed, skipping...`);return}P.info(`Installing browser '${r}'...`);try{await yp.installDeps([t],!1),await yp.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){P.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=yp.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!iw(o);)P.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function kQ(){if(MQ()==="win32"){P.info("Installing Windows dependencies for Playwright...");try{await OQ.parseAsync(["","","install","winldd"])}catch(r){P.warn(`Failed to install Windows dependencies: ${r}. Continuing with browser installation...`)}}}async function iy({rawBrowsers:r,force:e=!1,all:t=!1}){await kQ();let n=t?oy:Array.from(new Set(r));try{await OF.lock(NF,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){P.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await DQ({browser:i,force:e})}catch(a){o=a,P.error(`Failed to install the ${i} browser: ${a}`)}}finally{await OF.unlock(NF,{realpath:!1})}if(o)throw o}import{createServer as FQ}from"http";async function zo(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await ay(o))return o}P.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function ay(r){return new Promise((e,t)=>{let n=FQ();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(P.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import PXe from"blocked-at";import OXe from"why-is-node-running";function kF(r){let e=r?.shardIndex??1,t=r?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(t<1)throw new Error("Shard count must be greater than 0.");if(e>t)throw new Error("Shard index cannot be greater than shard count")}function UQ(r,e,t,n){if(t>r.length&&(P.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let o=Math.floor((e-1)*(r.length/t)),i=Math.floor(e*(r.length/t));return(n?[...r].sort((s,l)=>n(s).localeCompare(n(l))):[...r].sort()).filter((s,l)=>l>=o&&l<i)}function FF(r){let{items:e,shardIndex:t,shardCount:n,sortKey:o}=r;return n>1?UQ(e,t,n,o):e}function sy({regenerateCache:r,saveCache:e,disableCache:t}){if(t){if(r)throw new Error("--disable-cache and --regenerate-cache cannot be used together.");if(e)throw new Error("--disable-cache and --save-cache cannot be used together.")}}function UF(r,e,t){return r instanceof Ls?(r.zodIssues.forEach(n=>{t.push({file:e,stepIndex:typeof n.path[0]=="number"?n.path[0]:void 0,field:n.path.slice(1).join(".")||n.path.join("."),issue:n.message})}),!0):!1}function aw({parsingErrors:r,parsingErrorDetails:e,failedTestFilePaths:t,failedModuleFilePaths:n}){if(P.error(`
39
39
  Found ${r} file(s) with validation errors that must be fixed manually:
40
40
  `),e.length>0){let o=new Map;e.forEach(i=>{let a=o.get(i.file)||[];a.push(i),o.set(i.file,a)}),o.forEach((i,a)=>{P.error(` ${a}`),i.forEach(({stepIndex:s,field:l,issue:c})=>{let u=s!==void 0?`Step ${s}`:"File",d=l?`, field "${l}"`:"";P.error(` ${u}${d}:`),P.error(` \u2192 ${c}`)})})}else t.size>0&&P.error(`Failed test files:
41
41
  ${[...t].map(o=>`${fu}- ${o}`).join(`
@@ -56,7 +56,7 @@ ${o.map(i=>i.configFilePath)}`);if(o.length===0)throw new Error("No valid Moment
56
56
  `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function Q7(r,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n&&e?.startsWith("git@")&&n.includes("github"))try{let{stdout:o,stderr:i}=await J7("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}catch{return}}async function eee(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return Q7(r,e,t);if(o)return}catch{}}function Py(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}function tee(r){if(!(r instanceof Error))return!1;let e=r.message;return e.includes("not a git repository")||e.includes("ENOENT")}async function Mt(r,e){try{return(await e).trim()}catch(t){if(tee(t))return;r.error({err:t},"Failed to run git command");return}}function ree(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild";if(process.env.MOMENTIC_GIT_OVERRIDE)return"Custom"}async function nee(r){let[e,t,n]=await Promise.all([Mt(r,_t.show(["--no-patch","--format=%ci"])),Mt(r,_t.show(["-s","--pretty=%B"])),Mt(r,_t.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?ia(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function oee(r){let[e,t,n]=await Promise.all([Mt(r,_t.listRemote(["--get-url","origin"])),Mt(r,_t.show(["-s","--pretty=%B"])),Mt(r,_t.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?ia(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function iee(r){let[e,t,n,o]=await Promise.all([Mt(r,_t.show(["--no-patch","--format=%ci"])),Mt(r,_t.listRemote(["--get-url","origin"])),Mt(r,_t.show(["-s","--pretty=%B"])),Mt(r,_t.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??t,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),l=i?Py(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?ia(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?l:void 0,gitlabProjectPath:s?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function aee(r){let[e,t,n]=await Promise.all([Mt(r,_t.show(["--no-patch","--format=%ci"])),Mt(r,_t.show(["-s","--pretty=%B"])),Mt(r,_t.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Py(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?ia(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function see(r){let[e,t,n]=await Promise.all([Mt(r,_t.show(["--no-patch","--format=%ci"])),Mt(r,_t.show(["-s","--pretty=%B"])),Mt(r,_t.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Py(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?ia(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function lee(r,e,t){let[n,o,i,a,s,l,c,u,d]=await Promise.all([Mt(r,_t.revparse(["HEAD"])),Mt(r,_t.revparse(["--short","HEAD"])),Mt(r,_t.revparse(["--abbrev-ref","HEAD"])),Mt(r,_t.listRemote(["--get-url","origin"])),Mt(r,_t.show(["--no-patch","--format=%ci"])),Mt(r,_t.show(["-s","--pretty=%B"])),Mt(r,_t.show(["-s","--pretty=%an"])),e?Mt(r,_t.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),Z7(r)]),m=u||(e?await Mt(r,_t.raw(["merge-base",e,"HEAD"])):void 0),p=m?await Mt(r,_t.show(["--no-patch","--format=%ci",m])):void 0,f=a?.includes("github.com"),h=a?.includes("gitlab.com"),g=a?Py(a):void 0,y=d["user.email"]||void 0,b=d["user.name"]||void 0,E=d["user.username"]||void 0,v=d["github.user"]||void 0,I=(t?.includeHostingUsername??!0?await eee(r,a,d):void 0)??E??v??void 0;return{ciProvider:"none",gitCommitSha:n,gitCommitShaShort:o,gitBranchName:i,gitOriginUrl:a,gitCommitTimestamp:s?ia(s):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:I,gitLocalEmail:y,gitLocalName:b,lastCommitOnMainSha:m,lastCommitOnMainTimestamp:p?ia(p):void 0,githubRepository:f?g:void 0,gitlabProjectPath:h?g:void 0,pipelineId:void 0}}async function cee(){let r=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}function uee(){return{ciProvider:"Custom",gitCommitSha:process.env.GIT_COMMIT_SHA,gitCommitShaShort:process.env.GIT_COMMIT_SHA_SHORT??process.env.GIT_COMMIT_SHA?.slice(0,6),gitCommitTimestamp:ia(process.env.GIT_COMMIT_TIMESTAMP),gitBranchName:process.env.GIT_BRANCH_NAME,gitOriginUrl:process.env.GIT_ORIGIN_URL,gitCommitAuthorName:process.env.GIT_COMMIT_AUTHOR_NAME,gitCommitMessage:process.env.GIT_COMMIT_MESSAGE,lastCommitOnMainSha:process.env.LAST_COMMIT_ON_MAIN_SHA,lastCommitOnMainTimestamp:ia(process.env.LAST_COMMIT_ON_MAIN_TIMESTAMP),mergedGitBranchName:process.env.MERGED_GIT_BRANCH_NAME,githubRepository:process.env.GITHUB_REPOSITORY,gitlabProjectPath:process.env.GITLAB_PROJECT_PATH,gitLocalUsername:process.env.GIT_USERNAME,gitLocalEmail:process.env.GIT_EMAIL,gitLocalName:process.env.GIT_NAME}}async function dee(r){let e=[...r.config.gitProtectedBranches??[]];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Cp(r,e,t){let n=ree();if(!n)return lee(r,e,t);switch(n){case"GithubActions":return nee(r);case"GitlabCI":return oee(r);case"CircleCI":return iee(r);case"Buildkite":return aee(r);case"AzureDevOps":return see(r);case"GCPCloudBuild":return cee();case"Custom":return uee()}}async function mee(r,e,t,n){let o=n,i=n.gitCommitSha;if(!i)return o;let a=n.gitMainBranch;if(a&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let s=await po({logger:r,operation:"getRemoteMetadataFromGitlab.getMergeBaseCommitFromGitlab",fn:()=>e.getMergeBaseCommitFromGitlab(t,a,i),context:{projectPath:t,mainBranch:a}});o={...o,lastCommitOnMainSha:s.sha,lastCommitOnMainTimestamp:s.committer.date}}catch(s){r.warn({err:s},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let s=await po({logger:r,operation:"getRemoteMetadataFromGitlab.getCommitFromGitlab",fn:()=>e.getCommitFromGitlab(t,i),context:{projectPath:t,gitCommitSha:i}});s&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??s.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??s.author.name,gitCommitMessage:o.gitCommitMessage??s.message})}catch(s){r.warn({err:s},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName){let s=n.gitBranchName;try{let l=await po({logger:r,operation:"getRemoteMetadataFromGitlab.getMergedBranchFromGitlab",fn:()=>e.getMergedBranchFromGitlab(t,s,i),context:{projectPath:t,branchName:s,gitCommitSha:i}});l.mergedBranch&&(o={...o,mergedGitBranchName:l.mergedBranch})}catch(l){r.warn({err:l},"Failed to get merged branch from Gitlab")}}return o}async function pee(r,e,t,n,o){let i=o,a=o.gitCommitSha;if(!a)return i;let s=o.gitMainBranch;if(s&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let l=await po({logger:r,operation:"getRemoteMetadataFromGitHub.getMergeBaseCommitFromGithub",fn:()=>e.getMergeBaseCommitFromGithub(t,n,s,a),context:{owner:t,repo:n,mainBranch:s}});i={...i,lastCommitOnMainSha:l.sha,lastCommitOnMainTimestamp:l.committer.date}}catch(l){r.warn({err:l},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let l=await po({logger:r,operation:"getRemoteMetadataFromGitHub.getCommitFromGithub",fn:()=>e.getCommitFromGithub(t,n,a),context:{owner:t,repo:n,gitCommitSha:a}});l&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??l.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??l.author.name,gitCommitMessage:i.gitCommitMessage??l.message})}catch(l){r.warn({err:l},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName){let l=o.gitBranchName;try{let c=await po({logger:r,operation:"getRemoteMetadataFromGitHub.getMergedBranchFromGithub",fn:()=>e.getMergedBranchFromGithub(t,n,l,a),context:{owner:t,repo:n,branchName:l,gitCommitSha:a}});c.mergedBranch&&(i={...i,mergedGitBranchName:c.mergedBranch})}catch(c){r.warn({err:c},"Failed to get merged branch from GitHub")}}return i}async function fee(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await po({logger:r,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>pee(r,e,n,o,t),context:{githubRepository:t.githubRepository}})}else if(t.gitlabProjectPath){let n=t.gitlabProjectPath;return await po({logger:r,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>mee(r,e,n,t),context:{gitlabProjectPath:n}})}}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Wr(r,e,t,n){let o={},i={gitMainBranch:t.config.gitMainBranch};return po({logger:r,operation:"getGitMetadata.total",fn:async()=>{let[a,s]=await Promise.all([po({logger:r,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>dee(t),context:{projectConfigPath:t.configFilePath}}),po({logger:r,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let u=await Cp(r,t.config.gitMainBranch,n);return i.ciProvider=u.ciProvider,u},context:i})]),l={...a,...s};o.gitBranchName=l.gitBranchName,o.githubRepository=l.githubRepository,o.gitlabProjectPath=l.gitlabProjectPath,(!l.lastCommitOnMainSha||!l.lastCommitOnMainTimestamp)&&l.gitBranchName===a.gitMainBranch&&(l.lastCommitOnMainSha=l.gitCommitSha,l.lastCommitOnMainTimestamp=l.gitCommitTimestamp);let c=await po({logger:r,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>fee(r,e,l),context:{githubRepository:l.githubRepository,gitlabProjectPath:l.gitlabProjectPath,gitBranchName:l.gitBranchName}});return{...a,...s,...c}},context:o})}import{diff as XU}from"deep-object-diff";import Wa from"fs";import{cloneDeep as hee}from"lodash-es";import Iy from"path";import{v4 as gee}from"uuid";import Rp from"yaml";function JU(r,e){let t=`${Do(e)}.module.yaml`,n=Iy.join(Iy.dirname(r),t);if(Wa.existsSync(n))throw new Error(`A conflicting file already exists at the following path: ${n}`);return Wa.renameSync(r,n),n}function vu({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath,a=t.mobileModules[r.moduleId]?.name;if(!i||!Wa.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let s=Wa.readFileSync(i,"utf-8"),l=Rp.parse(s),c={...l,...r,schemaVersion:e},u=ra({fileType:pt.MOBILE_MODULE,...Dm.parse(c),steps:qi(r.platform).array().parse(r.steps)}),d=!!r.name&&r.name!==a,m=XU(u,l);if(m&&Object.keys(m).length===0&&!o&&!d)return;let p=Rp.stringify(u);Wa.writeFileSync(i,p,"utf-8");let f;d&&(f=JU(i,r.name)),Si(f||i,n.config)}function ZU({moduleId:r,patch:e,momenticFiles:t,project:n,logger:o}){let i=t.mobileModules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update mobile module ${r} that could not be found on disk`);let a=xp(i,o),s={...a,...e},l=ra({fileType:pt.MOBILE_MODULE,...Fh.parse(s)}),c=XU(l,a);if(c&&Object.keys(c).length===0)return;let u=Rp.stringify(l);Wa.writeFileSync(i,u,"utf-8");let d;e.name&&(d=JU(i,e.name)),Si(d||i,n.config)}async function _p({name:r,description:e,enabled:t,platform:n,steps:o,folder:i,project:a}){let s=Do(r),l=Iy.join(i,`${s}.module.yaml`),c=gee(),{stepsToSave:u}=await _n({platform:n,steps:o}),d={schemaVersion:Sa,platform:n,moduleId:c,description:e,enabled:t},m={fileType:pt.MOBILE_MODULE,...d,steps:u},p=Rp.stringify(EN.parse(m));switch(Wa.writeFileSync(l,p,"utf-8"),Si(l,a.config),n){case"ANDROID":return{moduleId:c,platform:n,name:r,description:e||void 0,steps:o};case"IOS":return{moduleId:c,platform:n,name:r,description:e||void 0,steps:o}}}function xp(r,e){let t=Wa.readFileSync(r,"utf-8"),n=Rp.parse(t);try{return{...Fh.parse(n),name:Iy.basename(r,".module.yaml")}}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic mobile module`),o}}async function hl(r,e,t,n){let o=xp(r.fullFilePath,t),i=o.platform==="ANDROID"?n?.android:n?.ios,{resolvedSteps:a}=await fy({platform:o.platform,rawSteps:o.steps,resolvedModuleCache:i||{},onFetchModule:async l=>{let c=e.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${l}`);return xp(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),s=o.platform==="ANDROID"?{...o,platform:"ANDROID",name:r.name,description:o.description||void 0,steps:a}:{...o,platform:"IOS",name:r.name,description:o.description||void 0,steps:a};return i&&(i[r.id]=hee(s)),s}async function QU(r,e){let t={},n={};return await Promise.all(Object.values(r.mobileModules).map(async o=>{await hl(o,r,e,{ios:t,android:n})})),[...Object.values(t),...Object.values(n)]}import{randomUUID as yee}from"crypto";import fo from"fs";import Va from"path";import Au from"yaml";import gl from"zod";var Oy=gl.discriminatedUnion("platform",[zh.extend({steps:gl.record(gl.string(),gl.unknown()).array()}),$h.extend({steps:gl.record(gl.string(),gl.unknown()).array()})]);function Ny({name:r,description:e="",settings:t={},folder:n,platform:o="ANDROID"}){try{eo(r)}catch(d){throw new ln(`${d} when validating the test entity name`)}let a=`${Do(r)}.test.yaml`,s=Va.join(n,a);if(fo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let l=yee(),c={fileType:pt.MOBILE_TEST,id:l,description:e,schemaVersion:vn,platform:o,settings:t,steps:[]},u=Au.stringify(MN.parse(c));return fo.writeFileSync(s,u,"utf-8"),{fullPath:s,testId:l}}function See(r){if(!fo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=fo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
57
57
  `),t=Au.parse(e);if(!t.steps||!Array.isArray(t.steps))throw new Error(`Test ${r} is missing steps`);return t}async function Er(r,e,t){let n=See(r),o;try{o=Ma.parse(n)}catch(a){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${a}`,{cause:a})}let i={rawStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},logger:e,testMetadata:o,onFetchModule:async a=>{let s=t.mobileModules[a]?.fullFilePath;if(!s)throw new Error(`Mobile module ${a} not found`);return xp(s,e)}};switch(o.platform){case"ANDROID":{let{resolvedStepLists:a}=await bw({...i,platform:o.platform});return{...o,steps:a.steps}}case"IOS":{let{resolvedStepLists:a}=await bw({...i,platform:o.platform});return{...o,steps:a.steps}}}}async function wu({platform:r,filePath:e,steps:t,settings:n,labels:o,folder:i,project:a,momenticFiles:s,schemaVersion:l}){let c=Va.isAbsolute(e)?e:Va.join(i,e);if(!fo.existsSync(c))throw new Error(`Test file not found: ${c}`);let u=fo.readFileSync(c,"utf-8").replace(/\r\n|\r/g,`
58
58
  `),d=Au.parse(u),m=Oy.parse({...d,schemaVersion:l});if(m.fileType!==pt.MOBILE_TEST)throw new Error(`File at '${c}' is not a mobile test (fileType=${m.fileType}).`);if(m.platform!==r)throw new Error(`Platform mismatch. Test at '${c}' is for platform ${m.platform}, but update is for platform ${r}.`);let p;t&&(p=await _n({platform:m.platform,steps:t}));let f={...m,...p?.stepsToSave!==void 0?{steps:p.stepsToSave}:{steps:m.steps},...o!==void 0?{labels:o}:{}};n&&(f.settings=n);let h=Au.stringify(Oy.parse(f));for(let g of p?.moduleUpdates??[])vu({content:g,schemaVersion:vn,momenticFiles:s,project:a});fo.writeFileSync(c,h,"utf-8"),Si(c,a.config)}function eB(r,e,t){let n=Va.join(t.rootDir,r);if(!fo.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=fo.readFileSync(n,"utf-8").replace(/\r\n|\r/g,`
59
- `),i=Au.parse(o),a=Oy.parse(i),s=Va.basename(r,".test.yaml"),l,c;if(e.name&&e.name!==s){let m=`${Do(e.name)}.test.yaml`;if(l=Va.join(Va.dirname(r),m),c=Va.join(t.rootDir,l),fo.existsSync(c))throw new Error(`Test with name '${e.name}' already exists at path '${c}'`)}let u={...a,...e};if(delete u.name,u.fileType!==pt.MOBILE_TEST)throw new Error(`File at '${n}' is not a mobile test (fileType=${u.fileType}).`);let d=Au.stringify(Oy.parse(u));return fo.writeFileSync(n,d,"utf-8"),c&&c!==n?(fo.renameSync(n,c),Si(c,t.config)):Si(n,t.config),{newRelativeTestPath:l}}import{randomUUID as bee}from"crypto";import qa from"fs";import Cu from"path";var tB=new Set([".DS_Store","__MACOSX"]),rB={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function Eee(r,e,t){if(rB[t]){let i=rB[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var Iw=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function nB(r,e){try{let t=Cu.join(e,"metadata.json");return Xc.parse(JSON.parse(qa.readFileSync(t,"utf-8")))}catch{throw new Iw(r,e)}}function oB(r,e,t){let n=bee(),o=r.child({runGroupId:n});qa.rmSync(e,{recursive:!0,force:!0});let i=qa.readdirSync(t).filter(l=>!tB.has(l)).map(l=>Cu.join(t,l));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);qa.mkdirSync(e,{recursive:!0});let a={...nB(t,i[0]),id:n};for(let l of i){let c=Cu.join(l,"runs");if(!qa.existsSync(c))continue;let u=nB(t,l);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=Eee(a,u,p)}let d=qa.readdirSync(c);for(let m of d){if(tB.has(m))continue;let p=Cu.join(c,m),f=Cu.join(e,"runs",m);qa.cpSync(p,f,{recursive:!0})}}let s=Cu.join(e,"metadata.json");qa.writeFileSync(s,JSON.stringify(a,null,2))}import qz from"adm-zip";import Zw from"fs";import{z as cne}from"zod";var K="v1",Ow="mobile-cli",yl="0.59.0";var Tee=9e4,vee=3,Aee=1500,wee=15e3,Ho=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function Cee(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Nw=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return yl&&(e[rg]=yl),Ow&&(e[gL]=Ow),e}async sendRequest(e,t){let{retries:n=vee,requestTimeoutMs:o=Tee,initialRetryDelayMs:i=Aee,maxRetryDelayMs:a=wee,onFailedRequest:s}=t,l=n,c=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Ho&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Da),l===0)throw u;let p=c-l,f=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,f))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let l=Date.now(),c={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!u.ok){let p=await Cee(u);throw new Ho(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else if(t.responseType==="buffer"){let p=await u.arrayBuffer();d=Buffer.from(p)}else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-l,...o},"Got response from Momentic server");let m=t.responseHeadersObject;return m&&u.headers.forEach((p,f)=>{m[f.toLowerCase()]=p}),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},bi=class extends Nw{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[hL]:this.mode??""}}};import{createAnthropic as lne}from"@ai-sdk/anthropic";var NB="vercel.ai.error",Ree=Symbol.for(NB),iB,aB,Nt=class LB extends(aB=Error,iB=Ree,aB){constructor({name:e,message:t,cause:n}){super(t),this[iB]=!0,this.name=e,this.cause=n}static isInstance(e){return LB.hasMarker(e,NB)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}},DB="AI_APICallError",kB=`vercel.ai.error.${DB}`,xee=Symbol.for(kB),sB,lB,Vr=class extends(lB=Nt,sB=xee,lB){constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:i,cause:a,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:DB,message:r,cause:a}),this[sB]=!0,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=i,this.isRetryable=s,this.data=l}static isInstance(r){return Nt.hasMarker(r,kB)}},FB="AI_EmptyResponseBodyError",UB=`vercel.ai.error.${FB}`,_ee=Symbol.for(UB),cB,uB,BB=class extends(uB=Nt,cB=_ee,uB){constructor({message:r="Empty response body"}={}){super({name:FB,message:r}),this[cB]=!0}static isInstance(r){return Nt.hasMarker(r,UB)}};function zB(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var $B="AI_InvalidArgumentError",HB=`vercel.ai.error.${$B}`,Mee=Symbol.for(HB),dB,mB,Ly=class extends(mB=Nt,dB=Mee,mB){constructor({message:r,cause:e,argument:t}){super({name:$B,message:r,cause:e}),this[dB]=!0,this.argument=t}static isInstance(r){return Nt.hasMarker(r,HB)}},jB="AI_InvalidPromptError",GB=`vercel.ai.error.${jB}`,Pee=Symbol.for(GB),pB,fB,WB=class extends(fB=Nt,pB=Pee,fB){constructor({prompt:r,message:e,cause:t}){super({name:jB,message:`Invalid prompt: ${e}`,cause:t}),this[pB]=!0,this.prompt=r}static isInstance(r){return Nt.hasMarker(r,GB)}},VB="AI_InvalidResponseDataError",qB=`vercel.ai.error.${VB}`,Iee=Symbol.for(qB),hB,gB,Dy=class extends(gB=Nt,hB=Iee,gB){constructor({data:r,message:e=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:VB,message:e}),this[hB]=!0,this.data=r}static isInstance(r){return Nt.hasMarker(r,qB)}},KB="AI_JSONParseError",YB=`vercel.ai.error.${KB}`,Oee=Symbol.for(YB),yB,SB,Mp=class extends(SB=Nt,yB=Oee,SB){constructor({text:r,cause:e}){super({name:KB,message:`JSON parsing failed: Text: ${r}.
59
+ `),i=Au.parse(o),a=Oy.parse(i),s=Va.basename(r,".test.yaml"),l,c;if(e.name&&e.name!==s){let m=`${Do(e.name)}.test.yaml`;if(l=Va.join(Va.dirname(r),m),c=Va.join(t.rootDir,l),fo.existsSync(c))throw new Error(`Test with name '${e.name}' already exists at path '${c}'`)}let u={...a,...e};if(delete u.name,u.fileType!==pt.MOBILE_TEST)throw new Error(`File at '${n}' is not a mobile test (fileType=${u.fileType}).`);let d=Au.stringify(Oy.parse(u));return fo.writeFileSync(n,d,"utf-8"),c&&c!==n?(fo.renameSync(n,c),Si(c,t.config)):Si(n,t.config),{newRelativeTestPath:l}}import{randomUUID as bee}from"crypto";import qa from"fs";import Cu from"path";var tB=new Set([".DS_Store","__MACOSX"]),rB={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function Eee(r,e,t){if(rB[t]){let i=rB[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var Iw=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function nB(r,e){try{let t=Cu.join(e,"metadata.json");return Xc.parse(JSON.parse(qa.readFileSync(t,"utf-8")))}catch{throw new Iw(r,e)}}function oB(r,e,t){let n=bee(),o=r.child({runGroupId:n});qa.rmSync(e,{recursive:!0,force:!0});let i=qa.readdirSync(t).filter(l=>!tB.has(l)).map(l=>Cu.join(t,l));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);qa.mkdirSync(e,{recursive:!0});let a={...nB(t,i[0]),id:n};for(let l of i){let c=Cu.join(l,"runs");if(!qa.existsSync(c))continue;let u=nB(t,l);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=Eee(a,u,p)}let d=qa.readdirSync(c);for(let m of d){if(tB.has(m))continue;let p=Cu.join(c,m),f=Cu.join(e,"runs",m);qa.cpSync(p,f,{recursive:!0})}}let s=Cu.join(e,"metadata.json");qa.writeFileSync(s,JSON.stringify(a,null,2))}import qz from"adm-zip";import Zw from"fs";import{z as cne}from"zod";var K="v1",Ow="mobile-cli",yl="0.59.1";var Tee=9e4,vee=3,Aee=1500,wee=15e3,Ho=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function Cee(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Nw=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return yl&&(e[rg]=yl),Ow&&(e[gL]=Ow),e}async sendRequest(e,t){let{retries:n=vee,requestTimeoutMs:o=Tee,initialRetryDelayMs:i=Aee,maxRetryDelayMs:a=wee,onFailedRequest:s}=t,l=n,c=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Ho&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Da),l===0)throw u;let p=c-l,f=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,f))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let l=Date.now(),c={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!u.ok){let p=await Cee(u);throw new Ho(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else if(t.responseType==="buffer"){let p=await u.arrayBuffer();d=Buffer.from(p)}else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-l,...o},"Got response from Momentic server");let m=t.responseHeadersObject;return m&&u.headers.forEach((p,f)=>{m[f.toLowerCase()]=p}),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},bi=class extends Nw{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[hL]:this.mode??""}}};import{createAnthropic as lne}from"@ai-sdk/anthropic";var NB="vercel.ai.error",Ree=Symbol.for(NB),iB,aB,Nt=class LB extends(aB=Error,iB=Ree,aB){constructor({name:e,message:t,cause:n}){super(t),this[iB]=!0,this.name=e,this.cause=n}static isInstance(e){return LB.hasMarker(e,NB)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}},DB="AI_APICallError",kB=`vercel.ai.error.${DB}`,xee=Symbol.for(kB),sB,lB,Vr=class extends(lB=Nt,sB=xee,lB){constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:i,cause:a,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:DB,message:r,cause:a}),this[sB]=!0,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=i,this.isRetryable=s,this.data=l}static isInstance(r){return Nt.hasMarker(r,kB)}},FB="AI_EmptyResponseBodyError",UB=`vercel.ai.error.${FB}`,_ee=Symbol.for(UB),cB,uB,BB=class extends(uB=Nt,cB=_ee,uB){constructor({message:r="Empty response body"}={}){super({name:FB,message:r}),this[cB]=!0}static isInstance(r){return Nt.hasMarker(r,UB)}};function zB(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var $B="AI_InvalidArgumentError",HB=`vercel.ai.error.${$B}`,Mee=Symbol.for(HB),dB,mB,Ly=class extends(mB=Nt,dB=Mee,mB){constructor({message:r,cause:e,argument:t}){super({name:$B,message:r,cause:e}),this[dB]=!0,this.argument=t}static isInstance(r){return Nt.hasMarker(r,HB)}},jB="AI_InvalidPromptError",GB=`vercel.ai.error.${jB}`,Pee=Symbol.for(GB),pB,fB,WB=class extends(fB=Nt,pB=Pee,fB){constructor({prompt:r,message:e,cause:t}){super({name:jB,message:`Invalid prompt: ${e}`,cause:t}),this[pB]=!0,this.prompt=r}static isInstance(r){return Nt.hasMarker(r,GB)}},VB="AI_InvalidResponseDataError",qB=`vercel.ai.error.${VB}`,Iee=Symbol.for(qB),hB,gB,Dy=class extends(gB=Nt,hB=Iee,gB){constructor({data:r,message:e=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:VB,message:e}),this[hB]=!0,this.data=r}static isInstance(r){return Nt.hasMarker(r,qB)}},KB="AI_JSONParseError",YB=`vercel.ai.error.${KB}`,Oee=Symbol.for(YB),yB,SB,Mp=class extends(SB=Nt,yB=Oee,SB){constructor({text:r,cause:e}){super({name:KB,message:`JSON parsing failed: Text: ${r}.
60
60
  Error message: ${zB(e)}`,cause:e}),this[yB]=!0,this.text=r}static isInstance(r){return Nt.hasMarker(r,YB)}},XB="AI_LoadAPIKeyError",JB=`vercel.ai.error.${XB}`,Nee=Symbol.for(JB),bB,EB,Pp=class extends(EB=Nt,bB=Nee,EB){constructor({message:r}){super({name:XB,message:r}),this[bB]=!0}static isInstance(r){return Nt.hasMarker(r,JB)}},ZB="AI_LoadSettingError",QB=`vercel.ai.error.${ZB}`,Lee=Symbol.for(QB),TB,vB,Htt=class extends(vB=Nt,TB=Lee,vB){constructor({message:r}){super({name:ZB,message:r}),this[TB]=!0}static isInstance(r){return Nt.hasMarker(r,QB)}},ez="AI_NoContentGeneratedError",tz=`vercel.ai.error.${ez}`,Dee=Symbol.for(tz),AB,wB,jtt=class extends(wB=Nt,AB=Dee,wB){constructor({message:r="No content generated."}={}){super({name:ez,message:r}),this[AB]=!0}static isInstance(r){return Nt.hasMarker(r,tz)}},rz="AI_NoSuchModelError",nz=`vercel.ai.error.${rz}`,kee=Symbol.for(nz),CB,RB,Gtt=class extends(RB=Nt,CB=kee,RB){constructor({errorName:r=rz,modelId:e,modelType:t,message:n=`No such ${t}: ${e}`}){super({name:r,message:n}),this[CB]=!0,this.modelId=e,this.modelType=t}static isInstance(r){return Nt.hasMarker(r,nz)}},oz="AI_TooManyEmbeddingValuesForCallError",iz=`vercel.ai.error.${oz}`,Fee=Symbol.for(iz),xB,_B,az=class extends(_B=Nt,xB=Fee,_B){constructor(r){super({name:oz,message:`Too many values for a single embedding call. The ${r.provider} model "${r.modelId}" can only embed up to ${r.maxEmbeddingsPerCall} values per call, but ${r.values.length} values were provided.`}),this[xB]=!0,this.provider=r.provider,this.modelId=r.modelId,this.maxEmbeddingsPerCall=r.maxEmbeddingsPerCall,this.values=r.values}static isInstance(r){return Nt.hasMarker(r,iz)}},sz="AI_TypeValidationError",lz=`vercel.ai.error.${sz}`,Uee=Symbol.for(lz),MB,PB,Ka=class Lw extends(PB=Nt,MB=Uee,PB){constructor({value:e,cause:t}){super({name:sz,message:`Type validation failed: Value: ${JSON.stringify(e)}.
61
61
  Error message: ${zB(t)}`,cause:t}),this[MB]=!0,this.value=e}static isInstance(e){return Nt.hasMarker(e,lz)}static wrap({value:e,cause:t}){return Lw.isInstance(t)&&t.value===e?t:new Lw({value:e,cause:t})}},cz="AI_UnsupportedFunctionalityError",uz=`vercel.ai.error.${cz}`,Bee=Symbol.for(uz),IB,OB,Mn=class extends(OB=Nt,IB=Bee,OB){constructor({functionality:r,message:e=`'${r}' functionality not supported.`}){super({name:cz,message:e}),this[IB]=!0,this.functionality=r}static isInstance(r){return Nt.hasMarker(r,uz)}};var ky=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Dw(r){}function dz(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=Dw,onError:t=Dw,onRetry:n=Dw,onComment:o}=r,i="",a=!0,s,l="",c="";function u(h){let g=a?h.replace(/^\xEF\xBB\xBF/,""):h,[y,b]=zee(`${i}${g}`);for(let E of y)d(E);i=b,a=!1}function d(h){if(h===""){p();return}if(h.startsWith(":")){o&&o(h.slice(h.startsWith(": ")?2:1));return}let g=h.indexOf(":");if(g!==-1){let y=h.slice(0,g),b=h[g+1]===" "?2:1,E=h.slice(g+b);m(y,E,h);return}m(h,"",h)}function m(h,g,y){switch(h){case"event":c=g;break;case"data":l=`${l}${g}
62
62
  `;break;case"id":s=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):t(new ky(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:t(new ky(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:g,line:y}));break}}function p(){l.length>0&&e({id:s,event:c||void 0,data:l.endsWith(`
@@ -4881,25 +4881,25 @@ ${r}`;case"ELEMENT_CHECK":return`${DH}
4881
4881
  ${r}`;default:return r}}async function vo({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var Yse=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function UH({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(Yse.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,l=Date.now(),c=0;for(;c===0||Date.now()-l<s;){await ee(250),c++;let u=(await t.getOpenPages()).map(m=>m.url),d=t.url();if(u.length!==e.length)for(let m=u.length-1;m>=e.length;m--){let p=u[m];if(ml(p,o)&&p!==r&&p!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(m)});break}}}}async function Mi(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}var BH=r=>!!r&&tc(r),zH=r=>{let{cache:e,description:t,disableSecondaryCacheResolution:n,logger:o}=r,i=e,a=!1,s;return i&&n&&i.targetSource==="HEURISTIC_HEALED"&&(a=!0,s="Heuristic healed cache incompatible",i=void 0),i?.inputDescription&&!kH(t,i.inputDescription)&&(o.warn({old:i.inputDescription,new:t},"Target cache was generated with a different description, clearing it automatically"),a=!0,s="Description changed",i=void 0),{cache:i,cacheBustedBeforeAction:a,cacheBustReason:s}};import{randomUUID as tle}from"crypto";var HH={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},jH={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},$H=/<(\S+) id="(\d+)".*?>/g,Xse=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,GH=["h1","h2","section","footer","nav","aside","form","label","dialog"],Jse=[...GH,"span","div","h3"],Zse=["table","select","form","ul","ol","menu","pre","code","dialog"],Qse=["table","form","dialog","nav","section","ul","select"];function AS(r){return ele(r)}function ele({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,s=[],l=e.split(`
4882
4882
  `),c=0,u=[],d=0,m=[],p=[],f=!1;for(;c<l.length;){f&&(s.push({ids:m,content:u.join(`
4883
4883
  `),tokenLength:d}),u=[],d=0,m=p.length?[p[p.length-1].id]:[],f=!1);let h=l[c],g=mo(h);d+=g,h.length>a&&(h=h.slice(0,a));let E=Array.from(h.matchAll($H)).map($=>$&&$.length>=3?{tagName:$[1],id:$[2]}:void 0).filter($=>!!$),w=Array.from(h.matchAll(Xse)).map($=>$&&($[2]||$[4])).filter($=>!!$);w.reverse();let L=h.replace(/ id="[0-9]+"/g,"");u.push(L);for(let $ of E)m.push($.id),p.push($);for(let $ of w){let xe=p[p.length-1];xe&&xe.tagName===$&&p.pop()}let I=p.some($=>Zse.includes($.tagName)),A=l[c+1]??"",_=mo(A),k=Array.from(A.matchAll($H)).map($=>$&&$.length>2?$[1]:void 0).filter($=>!!$),D=k.some($=>GH.includes($)),j=k.some($=>Jse.includes($));d+_>=i&&(f=!0),d>=n&&(D&&!I||w.some($=>Qse.includes($)))&&(f=!0),d>=o&&j&&!I&&(f=!0),c++}return u.length&&s.push({ids:m,content:u.join(`
4884
- `),tokenLength:d}),s.forEach((h,g)=>{let y=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:y,maxId:b},`Chunk for page filtering (index ${g+1}/${s.length})`)}),{chunks:s}}var rle=75e4,wS=3e5;async function Cl(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:l}=t,c=r.tree,u=r.serializedTree,d=mo(u);if(d>rle)try{let m=AS({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});c=await ole({...r,tokenLimit:wS-1e4,chunks:m.chunks}),u=c.serialize();let p=mo(u);i.info({oldTokens:d,newTokens:p},"Filtered page using keywords"),d=p}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),c=c.pruneToSerializedCharLimit(wS*ja),u=c.serialize();let p=mo(u);i.info({oldTokens:d,newTokens:p},"Filtered page using naive truncation"),d=p}if(d>wS)try{if(o){let m=AS({serializedTree:u,options:jH,logger:i}),p=tle();c=await J(nle({...r,chunks:m.chunks,callId:p}),{milliseconds:12e3,signal:l}),u=c.serialize();let f=mo(u);i.info({oldTokens:d,newTokens:f,langfuseCallId:p},"Filtered page using AI chunk ranking"),d=f}else{let m=AS({serializedTree:u,options:HH,logger:i});c=await J(ile({...r,chunkResult:m,tokenLimit:4e4}),{milliseconds:12e3,signal:l}),u=c.serialize();let p=mo(u);i.info({oldTokens:d,newTokens:p},"Filtered page using RAG"),d=p}}catch(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),c=c.pruneToSerializedCharLimit(wS*ja),u=c.serialize(),i.info("Filtered page using naive truncation")}return u}async function nle({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:l}=o,c=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:l,loggerTags:Ee(l)}),u=[];return t.forEach((m,p)=>{c.indices.includes(p)&&(u=u.concat(m.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function ole(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:Ee(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let l of s.keywords){let c=r.chunks.filter(p=>p.content.toLowerCase().includes(l.toLowerCase()));if(!c.length||c.reduce((p,f)=>p+f.tokenLength,0)>r.tokenLimit&&c.length>1)continue;let d=c.flatMap(p=>p.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function ile(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:s,signal:l}=t,c=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:l,logger:s,loggerTags:Ee(s)});if(c.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(c.ids.map(d=>`${d}`)))}async function ZC(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return vo({action:async()=>ale(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function ale(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:l,logger:c,allowNotActionableNodesOverride:u,skipSavingVisualAttributes:d,isAutoHeal:m,cacheBustReason:p}=r,{orgId:f,browser:h,localCodeEvalTools:g,generator:y,abortSignal:b}=e,E=r.description,v=Pn(),w=r.useMemory&&!t;n&&(E=await bl({orgId:f,s:E,context:n,localTools:g,signal:b,logger:c})),a&&(E=FH(E,a));let{serializedTree:L,tree:I}=await v.startAsyncSpan("GET_PAGE_STATE",async()=>Mi(h,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:b,skipWait:i,logger:c}),{}),A=await v.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let ie,se=Date.now(),Pe;for(;!ie&&Date.now()-se<3e3;){b.throwIfAborted();try{ie=await h.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(we){Pe=we}}if(!ie)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${Pe?.message}`);return ie}),_=L,O=!1,D=`data:image/jpeg;base64,${A.toString("base64")}`;_=await Cl({type:"locator",description:E,screenshot:D,serializedTree:L,options:{aiPageFiltering:l},tree:I,fixtures:{generator:y,signal:b,logger:c,orgId:f}}),_!==L&&(O=!0);let j=await v.startAsyncSpan("AI_LOCATOR_CALL",async ie=>{m&&(ie.attributes.isAutoHeal=!0),p&&(ie.attributes.cacheBustReason=p);let se=await y.getElementLocation({browserState:_,goal:E,screenshot:D,source:a,memory:w?s:void 0},{disableCache:t,abortSignal:b,loggerTags:Ee(c),useMemory:w});if(ie.result=se,v.storeTraceAsset){let Pe=WH();v.storeTraceAsset({snapshotId:Pe,data:A}),ie.screenshotSnapshotId=Pe}return se});if(c.debug({usedRag:O,result:j},"Got locator result"),!(j.id>0))throw new ni(`Could not find any relevant element: ${j.thoughts}`,j.updatedMemory?{type:"GCS_TRACES",traces:j.updatedMemory}:void 0);let{resolution:xe,target:B,frameConfig:Z}=await v.startAsyncSpan("TARGET_RESOLUTION",async ie=>{let se=await h.createTargetFromA11yId({id:j.id,requirements:j.requirements,additionalElements:j.additionalElements,description:E,targetSource:"AI",logger:c,skipSavingVisualAttributes:d});if(ie.result={serializedElement:se.target.nodeOnlySerializedHtml??"Unknown HTML element"},v.storeTraceAsset)try{let Pe=await h.screenshot({locator:se.resolution.locator,clearHighlights:!0}),we=WH();v.storeTraceAsset({snapshotId:we,data:Pe}),ie.elementScreenshotSnapshotId=we}catch(Pe){c.debug({err:Pe},"Failed to capture element screenshot for locator trace, continuing...")}return se});if(xe.a11yNode?.properties?.hidden&&xe.a11yNode?.properties?.hidden!=="false")throw new C("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${xe.displayString}`);return w&&(j.updatedMemory?B.memory={type:"GCS_TRACES",traces:j.updatedMemory}:s&&(B.memory=s)),{thoughts:j.thoughts,target:B,resolution:xe,frameConfig:Z,screenshot:D}}import{randomUUID as VH}from"crypto";var sle=15;async function CS({command:r,aiPageFiltering:e,logger:t,fixtures:n,useMemory:o,maxRetries:i=sle}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let a=kT.optional().catch(void 0).parse(r.source);r.source&&!a&&t.warn(`Invalid source ${r.source} for AI assertion, ignoring...`);let s=Pn();return s.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,u=r.timeout?r.timeout*1e3:c.smartWaitingTimeout,d=FU(u,i-1),m=0,p=Date.now(),f=p+u,h=p,g,y,b;try{await vo({action:()=>c.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:c,logger:t})}catch(w){t.warn({err:w},"Failed to clear highlights before AI check, continuing...")}for(;m<i;){n.abortSignal.throwIfAborted();let w=Date.now();if(m>0){if(w>=f)break;let A=f-w,_=h-w,O=Math.min(_,A);O>0&&await ee(O,n.abortSignal)}let L=Date.now();if(m>0&&L>=f)break;let I=!1;try{if(g=await vo({action:async()=>{let _=await qH(c,t,n.abortSignal);return y&&y.serializedTree===_.serializedTree&&y.screenshotBuff.equals(_.screenshotBuff)?(I=!0,g):(y=_,KH({command:r,state:_,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:m,aiPageFiltering:e,logger:t,source:a}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:c}),g?.success){g?.updatedMemory&&bp(r,g.updatedMemory,t);break}else throw g?.thoughts?new C("AssertionFailureError",g.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(A){n.abortSignal.throwIfAborted(),b=A instanceof Error?A:new Error(`${A}`),I?t.info(`AI check attempt ${m} failed (re-used previous result)`):t.info({err:A},`AI check assert attempt ${m} failed, retrying...`)}finally{m++,h=L+d}}if(!g?.success){let w=f-Date.now();w>0&&await ee(w,n.abortSignal)}if(!g?.success)try{g=await vo({action:async()=>KH({command:r,state:await qH(c,t,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:m,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:c})}catch(w){n.abortSignal.throwIfAborted(),b=w instanceof Error?w:new Error(`${w}`)}finally{m++}g?.updatedMemory&&bp(r,g.updatedMemory,t);let E=g?.afterScreenshotOverride;if(E&&s.storeTraceAsset){let w=VH();s.storeTraceAsset({snapshotId:w,data:E}),l.screenshotSnapshotId=w}let v=g?.elementScreenshotOverride;if(v&&s.storeTraceAsset){let w=VH();s.storeTraceAsset({snapshotId:w,data:v}),l.elementScreenshotSnapshotId=w}if(!g?.success){l.result={thoughts:b?.message??"AI check failed after all attempts",result:!1};let w=`AI check still failing after ${m} attempts.`;throw b&&(w+=` Latest result: ${b.message}`),new C("AssertionFailureError",w)}return l.result={thoughts:g.thoughts,result:!0},{...g,succeedImmediately:!1,urlAfterCommand:c.url()}})}async function qH(r,e,t){await r.waitForPageLoad({signal:t});let[n,o]=await Promise.all([Mi(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function KH({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:l,logger:c}){let{browser:u,generator:d,abortSignal:m}=t,p={type:"ASSERTION"},{serializedTree:f,tree:h}=e,g=e.screenshotBuff,y=g.toString("base64"),b=u.url(),E=r.contextChoice??"MULTIMODAL",v=f;E!=="VISION_ONLY"&&(v=await Cl({type:"assertion",serializedTree:f,tree:h,description:r.assertion,screenshot:y,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:c,orgId:t.orgId}}),v!==f&&(p.ragUsed=!0),p.pageState=v);let w={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:y,contextChoice:E,source:l},I=await(E==="VISION_ONLY"?(_,O)=>d.getVisualAssertionResult(_,O):(_,O)=>d.getAssertionResult(_,O))(w,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:c,loggerTags:Ee(c)}),A;if((I.result||i)&&I.relevantElements?.length){p.relevantElementsSerialized=I.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_);try{let _=I.relevantElements[0],{resolution:O}=await u.createTargetFromA11yId({id:_,description:null,targetSource:"AI",skipSaveToCache:!0});A=await u.screenshot({locator:O.locator,clearHighlights:!0,respectActiveFrame:!0})}catch(_){c.debug({err:_},"Failed to capture element screenshot for trace, continuing...")}await lle(I.relevantElements,u,c)}return{success:I.result,thoughts:I.thoughts,afterScreenshotOverride:g,elementScreenshotOverride:A,updatedMemory:o?I.updatedMemory:void 0}}async function lle(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await J(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var cle=1e5,RS=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function YH(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await ule(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof RS?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await ee(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function ule(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await ee(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await J(dle(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function dle(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await vo({action:async()=>mle(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function mle(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:l,orgId:c,generator:u}=e,d=r.description;t&&(d=await bl({orgId:c,s:d,context:t,localTools:l,signal:s,logger:n}));let{serializedTree:m}=await Mi(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(mo(m)>cle)throw new RS;s.throwIfAborted();let f;try{f=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let g=`data:image/jpeg;base64,${f.toString("base64")}`;s.throwIfAborted();let y=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:g},{abortSignal:s,loggerTags:Ee(n)});return n.debug({result:y},"Got smart waiting result"),y.isPageReady}import{cloneDeep as JH}from"lodash-es";async function ZH(r){return Pn().startAsyncSpan("ELEMENT_ASSERTION",async t=>ple(r,t),{name:"Element check"})}async function ple(r,e){let{command:t,timeoutMs:n,fixtures:o,disableCache:i}=r,{abortSignal:a}=o,s=()=>rh(t.cache)?t.cache:void 0,l=s(),c=!i&&!!l?.target&&tc(l.target),u=JH(l),d=(b=!1)=>{if(l=s(),!!l)if(b){let E=qF(u,l);l.target=E.target,l.updatedAt=E.updatedAt}else{if(!u){l=void 0;return}l.target=u.target,l.updatedAt=u.updatedAt}},m=Date.now(),p=0,f,h=500,g=!1;for(;p<2||Date.now()-m<n;){p++,p>1&&await ee(h,a),a?.throwIfAborted(),l=s();let b=p===1,{result:E,elementWasFound:v}=await XH({cacheToUse:l,skipAISmartWaiting:!b,useAIIfCacheFails:!c,params:r});if(f=E,g=g||v,E.success)break;d(),h=Math.min(h*1.25,1e4)}if(!f)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${n}ms.`);if(a?.throwIfAborted(),!f.success){let b=s(),E=b?.target?.memory?{target:{id:-1,memory:b.target.memory}}:void 0,{result:v,elementWasFound:w}=await XH({cacheToUse:E,skipAISmartWaiting:!0,useAIIfCacheFails:!0,params:r});f=v,g=g||w,f.success||d(!0)}let y=s();return f.success&&y?.target&&!g&&(y.target=mw(y.target),y.updatedAt=new Date),e.result={success:f.success,message:f.err?.message},f}async function XH({cacheToUse:r,skipAISmartWaiting:e,useAIIfCacheFails:t,params:n}){let{command:o,disableCache:i,fixtures:a,tracer:s,targetingWrapper:l}=n,{logger:c}=a;if(o.target&&!ha(o.target))throw new Error("Element assertion with x/y is not supported yet");let u=yu(o.assertion),d,m=!1,p=JH(r);try{let{elementInteractedDisplayString:f,result:h,thoughts:g}=await l({tracer:s,command:o,target:o.target,cache:p?.target,action:async y=>fle(y.locator,n),options:{...o,allowNotActionableNodesOverride:!0,disableCache:i,memory:p?.target?.memory,disableGlobalLocatorRedirect:!0,source:Zd(o),skipAISmartWaiting:e,targetName:"target"},retriesWithAI:t?1:0});return d={success:h.success,data:h.data,err:h.err,elementInteractedDisplayString:f,thoughts:g},m=!0,h.success||(c.warn({aiThoughts:g,elementString:f,err:h.err},"Element check found an element but failed"),d={...h,thoughts:g}),{result:d,elementWasFound:m}}catch(f){if(u)return d={success:!0,thoughts:`The element described does not exist on the page: ${f.message}`,err:void 0,data:void 0},{result:d,elementWasFound:m};if(!(f instanceof C)||f.reason!="ActionFailureError")throw f;return d={success:!1,err:f,data:void 0,thoughts:void 0},c.warn({err:f},"Element check did not find an element and failed"),{result:d,elementWasFound:m}}}async function fle(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await hle(r,e.assertion)}async function hle(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:Xt(a,500,!0)},!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=Ar(e);t=!1,n=new C("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:Xt(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a=null;try{a=await r.getAttribute(e.attr,{timeout:3e3})}catch(s){n=new C("AssertionFailureError",s instanceof Error?s.message:String(s)),t=!1;break}if(!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=Ar(e);t=!1,e.operation==="EXISTS"?n=new C("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new C("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},ur*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:ur*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:ur*1e3});break}case"FOCUSED":{t=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.condition)}if(t=e.negated?!t:t,!t){let a=Ar(e);n=new C("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=Ar(e);t=!1,n=new C("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,l)=>window.getComputedStyle(s).getPropertyValue(l),e.property);if(!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=Ar(e);t=!1,e.operation==="EXISTS"?n=new C("AssertionFailureError",`The style property ${e.property} ${s}`):n=new C("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function QH(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as gle}from"jimp";async function Gp(r,e){let t=await r.screenshot(e),n=await gle.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as ej}from"jimp";import QC from"jpeg-js";import yle from"pixelmatch";async function tj({tracer:r,command:e,disableCache:t,browser:n,targetingWrapper:o,logger:i,screenshotStorage:a}){if(e.target&&!ha(e.target))throw new Error("Visual Diff with x/y is not supported yet");await n.waitForStability({logger:i});let s={clearHighlights:!0,hideCaret:!0},l;e.target?.elementDescriptor?l=(await o({tracer:r,command:e,target:e.target,cache:e.cache?.target,action:async O=>Gp(n,{locator:O.locator,...s}),options:{...e,disableCache:t,disableGlobalLocatorRedirect:!0,memory:e.cache?.target?.memory,targetName:"target"}})).result:l=await Gp(n,s);let c=await a.prepareGoldenScreenshotForComparison(i,e,l);if((l.height!==c.height||l.width!==c.width)&&i.warn({currHeight:l.height,currWidth:l.width,savedHeight:c.height,savedWidth:c.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-c.height)>10||Math.abs(l.width-c.width)>10){let _=`${l.width}x${l.height}`,O=`${c.width}x${c.height}`;return{fail:!0,thoughts:`Current screenshot (${_}) does not match saved screenshot dimensions (${O}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let u=await ej.fromBuffer(l.buffer),d={width:l.width,height:l.height},m=await ej.fromBuffer(c.buffer),p={width:c.width,height:c.height},f,h=d.width*d.height,g=p.width*p.height,y=Math.abs(d.height-p.height),b=Math.abs(d.width-p.width);if(h>g){let _=u.cover({w:p.width,h:p.height});l.buffer=await _.getBuffer("image/jpeg"),f="current",l.width=p.width,l.height=p.height}else if(g>h){let _=m.cover({w:d.width,h:d.height});c.buffer=await _.getBuffer("image/jpeg"),f="saved"}let E={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=e.threshold??.1,L=yle(QC.decode(c.buffer).data,QC.decode(l.buffer).data,E.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,I=L>v*100,A=`Visual diff of ${L.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${v*100}%.`;if(f&&(A+=` The ${f} screenshot was cropped since it was taller by ${y} pixels and wider by ${b} pixels.`),I)throw new C("ActionFailureError",A);return{fail:I,thoughts:A,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:QC.encode(E,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}var Sle=3e4;function ble(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function $u({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Sle/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([f,h])=>f&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([f,h])=>f&&h).forEach(([f,h])=>{a.append(f,h)});let s=a.toString(),l;if(bu(r.url)&&(l=r.url),t&&Eu(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let c=l;e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let d=await J((async()=>{let f=s?`${c}?${s}`:c;try{let h=ble(r),g=new Headers(i);return h.contentType&&!g.has("Content-Type")&&g.set("Content-Type",h.contentType),await n(f,{headers:g,method:r.method,body:h.content})}catch(h){throw new Error(`Failed to make HTTP request: ${h}`,{cause:h})}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let f;try{f=await d.text()}catch(h){f=`Failed to read response body: ${h}`}throw new C("ActionFailureError",`Fetch request failed with status ${d.status}: ${f}`)}let m={};d.headers.forEach((f,h)=>{m[h]=f});let p={status:d.status,headers:m,request:{url:d.url,method:r.method,headers:i}};if(r.body?.type==="json"&&r.body.content)try{p.request.json=JSON.parse(r.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{p.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(p.text=await d.text());return p}var Ele=5e3;async function nj({timeout:r=ur,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal?.throwIfAborted();let l=Date.now();i=await xS(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await ee(s,e.signal),s=Math.min(Math.floor(s*1.5),Ele);else return i}return i=await xS(e),i}async function xS({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let l=await e.evaluateFunctionInAllFrames(rj,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(rj,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let l=r.negated?ea.CONTAINS:ta.CONTAINS;a=new C("AssertionFailureError",`The page ${l} '${r.value}'.`),o=s}}catch(s){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function rj({value:r,negated:e,returnHtml:t}){let n=document.body.innerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var Tle=3e4;async function oj({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Tle/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(bu(r.url)&&(s=r.url),t&&Eu(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let c=await J((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){throw new Error(`Failed to make HTTP request: ${d}`,{cause:d})}})(),{milliseconds:o*1e3});if(!c)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let d,m=await c.text();try{d=JSON.parse(m)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${c.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let u={};return c.headers.forEach((d,m)=>{u[m]=d}),{status:c.status,headers:u,json:await c.json()}}var _S=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(e,t){this.executionOptionsStack.push(e);try{return await t()}finally{this.executionOptionsStack.pop()}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[l,c]=await Promise.all([Mi(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${c.toString("base64")}`,d=await Cl({type:"ai-action",description:e,screenshot:u,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,u]=await Promise.all([Mi(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await Cl({type:"ai-action",description:e,screenshot:d,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:l,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(a)},langfuseSessionId:s})}catch(f){throw new C("InternalWebAgentError",`Error generating command: ${f instanceof Error?f.message:f}`,{errOptions:{cause:f}})}}async getBrowserState(e){return Mi(this.browser,e)}async locateElement(e){return await ZC({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return vo({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return{browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({tracer:e,command:t,targetNames:n,descriptions:o,caches:i,action:a,options:s,retriesWithAI:l=1}){let c=[];for(let u=0;u<o.length;u++){let d=o[u],m=await this.wrapElementTargetingCommand({tracer:e,command:t,target:d,cache:i[u],action:async p=>p,options:{...s,targetName:n[u]}});c.push(m)}try{let u=await a(...c.map(p=>p.result)),d=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",m=c.map((p,f)=>p.thoughts?`${d(n[f])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:c.map(p=>p.elementInteractedDisplayString),thoughts:m}}catch(u){if(this.throwIfClosed(),l>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:e,command:t,targetNames:n,descriptions:o,caches:o.map(()=>{}),action:a,options:s,retriesWithAI:l-1});throw new C("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapHardcodedCssTargetingCommandHelper({target:e,action:t,options:n,command:o}){let i=this.logger.child({commandId:o.id}),{targetName:a}=n;if(e.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let s,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({selector:e.elementDescriptor,targetName:a,logger:i});return{result:await t({locator:u.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;s=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await ee(500)}}throw s}async scrollIntoViewAndResolveFinalTarget(e){let{resolutionResult:t,disableGlobalLocatorRedirect:n,logger:o}=e,i=Pn(),a=!n&&this.browser.userBrowserSettings.globalLocatorRedirect!==!1;(this.browser.userBrowserSettings.visualActions||a)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(t.locator)});let s;return a&&(s=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:u}=await this.browser.performTargetRedirection(t,o);if(l.result=u,c&&i.storeTraceAsset)try{let d=await this.browser.screenshot({locator:c.locator,clearHighlights:!0}),m=vle();i.storeTraceAsset({snapshotId:m,data:d}),l.elementScreenshotSnapshotId=m}catch(d){o.debug({err:d},"Failed to capture element screenshot for redirect trace")}return c})),s||(s={locator:t.locator,serverSideBoundingBox:await t.locator.boundingBox({timeout:fe}),originalElementLocationResult:t.originalElementLocationResult}),s}async resolveCachedTargetForAction(e){let{cache:t,options:n,logger:o}=e,a=await Pn().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=t.targetSource;try{let c=await this.browser.resolveTarget(t,{allowNotActionableNodesOverride:n.allowNotActionableNodesOverride,logger:o,signal:this.executeAbortController.signal,...n.resolveTargetOptions});l.attributes.targetDisplayString=c.displayString,l.attributes.decisions=c.decisions;let u=c.decisions.find(d=>d.matched);return u&&(l.resolutionMethod=u.type),c}catch(c){throw c instanceof Ze&&(l.cacheMissReason=c.cacheMissReason,l.attributes.decisions=c.decisions),c}}),s=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:a,disableGlobalLocatorRedirect:n.disableGlobalLocatorRedirect,logger:o});return await a.revalidator?.(),{resolutionResult:a,finalTarget:s}}async wrapElementTargetingCommand(e){return await vo({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(e){let{tracer:t,target:n,action:o,options:i,command:a,finalAttempt:s=!1,originalCache:l=e.cache}=e,{retriesWithAI:c=1}=e,{disableCache:u,useSelector:d,targetName:m}=i,p=Pn(),f=this.logger.child({commandId:a.id}),h=this.shouldUseMemory(),g=ij(e.cache);if((!g||u)&&!ZE(n))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);let y=!1,b;u&&(f.info("Cache explicitly disabled for this step"),y=!0,b="Cache explicitly disabled",g=void 0);let E=zH({cache:g,description:n.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:f});g=E.cache,y=y||E.cacheBustedBeforeAction,!b&&E.cacheBustReason&&(b=E.cacheBustReason);let v=!0;if(!BH(g))return c--,v=!1,this.executeTargetingCommandWithAI({tracer:p,stepTracer:t,target:n,options:i,command:a,action:o,originalCache:l,logger:f,useMemory:h,cacheBustedBeforeAction:y,cacheBustReason:b});try{let{resolutionResult:w,finalTarget:L}=await this.resolveCachedTargetForAction({cache:g,options:i,logger:f}),I=await o(L);if(gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.59.0"]),uy({cmd:a,key:m,newTarget:g,logger:f,updatedWithAI:!1}),v){let A=w.decisions.filter(_=>_.matched);if(A.length!==1)f.warn({decisions:w.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let _=A[0].type;t.recordTargetAutoHeal({healType:_})}}return{result:I,elementInteractedDisplayString:w.displayString}}catch(w){this.throwIfClosed();let L=uT(w);if(L&&!s)return f.warn({err:w},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:t,command:a,target:n,action:o,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:!0,options:i});if(w instanceof C&&!L)throw f.warn({err:w},"Failed to execute command with target (fatal)"),w;if(c>0&&n){f.info({err:w},"Failed to execute action with cached target, retrying with AI"),gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.59.0",`missReason:${w instanceof Ze?w.cacheMissReason:"unknown"}`]);let I;return g.memory&&OM(g.memory)&&(I=g.memory),this.wrapElementTargetingCommandHelper({tracer:t,command:a,target:n,cache:void 0,action:o,originalCache:l,retriesWithAI:c,finalAttempt:!0,options:{...i,memory:I,targetHealingInProgress:!0}})}throw new C("ActionFailureError",`Failed to execute interactive command: ${w instanceof Error?w.message:`${w}`}`,{errOptions:{cause:w}})}}async executeTargetingCommandWithAI(e){let{tracer:t,stepTracer:n,target:o,options:i,command:a,action:s,originalCache:l,logger:c,useMemory:u,cacheBustedBeforeAction:d,cacheBustReason:m}=e;c.info({description:o.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:d,memory:i.memory,useMemory:u},"Prompting AI for an updated element location"),(d||!l)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?await t.startAsyncSpan("SMART_WAITING",async()=>await YH({description:o.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())):(d||!l)&&(i.skipAISmartWaiting?c.debug("Skipping AI smart waiting for this targeting attempt"):c.debug("Skipping AI smart waiting due to controller execution options"));let p=2;for(let f=1;f<=p;f++){let h=!1,g=this.browser.getActiveFrameConfig();try{let y;try{y=await ZC({description:o.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:u,memory:u?i.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,logger:c,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:m},this.getControllerFixtures())}catch(v){if(v instanceof ni&&v.updatedLocatorMemory){let w={id:-1,...l,memory:v.updatedLocatorMemory};uy({cmd:a,key:i.targetName,newTarget:w,logger:c,updatedWithAI:!0})}throw v}y.frameConfig&&(this.browser.setActiveFrameConfig(y.frameConfig),h=!0);let b=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:y.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),E=await s(b);return uy({cmd:a,key:i.targetName,newTarget:y.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(n.recordTargetAutoHeal({healType:"AI"}),y.target.targetSource="AI_HEALED",y.target.targetUpdateTime=new Date().toUTCString(),y.target.targetUpdateLoggerTags=Ee(c)),{result:E,elementInteractedDisplayString:y.resolution.displayString,thoughts:y.thoughts}}catch(y){if(h&&this.browser.setActiveFrameConfig(g),this.throwIfClosed(),f<p&&uT(y)){c.warn({err:y,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw y instanceof C?y:new C("ActionFailureError",y.message)}}throw new C("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(e){return Gp(this.browser,e)}async executePresetCommand(e,t,n,o){this.options?.slowMoMs&&await ee(this.options.slowMoMs);let i=await this.browser.getOpenPages(),a=this.browser.url(),s;try{s=await this.resolveCommandTemplateStrings(t,n)}catch(l){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o);return this.options?.autoFollowNewTabs&&await UH({beforeUrl:a,command:t,beforePages:i.map(c=>c.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{Ou(t,s)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>bC(e)}}async traceBrowserInteraction(e,t,n){return Pn().startAsyncSpan("BROWSER_INTERACTION",async()=>t(),{name:e,...n})}async resolveCommandTemplateStrings(e,t){return Iu({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o){o=o||"disableCache"in t&&!!t.disableCache;let i=this.logger.child({commandId:t.id});switch(t.type){case"SUCCESS":{let a=t.condition;return a?.assertion.trim()?CS({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AI_ASSERTION":{if(!t.assertion.trim())throw new C("ActionFailureError","Missing assertion");if(t.timeout&&t.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);return CS({command:t,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!t.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let l=Yc(t.schema);if(l)throw new C("UserConfigurationError",l)}let a=await this.browser.getCondensedHtml(),s=await this.browser.screenshot({retries:2});try{let l=await this.generator.getTextExtraction({goal:t.goal,browserState:a,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${s.toString("base64")}`},{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:Ee(i)});if(l.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(l.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",l.thoughts);return{thoughts:l.thoughts||void 0,data:l.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(l){let c=l.message;throw c.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):c.includes("AIProviderError")&&c.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:l}}):l}}case"NAVIGATE":if(!bu(t.url)&&!Eu(t.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${t.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:t.url,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0}));break;case"DIALOG":this.browser.registerDialogHandler(t.action);break;case"CAPTCHA":throw new C("UserConfigurationError","Captcha solving is no longer available on Momentic");case"GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case"GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let a,s;if(t.target&&ti(t.target))await this.browser.hoverUsingVisualCoordinates(t.target.pixels);else if(t.target&&t.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:d}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:m=>this.browser.hover(m),options:{...t,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:o}});a=u,s=d}let l=this.browser.getViewport()?.height??ba.height,c=this.browser.getViewport()?.width??ba.width;switch(t.type){case"SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(t.deltaY??l)));break;case"SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(t.deltaY??l));break;case"SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(t.deltaX??c)));break;case"SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(t.deltaX??c));break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"WAIT_FOR_URL":{if(t.timeout&&t.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=t.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:t.timeout?t.timeout*1e3:void 0,negated:t.negated,caseInsensitive:t.caseInsensitive});break}case"WAIT":{if(t.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${t.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=t.delay*1e3;await ee(a,this.executeAbortController.signal);break}case"REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0}));break;case"CLICK":{if(ti(t.target)){let{pixels:d}=t.target;await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(d,t),{coordinates:d});break}let a=this.browser.url(),{elementInteractedDisplayString:s,result:l,thoughts:c}=await this.wrapElementTargetingCommand({tracer:e,target:t.target,command:t,cache:t.cache?.target,action:d=>this.traceBrowserInteraction("Click",()=>this.browser.click(d,this.createCallbacksForBrowser(this.orgId),t),{selector:d.locator.toString()}),options:{disableCache:o,targetName:"target",...t}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:c,data:l.downloadedFile?{downloadedFile:l.downloadedFile}:void 0};return wy(a,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"COPY":return await this.browser.copy(t.value),{succeedImmediately:!1,data:t.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(ti(t.fromTarget)&&ti(t.toTarget)){let l=t.fromTarget.pixels,c=t.toTarget.pixels;await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(l,c,{hoverDurationMs:t.hoverSeconds?t.hoverSeconds*1e3:void 0}),{coordinates:l});break}if(ti(t.fromTarget)||ti(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:s}=await this.wrapMultiElementTargetingCommand({tracer:e,command:t,targetNames:["fromTarget","toTarget"],descriptions:[t.fromTarget,t.toTarget],caches:[t.cache?.fromTarget,t.cache?.toTarget],action:(l,c)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(l,c,{hoverDurationMs:t.hoverSeconds?t.hoverSeconds*1e3:void 0,steps:t.steps})),options:{useSelector:!!t.useSelector,disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:s}}case"MOUSE_DRAG":{let a=parseInt(t.deltaX),s=parseInt(t.deltaY),l=t.steps??5;if(isNaN(a)||isNaN(s))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);if(t.target&&ti(t.target)){let d=t.target.pixels;await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:s,steps:l,fromTarget:d}),{coordinates:d});break}let c,u;if(t.target?.elementDescriptor){let{elementInteractedDisplayString:d,thoughts:m}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async p=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,l,p.locator,{force:t.force})),options:{disableCache:o,targetName:"target",...t}});c=d,u=m}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,l,void 0,{force:t.force}));return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:u}}case"SELECT_OPTION":{if(!ha(t.target))throw new Error("Select with x/y is not supported yet");let a=t.target.elementDescriptor,s=t.choice,{elementInteractedDisplayString:l,thoughts:c}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:{type:"description",elementDescriptor:a},cache:t.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,s,t.force),{value:s.type==="LABEL"?s.label:s.type==="VALUE"?s.value:s.index}),options:{...t,targetName:"target",disableCache:o,source:Zd(t)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:l,thoughts:c}}case"TAB":{let a={loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(t.action,a);break}case"NEW_TAB":await this.browser.createNewTab(t.url,{loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"COOKIE":{if(!t.value)break;let a=await this.browser.setCookie(t.value);i.debug({results:a},"Set cookies");break}case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let a;try{t.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:t.code,fragment:t.fragment??!1,context:n.toObjectCopy(),timeoutMs:t.timeout?t.timeout*1e3:void 0}),i.info({result:a},"Executed JavaScript in browser")):a=await bo({orgId:this.orgId,code:t.code,fragment:!!t.fragment,context:n,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async s=>{if(!this.options?.scratchPadId){i.warn({updates:s},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:s,logger:i})}}})}catch(s){throw this.throwIfClosed(),new C("ActionFailureError",s instanceof Error?s.message:`${s}`,{errOptions:{cause:s}})}try{JSON.stringify(a)}catch(s){throw new C("ActionFailureError",`Return value is not serializable: ${s instanceof Error?s.message:`${s}`}`,{errOptions:{cause:s}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:a}}case"TYPE":{if(t.target&&ti(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.pixels,t),await this.traceBrowserInteraction("Type",()=>this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter},!0),{value:t.value});break}let a=this.browser.url(),s,l,c=ij(t.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(c){let{elementInteractedDisplayString:m,thoughts:p}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:c,cache:t.cache?.target,action:f=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(t.value,f,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter,relativePosition:t.relativePosition}),{value:t.value,selector:f.locator.toString()}),options:{...t,targetName:"target",disableCache:o,disableGlobalLocatorRedirect:!u,source:Zd(t)}});s=m,l=p}else await this.traceBrowserInteraction("Type",()=>this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter},!0),{value:t.value});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:l};return wy(a,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d}case"HOVER":{if(ti(t.target)){let{pixels:l}=t.target;await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(l),{coordinates:l});break}let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:l=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(l),{selector:l.locator.toString()}),options:{...t,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"FOCUS":{if(!ha(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:l=>this.browser.focus(l),options:{...t,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"BLUR":{if(t.target&&!ha(t.target))throw new Error("Blur with x/y is not supported yet");if(!t.target||!t.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,target:t.target,command:t,cache:t.cache?.target,action:l=>this.browser.blur(l),options:{...t,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(t.value,{repeat:t.repeat,convertMeta:t.convertMeta??!0,delayMs:t.delayMs}),{value:t.value});let s={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return wy(a,s.urlAfterCommand)&&(s.succeedImmediately=!0,s.succeedImmediatelyReason="URL changed"),s}case"KEY_DOWN":return await this.browser.keyDown(t.value,{convertMeta:t.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(t.value,{convertMeta:t.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let a=new wle,s=Ale(fetch,a),l;try{l=new URL(t.url).hostname}catch{}let c=await $u({command:t,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:s});return{data:Is.parse({...c,cookies:Dc(a,l)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await oj({command:t,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return tj({tracer:e,command:t,disableCache:o,browser:this.browser,logger:i,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case"FILE_UPLOAD":{let a,s;if(t.fileSource.type==="URL"?(s=t.fileSource.url,a=await f$({uri:t.fileSource.url,logger:i,orgId:this.orgId})):t.fileSource.type==="USER_FILE"&&(s=t.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(t.fileSource.name,this.orgId)),!a)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${s}`);await this.browser.setFileChooserHandler({...a,filename:t.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let a;if(!t.storageState.trim())a=void 0;else if(a=await bo({orgId:this.orgId,code:t.storageState,fragment:!1,context:n,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let s;try{s=QO.optional().parse(a)}catch(l){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${l}`)}await this.browser.loadAuthState(s);break}case"ELEMENT_CHECK":{let a=(t.timeout??ur)*1e3,s=this.generator.getAgentConfig()?.assertion;if(QH(t.assertion)&&!t.useSelector&&t.target.type==="description"&&s&&s!=="v1"){let c={id:t.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${t.target.elementDescriptor}`,iframeUrl:t.iframeUrl,timeout:t.timeout,source:"NEGATED_CHECK",cache:t.cache&&"memory"in t.cache?{memory:t.cache?.memory}:void 0};try{let u=await CS({command:c,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory()});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${u.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:u.afterScreenshotOverride}}finally{c.cache?.memory&&bp(t,c.cache?.memory.traces,i)}}let l=await ZH({command:t,tracer:e,timeoutMs:a,targetingWrapper:c=>this.wrapElementTargetingCommand(c),fixtures:this.getControllerFixtures(),disableCache:o});return{fail:!l.success,data:l.data,elementInteracted:l.elementInteractedDisplayString,thoughts:l.err?.message??l.thoughts??`Element assertion ${l.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let a=await vo({action:async()=>nj({assertion:t.assertion,browser:this.browser,logger:i,timeout:t.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!a.success,data:a.data,thoughts:a.success?"Page assertion passed.":a.err?.message??`Page assertion still failing after ${t.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let a=new ns(t.requestMatcher),s=this.browser.registerRequestListener(a);return this.registeredListeners[t.key]=s.then(async l=>await wC(l)).catch(l=>{i.error({err:l},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let a=this.registeredListeners[t.key];if(!a)throw new C("ActionFailureError",`No listener registered with key: ${t.key}`);let s=t.timeout??10;return{data:await J(a,{milliseconds:s*1e3,message:`Request listener timed out after ${s} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let a=new ns(t.requestMatcher);return this.recordedRequests[t.key]={},this.browser.registerRequestRecorder(t.key,{matches:s=>a.matches({url:s.request.url,method:s.request.method}),onRequestStart:(s,l)=>{this.recordedRequests[t.key][s]=pS(l)},onRequestComplete:(s,l)=>{this.recordedRequests[t.key]?.[s]&&(this.recordedRequests[t.key][s]=pS(l))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let a=this.recordedRequests[t.key];if(!a)throw new C("ActionFailureError",`No recorder registered with key: ${t.key}`);return delete this.recordedRequests[t.key],{data:Object.values(a),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let a;return t.requestMatcher&&(a=new ns(t.requestMatcher)),this.browser.setHeader(t.name,t.value,a),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(t.key,new ns(t.requestMatcher),async(s,l)=>{let c=await bo({orgId:this.orgId,code:t.responseGenerator,fragment:!1,context:n,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:s,response:l},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),u=NN.parse(c);return new Response(u.body,{status:u.status,headers:u.headers})},t.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(t.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(t.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Ee(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new bS({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ee(this.logger)})}async getFailureRecoveryPlan(e,t){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ee(t??this.logger)})}};import{mkdirSync as Wle}from"fs";import{tmpdir as Vle}from"os";import hj from"path";import{diff as Gle}from"deep-object-diff";import{cloneDeep as tR}from"lodash-es";import uj from"fontoxpath";import Cle from"@prettier/plugin-xml";import Rle from"prettier";import{DOMParser as xle,XMLSerializer as _le}from"slimdom";var Mle=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function Ple(r){let e=r.toLowerCase();return e.endsWith("webview")||Mle.has(e)}function Wp(r){return!!(Ple(r.tagName)||r.getAttribute("package")==="com.android.chrome"&&r.getAttribute("content-desc")==="Web View"&&aj(r.tagName.toLowerCase()).startsWith("frame"))}function aj(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var Ile=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Ole=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),Nle=new Set(["text","hint"]),Lle=new Set(["live-region","drawing-order"]),Dle=new Set(["displayed","enabled"]);function kle(r,e){let t={};for(let[n,o]of Object.entries(e))Ile.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Ole.has(n)&&o==="false"||Nle.has(n)&&o===""||Dle.has(n)&&o==="true"||Lle.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function sj(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,l=a.value++;t.setAttribute("id",String(l));let c={};for(let m of e.attributes){let p=m.name,f=m.value;f!=null&&(c[p]=String(f))}let u=kle(e.tagName,c);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(l,e),i.set(l,t),Wp(e)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
4884
+ `),tokenLength:d}),s.forEach((h,g)=>{let y=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:y,maxId:b},`Chunk for page filtering (index ${g+1}/${s.length})`)}),{chunks:s}}var rle=75e4,wS=3e5;async function Cl(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:l}=t,c=r.tree,u=r.serializedTree,d=mo(u);if(d>rle)try{let m=AS({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});c=await ole({...r,tokenLimit:wS-1e4,chunks:m.chunks}),u=c.serialize();let p=mo(u);i.info({oldTokens:d,newTokens:p},"Filtered page using keywords"),d=p}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),c=c.pruneToSerializedCharLimit(wS*ja),u=c.serialize();let p=mo(u);i.info({oldTokens:d,newTokens:p},"Filtered page using naive truncation"),d=p}if(d>wS)try{if(o){let m=AS({serializedTree:u,options:jH,logger:i}),p=tle();c=await J(nle({...r,chunks:m.chunks,callId:p}),{milliseconds:12e3,signal:l}),u=c.serialize();let f=mo(u);i.info({oldTokens:d,newTokens:f,langfuseCallId:p},"Filtered page using AI chunk ranking"),d=f}else{let m=AS({serializedTree:u,options:HH,logger:i});c=await J(ile({...r,chunkResult:m,tokenLimit:4e4}),{milliseconds:12e3,signal:l}),u=c.serialize();let p=mo(u);i.info({oldTokens:d,newTokens:p},"Filtered page using RAG"),d=p}}catch(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),c=c.pruneToSerializedCharLimit(wS*ja),u=c.serialize(),i.info("Filtered page using naive truncation")}return u}async function nle({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:l}=o,c=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:l,loggerTags:Ee(l)}),u=[];return t.forEach((m,p)=>{c.indices.includes(p)&&(u=u.concat(m.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function ole(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:Ee(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let l of s.keywords){let c=r.chunks.filter(p=>p.content.toLowerCase().includes(l.toLowerCase()));if(!c.length||c.reduce((p,f)=>p+f.tokenLength,0)>r.tokenLimit&&c.length>1)continue;let d=c.flatMap(p=>p.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function ile(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:s,signal:l}=t,c=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:l,logger:s,loggerTags:Ee(s)});if(c.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(c.ids.map(d=>`${d}`)))}async function ZC(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return vo({action:async()=>ale(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function ale(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:l,logger:c,allowNotActionableNodesOverride:u,skipSavingVisualAttributes:d,isAutoHeal:m,cacheBustReason:p}=r,{orgId:f,browser:h,localCodeEvalTools:g,generator:y,abortSignal:b}=e,E=r.description,v=Pn(),w=r.useMemory&&!t;n&&(E=await bl({orgId:f,s:E,context:n,localTools:g,signal:b,logger:c})),a&&(E=FH(E,a));let{serializedTree:L,tree:I}=await v.startAsyncSpan("GET_PAGE_STATE",async()=>Mi(h,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:b,skipWait:i,logger:c}),{}),A=await v.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let ie,se=Date.now(),Pe;for(;!ie&&Date.now()-se<3e3;){b.throwIfAborted();try{ie=await h.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(we){Pe=we}}if(!ie)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${Pe?.message}`);return ie}),_=L,O=!1,D=`data:image/jpeg;base64,${A.toString("base64")}`;_=await Cl({type:"locator",description:E,screenshot:D,serializedTree:L,options:{aiPageFiltering:l},tree:I,fixtures:{generator:y,signal:b,logger:c,orgId:f}}),_!==L&&(O=!0);let j=await v.startAsyncSpan("AI_LOCATOR_CALL",async ie=>{m&&(ie.attributes.isAutoHeal=!0),p&&(ie.attributes.cacheBustReason=p);let se=await y.getElementLocation({browserState:_,goal:E,screenshot:D,source:a,memory:w?s:void 0},{disableCache:t,abortSignal:b,loggerTags:Ee(c),useMemory:w});if(ie.result=se,v.storeTraceAsset){let Pe=WH();v.storeTraceAsset({snapshotId:Pe,data:A}),ie.screenshotSnapshotId=Pe}return se});if(c.debug({usedRag:O,result:j},"Got locator result"),!(j.id>0))throw new ni(`Could not find any relevant element: ${j.thoughts}`,j.updatedMemory?{type:"GCS_TRACES",traces:j.updatedMemory}:void 0);let{resolution:xe,target:B,frameConfig:Z}=await v.startAsyncSpan("TARGET_RESOLUTION",async ie=>{let se=await h.createTargetFromA11yId({id:j.id,requirements:j.requirements,additionalElements:j.additionalElements,description:E,targetSource:"AI",logger:c,skipSavingVisualAttributes:d});if(ie.result={serializedElement:se.target.nodeOnlySerializedHtml??"Unknown HTML element"},v.storeTraceAsset)try{let Pe=await h.screenshot({locator:se.resolution.locator,clearHighlights:!0}),we=WH();v.storeTraceAsset({snapshotId:we,data:Pe}),ie.elementScreenshotSnapshotId=we}catch(Pe){c.debug({err:Pe},"Failed to capture element screenshot for locator trace, continuing...")}return se});if(xe.a11yNode?.properties?.hidden&&xe.a11yNode?.properties?.hidden!=="false")throw new C("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${xe.displayString}`);return w&&(j.updatedMemory?B.memory={type:"GCS_TRACES",traces:j.updatedMemory}:s&&(B.memory=s)),{thoughts:j.thoughts,target:B,resolution:xe,frameConfig:Z,screenshot:D}}import{randomUUID as VH}from"crypto";var sle=15;async function CS({command:r,aiPageFiltering:e,logger:t,fixtures:n,useMemory:o,maxRetries:i=sle}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let a=kT.optional().catch(void 0).parse(r.source);r.source&&!a&&t.warn(`Invalid source ${r.source} for AI assertion, ignoring...`);let s=Pn();return s.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,u=r.timeout?r.timeout*1e3:c.smartWaitingTimeout,d=FU(u,i-1),m=0,p=Date.now(),f=p+u,h=p,g,y,b;try{await vo({action:()=>c.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:c,logger:t})}catch(w){t.warn({err:w},"Failed to clear highlights before AI check, continuing...")}for(;m<i;){n.abortSignal.throwIfAborted();let w=Date.now();if(m>0){if(w>=f)break;let A=f-w,_=h-w,O=Math.min(_,A);O>0&&await ee(O,n.abortSignal)}let L=Date.now();if(m>0&&L>=f)break;let I=!1;try{if(g=await vo({action:async()=>{let _=await qH(c,t,n.abortSignal);return y&&y.serializedTree===_.serializedTree&&y.screenshotBuff.equals(_.screenshotBuff)?(I=!0,g):(y=_,KH({command:r,state:_,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:m,aiPageFiltering:e,logger:t,source:a}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:c}),g?.success){g?.updatedMemory&&bp(r,g.updatedMemory,t);break}else throw g?.thoughts?new C("AssertionFailureError",g.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(A){n.abortSignal.throwIfAborted(),b=A instanceof Error?A:new Error(`${A}`),I?t.info(`AI check attempt ${m} failed (re-used previous result)`):t.info({err:A},`AI check assert attempt ${m} failed, retrying...`)}finally{m++,h=L+d}}if(!g?.success){let w=f-Date.now();w>0&&await ee(w,n.abortSignal)}if(!g?.success)try{g=await vo({action:async()=>KH({command:r,state:await qH(c,t,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:m,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:c})}catch(w){n.abortSignal.throwIfAborted(),b=w instanceof Error?w:new Error(`${w}`)}finally{m++}g?.updatedMemory&&bp(r,g.updatedMemory,t);let E=g?.afterScreenshotOverride;if(E&&s.storeTraceAsset){let w=VH();s.storeTraceAsset({snapshotId:w,data:E}),l.screenshotSnapshotId=w}let v=g?.elementScreenshotOverride;if(v&&s.storeTraceAsset){let w=VH();s.storeTraceAsset({snapshotId:w,data:v}),l.elementScreenshotSnapshotId=w}if(!g?.success){l.result={thoughts:b?.message??"AI check failed after all attempts",result:!1};let w=`AI check still failing after ${m} attempts.`;throw b&&(w+=` Latest result: ${b.message}`),new C("AssertionFailureError",w)}return l.result={thoughts:g.thoughts,result:!0},{...g,succeedImmediately:!1,urlAfterCommand:c.url()}})}async function qH(r,e,t){await r.waitForPageLoad({signal:t});let[n,o]=await Promise.all([Mi(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function KH({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:l,logger:c}){let{browser:u,generator:d,abortSignal:m}=t,p={type:"ASSERTION"},{serializedTree:f,tree:h}=e,g=e.screenshotBuff,y=g.toString("base64"),b=u.url(),E=r.contextChoice??"MULTIMODAL",v=f;E!=="VISION_ONLY"&&(v=await Cl({type:"assertion",serializedTree:f,tree:h,description:r.assertion,screenshot:y,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:c,orgId:t.orgId}}),v!==f&&(p.ragUsed=!0),p.pageState=v);let w={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:y,contextChoice:E,source:l},I=await(E==="VISION_ONLY"?(_,O)=>d.getVisualAssertionResult(_,O):(_,O)=>d.getAssertionResult(_,O))(w,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:c,loggerTags:Ee(c)}),A;if((I.result||i)&&I.relevantElements?.length){p.relevantElementsSerialized=I.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_);try{let _=I.relevantElements[0],{resolution:O}=await u.createTargetFromA11yId({id:_,description:null,targetSource:"AI",skipSaveToCache:!0});A=await u.screenshot({locator:O.locator,clearHighlights:!0,respectActiveFrame:!0})}catch(_){c.debug({err:_},"Failed to capture element screenshot for trace, continuing...")}await lle(I.relevantElements,u,c)}return{success:I.result,thoughts:I.thoughts,afterScreenshotOverride:g,elementScreenshotOverride:A,updatedMemory:o?I.updatedMemory:void 0}}async function lle(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await J(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var cle=1e5,RS=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function YH(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await ule(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof RS?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await ee(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function ule(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await ee(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await J(dle(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function dle(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await vo({action:async()=>mle(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function mle(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:l,orgId:c,generator:u}=e,d=r.description;t&&(d=await bl({orgId:c,s:d,context:t,localTools:l,signal:s,logger:n}));let{serializedTree:m}=await Mi(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(mo(m)>cle)throw new RS;s.throwIfAborted();let f;try{f=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let g=`data:image/jpeg;base64,${f.toString("base64")}`;s.throwIfAborted();let y=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:g},{abortSignal:s,loggerTags:Ee(n)});return n.debug({result:y},"Got smart waiting result"),y.isPageReady}import{cloneDeep as JH}from"lodash-es";async function ZH(r){return Pn().startAsyncSpan("ELEMENT_ASSERTION",async t=>ple(r,t),{name:"Element check"})}async function ple(r,e){let{command:t,timeoutMs:n,fixtures:o,disableCache:i}=r,{abortSignal:a}=o,s=()=>rh(t.cache)?t.cache:void 0,l=s(),c=!i&&!!l?.target&&tc(l.target),u=JH(l),d=(b=!1)=>{if(l=s(),!!l)if(b){let E=qF(u,l);l.target=E.target,l.updatedAt=E.updatedAt}else{if(!u){l=void 0;return}l.target=u.target,l.updatedAt=u.updatedAt}},m=Date.now(),p=0,f,h=500,g=!1;for(;p<2||Date.now()-m<n;){p++,p>1&&await ee(h,a),a?.throwIfAborted(),l=s();let b=p===1,{result:E,elementWasFound:v}=await XH({cacheToUse:l,skipAISmartWaiting:!b,useAIIfCacheFails:!c,params:r});if(f=E,g=g||v,E.success)break;d(),h=Math.min(h*1.25,1e4)}if(!f)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${n}ms.`);if(a?.throwIfAborted(),!f.success){let b=s(),E=b?.target?.memory?{target:{id:-1,memory:b.target.memory}}:void 0,{result:v,elementWasFound:w}=await XH({cacheToUse:E,skipAISmartWaiting:!0,useAIIfCacheFails:!0,params:r});f=v,g=g||w,f.success||d(!0)}let y=s();return f.success&&y?.target&&!g&&(y.target=mw(y.target),y.updatedAt=new Date),e.result={success:f.success,message:f.err?.message},f}async function XH({cacheToUse:r,skipAISmartWaiting:e,useAIIfCacheFails:t,params:n}){let{command:o,disableCache:i,fixtures:a,tracer:s,targetingWrapper:l}=n,{logger:c}=a;if(o.target&&!ha(o.target))throw new Error("Element assertion with x/y is not supported yet");let u=yu(o.assertion),d,m=!1,p=JH(r);try{let{elementInteractedDisplayString:f,result:h,thoughts:g}=await l({tracer:s,command:o,target:o.target,cache:p?.target,action:async y=>fle(y.locator,n),options:{...o,allowNotActionableNodesOverride:!0,disableCache:i,memory:p?.target?.memory,disableGlobalLocatorRedirect:!0,source:Zd(o),skipAISmartWaiting:e,targetName:"target"},retriesWithAI:t?1:0});return d={success:h.success,data:h.data,err:h.err,elementInteractedDisplayString:f,thoughts:g},m=!0,h.success||(c.warn({aiThoughts:g,elementString:f,err:h.err},"Element check found an element but failed"),d={...h,thoughts:g}),{result:d,elementWasFound:m}}catch(f){if(u)return d={success:!0,thoughts:`The element described does not exist on the page: ${f.message}`,err:void 0,data:void 0},{result:d,elementWasFound:m};if(!(f instanceof C)||f.reason!="ActionFailureError")throw f;return d={success:!1,err:f,data:void 0,thoughts:void 0},c.warn({err:f},"Element check did not find an element and failed"),{result:d,elementWasFound:m}}}async function fle(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await hle(r,e.assertion)}async function hle(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:Xt(a,500,!0)},!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=Ar(e);t=!1,n=new C("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:Xt(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a=null;try{a=await r.getAttribute(e.attr,{timeout:3e3})}catch(s){n=new C("AssertionFailureError",s instanceof Error?s.message:String(s)),t=!1;break}if(!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=Ar(e);t=!1,e.operation==="EXISTS"?n=new C("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new C("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},ur*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:ur*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:ur*1e3});break}case"FOCUSED":{t=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.condition)}if(t=e.negated?!t:t,!t){let a=Ar(e);n=new C("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=Ar(e);t=!1,n=new C("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,l)=>window.getComputedStyle(s).getPropertyValue(l),e.property);if(!pn(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=Ar(e);t=!1,e.operation==="EXISTS"?n=new C("AssertionFailureError",`The style property ${e.property} ${s}`):n=new C("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function QH(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as gle}from"jimp";async function Gp(r,e){let t=await r.screenshot(e),n=await gle.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as ej}from"jimp";import QC from"jpeg-js";import yle from"pixelmatch";async function tj({tracer:r,command:e,disableCache:t,browser:n,targetingWrapper:o,logger:i,screenshotStorage:a}){if(e.target&&!ha(e.target))throw new Error("Visual Diff with x/y is not supported yet");await n.waitForStability({logger:i});let s={clearHighlights:!0,hideCaret:!0},l;e.target?.elementDescriptor?l=(await o({tracer:r,command:e,target:e.target,cache:e.cache?.target,action:async O=>Gp(n,{locator:O.locator,...s}),options:{...e,disableCache:t,disableGlobalLocatorRedirect:!0,memory:e.cache?.target?.memory,targetName:"target"}})).result:l=await Gp(n,s);let c=await a.prepareGoldenScreenshotForComparison(i,e,l);if((l.height!==c.height||l.width!==c.width)&&i.warn({currHeight:l.height,currWidth:l.width,savedHeight:c.height,savedWidth:c.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-c.height)>10||Math.abs(l.width-c.width)>10){let _=`${l.width}x${l.height}`,O=`${c.width}x${c.height}`;return{fail:!0,thoughts:`Current screenshot (${_}) does not match saved screenshot dimensions (${O}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let u=await ej.fromBuffer(l.buffer),d={width:l.width,height:l.height},m=await ej.fromBuffer(c.buffer),p={width:c.width,height:c.height},f,h=d.width*d.height,g=p.width*p.height,y=Math.abs(d.height-p.height),b=Math.abs(d.width-p.width);if(h>g){let _=u.cover({w:p.width,h:p.height});l.buffer=await _.getBuffer("image/jpeg"),f="current",l.width=p.width,l.height=p.height}else if(g>h){let _=m.cover({w:d.width,h:d.height});c.buffer=await _.getBuffer("image/jpeg"),f="saved"}let E={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=e.threshold??.1,L=yle(QC.decode(c.buffer).data,QC.decode(l.buffer).data,E.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,I=L>v*100,A=`Visual diff of ${L.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${v*100}%.`;if(f&&(A+=` The ${f} screenshot was cropped since it was taller by ${y} pixels and wider by ${b} pixels.`),I)throw new C("ActionFailureError",A);return{fail:I,thoughts:A,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:QC.encode(E,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}var Sle=3e4;function ble(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function $u({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Sle/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([f,h])=>f&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([f,h])=>f&&h).forEach(([f,h])=>{a.append(f,h)});let s=a.toString(),l;if(bu(r.url)&&(l=r.url),t&&Eu(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let c=l;e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let d=await J((async()=>{let f=s?`${c}?${s}`:c;try{let h=ble(r),g=new Headers(i);return h.contentType&&!g.has("Content-Type")&&g.set("Content-Type",h.contentType),await n(f,{headers:g,method:r.method,body:h.content})}catch(h){throw new Error(`Failed to make HTTP request: ${h}`,{cause:h})}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let f;try{f=await d.text()}catch(h){f=`Failed to read response body: ${h}`}throw new C("ActionFailureError",`Fetch request failed with status ${d.status}: ${f}`)}let m={};d.headers.forEach((f,h)=>{m[h]=f});let p={status:d.status,headers:m,request:{url:d.url,method:r.method,headers:i}};if(r.body?.type==="json"&&r.body.content)try{p.request.json=JSON.parse(r.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{p.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(p.text=await d.text());return p}var Ele=5e3;async function nj({timeout:r=ur,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal?.throwIfAborted();let l=Date.now();i=await xS(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await ee(s,e.signal),s=Math.min(Math.floor(s*1.5),Ele);else return i}return i=await xS(e),i}async function xS({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let l=await e.evaluateFunctionInAllFrames(rj,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(rj,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let l=r.negated?ea.CONTAINS:ta.CONTAINS;a=new C("AssertionFailureError",`The page ${l} '${r.value}'.`),o=s}}catch(s){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function rj({value:r,negated:e,returnHtml:t}){let n=document.body.innerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var Tle=3e4;async function oj({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Tle/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(bu(r.url)&&(s=r.url),t&&Eu(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let c=await J((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){throw new Error(`Failed to make HTTP request: ${d}`,{cause:d})}})(),{milliseconds:o*1e3});if(!c)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let d,m=await c.text();try{d=JSON.parse(m)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${c.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let u={};return c.headers.forEach((d,m)=>{u[m]=d}),{status:c.status,headers:u,json:await c.json()}}var _S=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(e,t){this.executionOptionsStack.push(e);try{return await t()}finally{this.executionOptionsStack.pop()}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[l,c]=await Promise.all([Mi(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${c.toString("base64")}`,d=await Cl({type:"ai-action",description:e,screenshot:u,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,u]=await Promise.all([Mi(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await Cl({type:"ai-action",description:e,screenshot:d,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:l,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(a)},langfuseSessionId:s})}catch(f){throw new C("InternalWebAgentError",`Error generating command: ${f instanceof Error?f.message:f}`,{errOptions:{cause:f}})}}async getBrowserState(e){return Mi(this.browser,e)}async locateElement(e){return await ZC({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return vo({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return{browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({tracer:e,command:t,targetNames:n,descriptions:o,caches:i,action:a,options:s,retriesWithAI:l=1}){let c=[];for(let u=0;u<o.length;u++){let d=o[u],m=await this.wrapElementTargetingCommand({tracer:e,command:t,target:d,cache:i[u],action:async p=>p,options:{...s,targetName:n[u]}});c.push(m)}try{let u=await a(...c.map(p=>p.result)),d=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",m=c.map((p,f)=>p.thoughts?`${d(n[f])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:c.map(p=>p.elementInteractedDisplayString),thoughts:m}}catch(u){if(this.throwIfClosed(),l>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:e,command:t,targetNames:n,descriptions:o,caches:o.map(()=>{}),action:a,options:s,retriesWithAI:l-1});throw new C("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapHardcodedCssTargetingCommandHelper({target:e,action:t,options:n,command:o}){let i=this.logger.child({commandId:o.id}),{targetName:a}=n;if(e.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let s,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({selector:e.elementDescriptor,targetName:a,logger:i});return{result:await t({locator:u.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;s=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await ee(500)}}throw s}async scrollIntoViewAndResolveFinalTarget(e){let{resolutionResult:t,disableGlobalLocatorRedirect:n,logger:o}=e,i=Pn(),a=!n&&this.browser.userBrowserSettings.globalLocatorRedirect!==!1;(this.browser.userBrowserSettings.visualActions||a)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(t.locator)});let s;return a&&(s=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:u}=await this.browser.performTargetRedirection(t,o);if(l.result=u,c&&i.storeTraceAsset)try{let d=await this.browser.screenshot({locator:c.locator,clearHighlights:!0}),m=vle();i.storeTraceAsset({snapshotId:m,data:d}),l.elementScreenshotSnapshotId=m}catch(d){o.debug({err:d},"Failed to capture element screenshot for redirect trace")}return c})),s||(s={locator:t.locator,serverSideBoundingBox:await t.locator.boundingBox({timeout:fe}),originalElementLocationResult:t.originalElementLocationResult}),s}async resolveCachedTargetForAction(e){let{cache:t,options:n,logger:o}=e,a=await Pn().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=t.targetSource;try{let c=await this.browser.resolveTarget(t,{allowNotActionableNodesOverride:n.allowNotActionableNodesOverride,logger:o,signal:this.executeAbortController.signal,...n.resolveTargetOptions});l.attributes.targetDisplayString=c.displayString,l.attributes.decisions=c.decisions;let u=c.decisions.find(d=>d.matched);return u&&(l.resolutionMethod=u.type),c}catch(c){throw c instanceof Ze&&(l.cacheMissReason=c.cacheMissReason,l.attributes.decisions=c.decisions),c}}),s=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:a,disableGlobalLocatorRedirect:n.disableGlobalLocatorRedirect,logger:o});return await a.revalidator?.(),{resolutionResult:a,finalTarget:s}}async wrapElementTargetingCommand(e){return await vo({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(e){let{tracer:t,target:n,action:o,options:i,command:a,finalAttempt:s=!1,originalCache:l=e.cache}=e,{retriesWithAI:c=1}=e,{disableCache:u,useSelector:d,targetName:m}=i,p=Pn(),f=this.logger.child({commandId:a.id}),h=this.shouldUseMemory(),g=ij(e.cache);if((!g||u)&&!ZE(n))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);let y=!1,b;u&&(f.info("Cache explicitly disabled for this step"),y=!0,b="Cache explicitly disabled",g=void 0);let E=zH({cache:g,description:n.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:f});g=E.cache,y=y||E.cacheBustedBeforeAction,!b&&E.cacheBustReason&&(b=E.cacheBustReason);let v=!0;if(!BH(g))return c--,v=!1,this.executeTargetingCommandWithAI({tracer:p,stepTracer:t,target:n,options:i,command:a,action:o,originalCache:l,logger:f,useMemory:h,cacheBustedBeforeAction:y,cacheBustReason:b});try{let{resolutionResult:w,finalTarget:L}=await this.resolveCachedTargetForAction({cache:g,options:i,logger:f}),I=await o(L);if(gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.59.1"]),uy({cmd:a,key:m,newTarget:g,logger:f,updatedWithAI:!1}),v){let A=w.decisions.filter(_=>_.matched);if(A.length!==1)f.warn({decisions:w.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let _=A[0].type;t.recordTargetAutoHeal({healType:_})}}return{result:I,elementInteractedDisplayString:w.displayString}}catch(w){this.throwIfClosed();let L=uT(w);if(L&&!s)return f.warn({err:w},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:t,command:a,target:n,action:o,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:!0,options:i});if(w instanceof C&&!L)throw f.warn({err:w},"Failed to execute command with target (fatal)"),w;if(c>0&&n){f.info({err:w},"Failed to execute action with cached target, retrying with AI"),gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.59.1",`missReason:${w instanceof Ze?w.cacheMissReason:"unknown"}`]);let I;return g.memory&&OM(g.memory)&&(I=g.memory),this.wrapElementTargetingCommandHelper({tracer:t,command:a,target:n,cache:void 0,action:o,originalCache:l,retriesWithAI:c,finalAttempt:!0,options:{...i,memory:I,targetHealingInProgress:!0}})}throw new C("ActionFailureError",`Failed to execute interactive command: ${w instanceof Error?w.message:`${w}`}`,{errOptions:{cause:w}})}}async executeTargetingCommandWithAI(e){let{tracer:t,stepTracer:n,target:o,options:i,command:a,action:s,originalCache:l,logger:c,useMemory:u,cacheBustedBeforeAction:d,cacheBustReason:m}=e;c.info({description:o.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:d,memory:i.memory,useMemory:u},"Prompting AI for an updated element location"),(d||!l)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?await t.startAsyncSpan("SMART_WAITING",async()=>await YH({description:o.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())):(d||!l)&&(i.skipAISmartWaiting?c.debug("Skipping AI smart waiting for this targeting attempt"):c.debug("Skipping AI smart waiting due to controller execution options"));let p=2;for(let f=1;f<=p;f++){let h=!1,g=this.browser.getActiveFrameConfig();try{let y;try{y=await ZC({description:o.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:u,memory:u?i.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,logger:c,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:m},this.getControllerFixtures())}catch(v){if(v instanceof ni&&v.updatedLocatorMemory){let w={id:-1,...l,memory:v.updatedLocatorMemory};uy({cmd:a,key:i.targetName,newTarget:w,logger:c,updatedWithAI:!0})}throw v}y.frameConfig&&(this.browser.setActiveFrameConfig(y.frameConfig),h=!0);let b=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:y.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),E=await s(b);return uy({cmd:a,key:i.targetName,newTarget:y.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(n.recordTargetAutoHeal({healType:"AI"}),y.target.targetSource="AI_HEALED",y.target.targetUpdateTime=new Date().toUTCString(),y.target.targetUpdateLoggerTags=Ee(c)),{result:E,elementInteractedDisplayString:y.resolution.displayString,thoughts:y.thoughts}}catch(y){if(h&&this.browser.setActiveFrameConfig(g),this.throwIfClosed(),f<p&&uT(y)){c.warn({err:y,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw y instanceof C?y:new C("ActionFailureError",y.message)}}throw new C("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(e){return Gp(this.browser,e)}async executePresetCommand(e,t,n,o){this.options?.slowMoMs&&await ee(this.options.slowMoMs);let i=await this.browser.getOpenPages(),a=this.browser.url(),s;try{s=await this.resolveCommandTemplateStrings(t,n)}catch(l){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o);return this.options?.autoFollowNewTabs&&await UH({beforeUrl:a,command:t,beforePages:i.map(c=>c.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{Ou(t,s)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>bC(e)}}async traceBrowserInteraction(e,t,n){return Pn().startAsyncSpan("BROWSER_INTERACTION",async()=>t(),{name:e,...n})}async resolveCommandTemplateStrings(e,t){return Iu({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o){o=o||"disableCache"in t&&!!t.disableCache;let i=this.logger.child({commandId:t.id});switch(t.type){case"SUCCESS":{let a=t.condition;return a?.assertion.trim()?CS({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AI_ASSERTION":{if(!t.assertion.trim())throw new C("ActionFailureError","Missing assertion");if(t.timeout&&t.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);return CS({command:t,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!t.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let l=Yc(t.schema);if(l)throw new C("UserConfigurationError",l)}let a=await this.browser.getCondensedHtml(),s=await this.browser.screenshot({retries:2});try{let l=await this.generator.getTextExtraction({goal:t.goal,browserState:a,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${s.toString("base64")}`},{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:Ee(i)});if(l.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(l.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",l.thoughts);return{thoughts:l.thoughts||void 0,data:l.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(l){let c=l.message;throw c.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):c.includes("AIProviderError")&&c.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:l}}):l}}case"NAVIGATE":if(!bu(t.url)&&!Eu(t.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${t.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:t.url,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0}));break;case"DIALOG":this.browser.registerDialogHandler(t.action);break;case"CAPTCHA":throw new C("UserConfigurationError","Captcha solving is no longer available on Momentic");case"GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case"GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let a,s;if(t.target&&ti(t.target))await this.browser.hoverUsingVisualCoordinates(t.target.pixels);else if(t.target&&t.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:d}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:m=>this.browser.hover(m),options:{...t,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:o}});a=u,s=d}let l=this.browser.getViewport()?.height??ba.height,c=this.browser.getViewport()?.width??ba.width;switch(t.type){case"SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(t.deltaY??l)));break;case"SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(t.deltaY??l));break;case"SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(t.deltaX??c)));break;case"SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(t.deltaX??c));break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"WAIT_FOR_URL":{if(t.timeout&&t.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=t.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:t.timeout?t.timeout*1e3:void 0,negated:t.negated,caseInsensitive:t.caseInsensitive});break}case"WAIT":{if(t.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${t.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=t.delay*1e3;await ee(a,this.executeAbortController.signal);break}case"REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0}));break;case"CLICK":{if(ti(t.target)){let{pixels:d}=t.target;await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(d,t),{coordinates:d});break}let a=this.browser.url(),{elementInteractedDisplayString:s,result:l,thoughts:c}=await this.wrapElementTargetingCommand({tracer:e,target:t.target,command:t,cache:t.cache?.target,action:d=>this.traceBrowserInteraction("Click",()=>this.browser.click(d,this.createCallbacksForBrowser(this.orgId),t),{selector:d.locator.toString()}),options:{disableCache:o,targetName:"target",...t}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:c,data:l.downloadedFile?{downloadedFile:l.downloadedFile}:void 0};return wy(a,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"COPY":return await this.browser.copy(t.value),{succeedImmediately:!1,data:t.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(ti(t.fromTarget)&&ti(t.toTarget)){let l=t.fromTarget.pixels,c=t.toTarget.pixels;await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(l,c,{hoverDurationMs:t.hoverSeconds?t.hoverSeconds*1e3:void 0}),{coordinates:l});break}if(ti(t.fromTarget)||ti(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:s}=await this.wrapMultiElementTargetingCommand({tracer:e,command:t,targetNames:["fromTarget","toTarget"],descriptions:[t.fromTarget,t.toTarget],caches:[t.cache?.fromTarget,t.cache?.toTarget],action:(l,c)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(l,c,{hoverDurationMs:t.hoverSeconds?t.hoverSeconds*1e3:void 0,steps:t.steps})),options:{useSelector:!!t.useSelector,disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:s}}case"MOUSE_DRAG":{let a=parseInt(t.deltaX),s=parseInt(t.deltaY),l=t.steps??5;if(isNaN(a)||isNaN(s))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);if(t.target&&ti(t.target)){let d=t.target.pixels;await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:s,steps:l,fromTarget:d}),{coordinates:d});break}let c,u;if(t.target?.elementDescriptor){let{elementInteractedDisplayString:d,thoughts:m}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async p=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,l,p.locator,{force:t.force})),options:{disableCache:o,targetName:"target",...t}});c=d,u=m}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,l,void 0,{force:t.force}));return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:u}}case"SELECT_OPTION":{if(!ha(t.target))throw new Error("Select with x/y is not supported yet");let a=t.target.elementDescriptor,s=t.choice,{elementInteractedDisplayString:l,thoughts:c}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:{type:"description",elementDescriptor:a},cache:t.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,s,t.force),{value:s.type==="LABEL"?s.label:s.type==="VALUE"?s.value:s.index}),options:{...t,targetName:"target",disableCache:o,source:Zd(t)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:l,thoughts:c}}case"TAB":{let a={loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(t.action,a);break}case"NEW_TAB":await this.browser.createNewTab(t.url,{loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"COOKIE":{if(!t.value)break;let a=await this.browser.setCookie(t.value);i.debug({results:a},"Set cookies");break}case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let a;try{t.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:t.code,fragment:t.fragment??!1,context:n.toObjectCopy(),timeoutMs:t.timeout?t.timeout*1e3:void 0}),i.info({result:a},"Executed JavaScript in browser")):a=await bo({orgId:this.orgId,code:t.code,fragment:!!t.fragment,context:n,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async s=>{if(!this.options?.scratchPadId){i.warn({updates:s},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:s,logger:i})}}})}catch(s){throw this.throwIfClosed(),new C("ActionFailureError",s instanceof Error?s.message:`${s}`,{errOptions:{cause:s}})}try{JSON.stringify(a)}catch(s){throw new C("ActionFailureError",`Return value is not serializable: ${s instanceof Error?s.message:`${s}`}`,{errOptions:{cause:s}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:a}}case"TYPE":{if(t.target&&ti(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.pixels,t),await this.traceBrowserInteraction("Type",()=>this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter},!0),{value:t.value});break}let a=this.browser.url(),s,l,c=ij(t.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(c){let{elementInteractedDisplayString:m,thoughts:p}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:c,cache:t.cache?.target,action:f=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(t.value,f,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter,relativePosition:t.relativePosition}),{value:t.value,selector:f.locator.toString()}),options:{...t,targetName:"target",disableCache:o,disableGlobalLocatorRedirect:!u,source:Zd(t)}});s=m,l=p}else await this.traceBrowserInteraction("Type",()=>this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,forceClearContent:t.forceClearContent,delay:t.delay,pressEnter:t.pressEnter},!0),{value:t.value});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:l};return wy(a,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d}case"HOVER":{if(ti(t.target)){let{pixels:l}=t.target;await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(l),{coordinates:l});break}let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:l=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(l),{selector:l.locator.toString()}),options:{...t,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"FOCUS":{if(!ha(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:t,target:t.target,cache:t.cache?.target,action:l=>this.browser.focus(l),options:{...t,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"BLUR":{if(t.target&&!ha(t.target))throw new Error("Blur with x/y is not supported yet");if(!t.target||!t.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,target:t.target,command:t,cache:t.cache?.target,action:l=>this.browser.blur(l),options:{...t,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(t.value,{repeat:t.repeat,convertMeta:t.convertMeta??!0,delayMs:t.delayMs}),{value:t.value});let s={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return wy(a,s.urlAfterCommand)&&(s.succeedImmediately=!0,s.succeedImmediatelyReason="URL changed"),s}case"KEY_DOWN":return await this.browser.keyDown(t.value,{convertMeta:t.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(t.value,{convertMeta:t.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let a=new wle,s=Ale(fetch,a),l;try{l=new URL(t.url).hostname}catch{}let c=await $u({command:t,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:s});return{data:Is.parse({...c,cookies:Dc(a,l)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await oj({command:t,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return tj({tracer:e,command:t,disableCache:o,browser:this.browser,logger:i,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case"FILE_UPLOAD":{let a,s;if(t.fileSource.type==="URL"?(s=t.fileSource.url,a=await f$({uri:t.fileSource.url,logger:i,orgId:this.orgId})):t.fileSource.type==="USER_FILE"&&(s=t.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(t.fileSource.name,this.orgId)),!a)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${s}`);await this.browser.setFileChooserHandler({...a,filename:t.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let a;if(!t.storageState.trim())a=void 0;else if(a=await bo({orgId:this.orgId,code:t.storageState,fragment:!1,context:n,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let s;try{s=QO.optional().parse(a)}catch(l){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${l}`)}await this.browser.loadAuthState(s);break}case"ELEMENT_CHECK":{let a=(t.timeout??ur)*1e3,s=this.generator.getAgentConfig()?.assertion;if(QH(t.assertion)&&!t.useSelector&&t.target.type==="description"&&s&&s!=="v1"){let c={id:t.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${t.target.elementDescriptor}`,iframeUrl:t.iframeUrl,timeout:t.timeout,source:"NEGATED_CHECK",cache:t.cache&&"memory"in t.cache?{memory:t.cache?.memory}:void 0};try{let u=await CS({command:c,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory()});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${u.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:u.afterScreenshotOverride}}finally{c.cache?.memory&&bp(t,c.cache?.memory.traces,i)}}let l=await ZH({command:t,tracer:e,timeoutMs:a,targetingWrapper:c=>this.wrapElementTargetingCommand(c),fixtures:this.getControllerFixtures(),disableCache:o});return{fail:!l.success,data:l.data,elementInteracted:l.elementInteractedDisplayString,thoughts:l.err?.message??l.thoughts??`Element assertion ${l.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let a=await vo({action:async()=>nj({assertion:t.assertion,browser:this.browser,logger:i,timeout:t.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!a.success,data:a.data,thoughts:a.success?"Page assertion passed.":a.err?.message??`Page assertion still failing after ${t.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let a=new ns(t.requestMatcher),s=this.browser.registerRequestListener(a);return this.registeredListeners[t.key]=s.then(async l=>await wC(l)).catch(l=>{i.error({err:l},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let a=this.registeredListeners[t.key];if(!a)throw new C("ActionFailureError",`No listener registered with key: ${t.key}`);let s=t.timeout??10;return{data:await J(a,{milliseconds:s*1e3,message:`Request listener timed out after ${s} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let a=new ns(t.requestMatcher);return this.recordedRequests[t.key]={},this.browser.registerRequestRecorder(t.key,{matches:s=>a.matches({url:s.request.url,method:s.request.method}),onRequestStart:(s,l)=>{this.recordedRequests[t.key][s]=pS(l)},onRequestComplete:(s,l)=>{this.recordedRequests[t.key]?.[s]&&(this.recordedRequests[t.key][s]=pS(l))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let a=this.recordedRequests[t.key];if(!a)throw new C("ActionFailureError",`No recorder registered with key: ${t.key}`);return delete this.recordedRequests[t.key],{data:Object.values(a),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let a;return t.requestMatcher&&(a=new ns(t.requestMatcher)),this.browser.setHeader(t.name,t.value,a),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(t.key,new ns(t.requestMatcher),async(s,l)=>{let c=await bo({orgId:this.orgId,code:t.responseGenerator,fragment:!1,context:n,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:s,response:l},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),u=NN.parse(c);return new Response(u.body,{status:u.status,headers:u.headers})},t.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(t.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(t.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Ee(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new bS({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ee(this.logger)})}async getFailureRecoveryPlan(e,t){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ee(t??this.logger)})}};import{mkdirSync as Wle}from"fs";import{tmpdir as Vle}from"os";import hj from"path";import{diff as Gle}from"deep-object-diff";import{cloneDeep as tR}from"lodash-es";import uj from"fontoxpath";import Cle from"@prettier/plugin-xml";import Rle from"prettier";import{DOMParser as xle,XMLSerializer as _le}from"slimdom";var Mle=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function Ple(r){let e=r.toLowerCase();return e.endsWith("webview")||Mle.has(e)}function Wp(r){return!!(Ple(r.tagName)||r.getAttribute("package")==="com.android.chrome"&&r.getAttribute("content-desc")==="Web View"&&aj(r.tagName.toLowerCase()).startsWith("frame"))}function aj(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var Ile=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Ole=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),Nle=new Set(["text","hint"]),Lle=new Set(["live-region","drawing-order"]),Dle=new Set(["displayed","enabled"]);function kle(r,e){let t={};for(let[n,o]of Object.entries(e))Ile.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Ole.has(n)&&o==="false"||Nle.has(n)&&o===""||Dle.has(n)&&o==="true"||Lle.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function sj(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,l=a.value++;t.setAttribute("id",String(l));let c={};for(let m of e.attributes){let p=m.name,f=m.value;f!=null&&(c[p]=String(f))}let u=kle(e.tagName,c);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(l,e),i.set(l,t),Wp(e)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
4885
4885
  ${m}
4886
- `));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let f=m.nodeValue;f&&f.trim().length>0&&t.appendChild(n.createTextNode(f));continue}if(p===1){let f=m;if(!Ble(f,s?.viewportBounds))continue;let h=n.createElement(aj(f.tagName));sj(r,f,h),t.appendChild(h)}}}function Fle(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;sj(a,e,s);let l=new _le().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:l}}async function lj(r,e,t){let n=new xle,o=n.parseFromString(r,"text/xml"),i=new Map,a=o.documentElement;if(!a)throw new C("InternalWebAgentError","No root element found in XML");if(a.tagName!=="hierarchy")throw new C("InternalWebAgentError","No hierarchy element found in XML");let{prunedDocument:s,prunedIdToElement:l,xml:c}=Fle(n,a,i,t),u=c;try{u=await Rle.format(c,{parser:"xml",plugins:[Cle],printWidth:120,tabWidth:1,singleAttributePerLine:!1})}catch(d){e.warn({err:d},"Failed to format XML")}return{xml:u,originalXml:r,document:o,idToElement:i,prunedDocument:s,prunedIdToElement:l}}function Ule(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function MS(r,e){let t=r.idToElement.get(e);if(t)return Ule(t)}function eR(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Rl(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function Ble(r,e){if(!e)return!0;let t=Rl(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function cj(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function dj({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=Rl(e),!t))throw new C("ActionFailureError","Element to cache has no bounds or unexpected bounds format");return{requiredText:r?.textRequired?e.getAttribute("text")??void 0:void 0,requiredAttributes:cj(e,r?.attributesRequired),requiredBounds:r?.boundsRequired,position:r?.positionSpecificity?{x1:t[0],y1:t[1],x2:t[2],y2:t[3],tolerance:r?.positionSpecificity}:void 0,shape:r?.shapeSpecificity?{width:t[2]-t[0],height:t[3]-t[1],tolerance:r?.shapeSpecificity}:void 0}}function pj({aiResponse:r,description:e,emulatorState:t,memory:n,useMemory:o}){let i=t.graph.idToElement.get(r.id);if(!i)throw new C("InternalWebAgentError",`Could not find node with id: ${r.id}`);let a=Rl(i);if(!a)throw new C("InternalWebAgentError",`Node ${r.id} has no bounding box: ${i.outerHTML}`);let s=MS(t.graph,r.id)??"",l=eR(t.graph,r.id)??"",c=dj({requirements:r.requirements,element:i}),u=[];r.additionalElements&&(u=r.additionalElements.map(({id:m,requirements:p})=>{let f=t.graph.idToElement.get(m);if(!f)return;let h=MS(t.graph,m);return h?{xPath:h,requirements:dj({requirements:p,element:f})}:void 0}).filter(m=>!!m));let d;if(Wp(i)&&r.inWebview!==!1?d={type:"WEBVIEW",resolvedDescription:e,xPath:s}:d={type:"NATIVE",bounds:a,resolvedDescription:e,xPath:s,elementOnlySerializedXml:l,requirements:c,requiredRelatedElements:u},o)if(r.updatedMemory){let m={type:"GCS_TRACES",traces:r.updatedMemory};d.memory=m}else n&&(d.memory=n);return{target:d,resolvedNode:i}}function fj(r){return r?.type==="WEBVIEW"?r.browserCache?.memory:void 0}function zle(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r[0]+r[2])/2;if(!Ri(e.tolerance,n,o,Math.min(1,t)))return!1;let i=e.y2-e.y1,a=(e.y1+e.y2)/2,s=(r[1]+r[3])/2;return Ri(e.tolerance,a,s,Math.min(1,i))}function $le(r,e){return Ri(e.tolerance,e.width,r[2]-r[0],Math.min(1,e.width))?Ri(e.tolerance,e.height,r[3]-r[1],Math.min(1,e.height)):!1}var mj=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i,position:a,shape:s}=e;if(o!==void 0&&o.length>0){let l=Fp(r);if(l!==o)throw new Ze(`Resolved element text mismatch: expected ${o}, got ${l}`)}if(n)for(let[l,c]of Object.entries(n)){let u=r.getAttribute(l)??void 0;if(u!==c)throw new Ze(`Attribute ${l} mismatch: expected ${c}, got ${u}`)}if(i&&t&&!t.targetBounds.every((c,u)=>c===t.newElementBounds[u]))throw new Ze(`Bounds changed from [${t.targetBounds.join(",")} ] to [${t.newElementBounds.join(",")} ]`);if(a&&t&&!zle(t.newElementBounds,a))throw new Ze(`Position mismatch: expected ${JSON.stringify(a)}, got ${JSON.stringify(t.newElementBounds)}`);if(s&&t&&!$le(t.newElementBounds,s))throw new Ze(`Shape mismatch: expected ${JSON.stringify(s)}, got ${JSON.stringify(t.newElementBounds)}`)};async function Vp(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=X();if(e.type==="WEBVIEW")return Hle(e,r);if(!e.xPath)throw new C("ActionFailureError","Native element cache has no XPath");let a=uj.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Ze(`Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let p of m){let f=uj.evaluateXPathToFirstNode(p.xPath,o);if(!f)throw new Ze(`Required related element not found for XPath: ${p.xPath}`);mj(f,p.requirements)}})}let s=Rl(a);if(!s)throw new Ze("Resolved native element has no bounding box");if(!e.bounds)throw new Ze("Native element cache has no bounds");mj(a,e.requirements,{targetBounds:e.bounds,newElementBounds:s});let l;for(let[m,p]of n.idToElement.entries())if(p===a){l=m;break}let c=e.elementOnlySerializedXml,u=e.xPath;return l!==void 0&&(c=eR(n,l)??c,u=MS(n,l)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:c,xPath:u}}}async function Hle(r,e){let{stateManager:t,logger:n,signal:o}=e,i=X(),a=await t.getActiveWebview();if(!a||!a.browserController)throw n.error({webview:a?{...a,browserController:!!a.browserController}:void 0},"resolveTargetCacheInWebView: No browser controller attached"),new Ze("No browser controller is attached to the requested webview");let s=a.browserController;if(!r.browserCache)throw n.error({target:r},"resolveTargetCacheInWebView: No browser target available on cache"),new Ze("No browser target available on cache");let l=r.browserCache,{finalTarget:c}=await i.startAsyncSection("Resolve target in webview",()=>s.resolveCachedTargetForAction({cache:l,options:{resolveTargetOptions:{logger:n,signal:o,skipWaitForPageLoad:!0,skipSavingVisualAttributes:!0}},logger:n}));return{resolvedTarget:{...r,controller:a.browserController,browserTarget:c}}}function xl(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;li(e)&&(e[t]={...e[t],[n]:_c.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date,e[t].updatedAtLoggerTags=Ee(r.logger)))}function _l(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache,memory:r.memory};let{resolvedNode:e,...t}=r;return{...t}}var la=.15,rr=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;aiSettings;options;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId,this.aiSettings=e.aiSettings,this.options=e.options}shouldUseMemoryForCommand(e){return this.aiSettings?.useMemory&&!e?.disableCache}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1,useMemory:i=!1,memory:a,webviewMemory:s,metadata:l,cacheBustReason:c}){let u=this.logger.child({...l}),d=await t.startAsyncSection("Get emulator state",async()=>{let y=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),screenshot:y}}),m;try{m=await t.startAsyncSpan("AI_LOCATOR_CALL",async y=>{c&&(y.attributes.cacheBustReason=c);let b=await this.generator.getAndroidElementLocation({description:e,screenXml:d.emulatorState.graph.xml,screenshot:d.screenshot,memory:i?a:void 0},{logger:u,loggerTags:Ee(u),abortSignal:this.aborter.controller?.signal,useMemory:i,agentConfigVersion:this.aiSettings.agentConfig?.["android-locator"]});return y.result=b,b})}catch(y){throw this.throwIfAborted(),u.error({err:y},"Failed to locate element"),new C("InternalWebAgentError",`Failed to locate element: ${y instanceof Error?y.message:y}`,{errOptions:{cause:y}})}if(m.id===-1){let y=m.updatedMemory?{type:"GCS_TRACES",traces:m.updatedMemory}:void 0;return{success:!1,thoughts:m.thoughts??"No matching element found",updatedLocatorMemory:y}}let{target:p,resolvedNode:f}=pj({aiResponse:m,description:e,emulatorState:d.emulatorState,memory:a,useMemory:i});if(p.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:p.elementOnlySerializedXml??"Unknown element"},attributes:{},subSpans:[]}),{success:!0,resolvedTarget:{...p,resolvedNode:f},thoughts:m.thoughts};let{browserLocateResult:h,browserController:g}=await t.startWebviewTrace(async()=>{let y=await this.stateManager.getActiveWebview();if(!y||!y.browserController)throw new C("InternalWebAgentError","No browser controller is attached to the requested webview");return{browserLocateResult:await y.browserController.locateElement({description:e,disableCache:!1,useMemory:i,memory:i?s:void 0,logger:this.logger,skipWait:!0,skipSavingVisualAttributes:!0}),browserController:y.browserController}});return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:h.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},attributes:{},subSpans:[]}),{success:!0,resolvedTarget:{...p,controller:g,browserTarget:{...h.resolution,serverSideBoundingBox:await h.resolution.locator.boundingBox({timeout:5e3})},browserCache:h.target},thoughts:h.thoughts}}async targetingActionWithAILocator(e){let{action:t,command:n,description:o,tracer:i,cacheKey:a,targetName:s,cache:l,skipFetchingFullWebviewContent:c,removeWebviewContent:u,metadata:d,cacheBustReason:m}=e,p=await this.findElement({description:o,tracer:i,skipFetchingFullWebviewContent:c,removeWebviewContent:u,useMemory:this.shouldUseMemoryForCommand(n),memory:l?.memory,webviewMemory:fj(l),metadata:d,cacheBustReason:m});if(!p.success){if(p.updatedLocatorMemory&&l){let y={...l,memory:p.updatedLocatorMemory};xl({command:n,cacheKey:a,targetName:s,updatedCache:y,updatedWithAI:!0,logger:this.logger})}throw new C("NoMatchingElementError",p.thoughts??"No matching element found")}let f=p.thoughts,{result:h,resolvedTarget:g}=await this.executeActionWithWebviewReconstructRetry({action:t,resolvedTarget:p.resolvedTarget,reason:"webview target closed during AI-located action"});return xl({command:n,cacheKey:a,targetName:s,updatedCache:_l(g),updatedWithAI:!0,logger:this.logger}),{result:h,thoughts:f}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:l,skipFetchingFullWebviewContent:c=!1,removeWebviewContent:u=!1}=e,d,m={commandId:o.id};if(i==="cache"&&"cache"in o&&o.cache){let E=o.cache;a==="target"&&"target"in E?d=E.target:a==="fromTarget"&&"fromTarget"in E?d=E.fromTarget:a==="toTarget"&&"toTarget"in E&&(d=E.toTarget)}let p=!1,f,h=tR(d);if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),p=!0,f="Cache explicitly disabled",h=void 0),s&&(p=!0,f=f??"Cache invalidated after resolution",h=void 0),h&&h?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:h?.resolvedDescription},"Cache description mismatch, clearing it automatically"),p=!0,f="Description mismatch",h=void 0),!h)return this.logger.info({description:n,cacheBustedBeforeAction:p},"Prompting AI for a new element location"),this.targetingActionWithAILocator({action:t,command:o,description:n,tracer:l,cacheKey:i,targetName:a,cache:d,skipFetchingFullWebviewContent:c,removeWebviewContent:u,metadata:m,cacheBustReason:f});let g=h.type==="NATIVE"?!!h.requirements:!!h.browserCache?.requirements,y=h.type==="NATIVE"?!!h.requiredRelatedElements?.length:!!h.browserCache?.additionalElements?.length,b;try{this.options?.emulator?.waitForStability&&await this.stateManager.waitForPageSourceStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let{resolvedTarget:E}=await l.startAsyncSpan("CACHE_RESOLUTION",async L=>{let I=Date.now(),A;for(;Date.now()-I<3e3;){b=await this.stateManager.getDomState({skipFetchingFullWebviewContent:h?.type==="NATIVE"});let _;try{_=(await Vp({target:h,domState:b,stateManager:this.stateManager,logger:this.logger})).resolvedTarget}catch(D){if(A=D,D instanceof Ze){this.logger.warn({err:D},"Failed to resolve target cache, retrying");continue}throw this.logger.error({err:D},"Failed to resolve target cache"),D}let O=_l(_),k=Gle(h,O);return k&&Object.keys(k).length>0&&this.logger.info({cacheDiffs:k},"Successfully resolved target with cache"),L.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml??"Unknown element",{resolvedTarget:_,updatedCache:O}}throw A}),{result:v,resolvedTarget:w}=await this.executeActionWithWebviewReconstructRetry({action:t,resolvedTarget:E,reason:"webview target closed during cached action"});return xl({command:o,cacheKey:i,targetName:a,updatedCache:_l(w),updatedWithAI:!1,logger:this.logger}),gt.increment("cache_target_resolution_v2",1,["outcome:hit",`platform:mobile-${h.type.toLowerCase()}`,`hasRequirements:${g}`,`hasAdditionalElements:${y}`,`orgId:${this.orgId}`,"cliVersion:0.59.0"]),{result:v,thoughts:"Successfully executed preset action with cache"}}catch(E){if(this.throwIfAborted(),E instanceof C&&E.reason!=="InternalWebAgentError")throw this.logger.error({err:E},"Failed to execute action with target cache (fatal)"),E;return gt.increment("cache_target_resolution_v2",1,["outcome:miss",`platform:mobile-${h.type.toLowerCase()}`,`hasRequirements:${g}`,`hasAdditionalElements:${y}`,`orgId:${this.orgId}`,"cliVersion:0.59.0"]),this.logger.warn({err:E},"Failed to execute action with target cache, retrying with AI"),this.targetingActionWithAILocator({action:t,command:o,description:n,tracer:l,cacheKey:i,targetName:a,cache:h,skipFetchingFullWebviewContent:c,removeWebviewContent:u,metadata:m})}}async executeActionWithWebviewReconstructRetry(e){let{action:t,resolvedTarget:n,reason:o}=e;try{return{result:await t(n),resolvedTarget:n}}catch(i){if(this.throwIfAborted(),n.type!=="WEBVIEW"||!this.errorLooksLikeClosedWebviewTarget(i)||(this.logger.warn({err:i},"Webview target appears closed or crashed during action, reconstructing browser and retrying once"),!(await this.stateManager.reconstructActiveWebviewBrowser(o))?.browserController))throw i;let s=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0}),{resolvedTarget:l}=await Vp({target:_l(n),domState:s,stateManager:this.stateManager,logger:this.logger,signal:this.abortSignal});return{result:await t(l),resolvedTarget:l}}}errorLooksLikeClosedWebviewTarget(e){let t=e instanceof Error?e.message:String(e);return["Target closed","Target crashed","Page crashed","Target page, context or browser has been closed","Session closed. Most likely the page has been closed"].some(n=>t.includes(n))}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId,aiSettings:this.aiSettings,options:this.options}}getBoundsFromNativeCache(e){if(!e.bounds)throw new C("ActionFailureError","Native element cache has no bounds");let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new C("ActionFailureError",`Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n}){let o=e.left+e.width/2,i=e.top+e.height/2;if(t==="up"||t==="down"){let a=e.height*la,s=e.top+a,l=e.top+e.height-a,c=l-s,u=Math.min(Math.abs(n),c);return{startX:o,startY:t==="down"?l:s,actualDelta:u}}else{let a=e.width*la,s=e.left+a,l=e.left+e.width-a,c=l-s,u=Math.min(Math.abs(n),c);return{startX:t==="right"?l:s,startY:i,actualDelta:u}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,l=t;o==="up"||o==="down"?l=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:l},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}get aiSettingsCopy(){return tR(this.aiSettings)}get optionsCopy(){return tR(this.options)}};function gj(r){return"iterations"in r}function qle(r){let e={relativePosition:r.relativePosition};if(r.iterations!==void 0&&(!Number.isInteger(r.iterations)||r.iterations<1))throw new Error("UserConfigurationError: iterations must be a positive integer");if(r.tapDelayMs!==void 0&&(!Number.isInteger(r.tapDelayMs)||r.tapDelayMs<0))throw new Error("UserConfigurationError: tapDelayMs must be >= 0");if(r.iterations&&r.iterations>1&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both more than one tap iteration and long press at the same time");if(r.tapDelayMs!==void 0&&(!r.iterations||r.iterations<2))throw new Error("UserConfigurationError: tapDelayMs requires iterations >= 2");if(r.longPress){if(r.tapDelayMs!==void 0)throw new Error("UserConfigurationError: tapDelayMs cannot be used with longPress");return{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}}return r.iterations!==void 0?{...e,iterations:r.iterations,tapDelayMs:r.tapDelayMs}:e}var ju=class extends rr{async tapOnNativeCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),"longPress"in e&&e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(gj(e)){let o=e.tapDelayMs??100;for(let i=0;i<e.iterations;i++)await this.driver.tap({x:t,y:n}),i<e.iterations-1&&await new Promise(a=>setTimeout(a,o));return}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,l=a-o,c=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??l/2;c=Math.max(0,Math.min(c,s)),u=Math.max(0,Math.min(u,l));let d=n+c,m=o+u;return await this.tapOnNativeCoordinates({x:d,y:m,...t}),{x:d,y:m}}async tapOnWebviewTarget(e,t){let{controller:n}=e,o,i=1;return t&&gj(t)?(o=t.tapDelayMs,i=t.iterations):t&&"longPress"in t&&(o=t.longPressDurationMs),(await n.browser.click(e.browserTarget,{createIsolatedFolder:()=>{let s=Math.random().toString(36).substring(4),l=hj.join(Vle(),"momentic","downloads"),c=hj.join(l,this.orgId,s);return Wle(c,{recursive:!0}),c}},{delayMs:o,relativePosition:t?.relativePosition,iterations:i})).coordinates}async tapOnTarget({target:e,options:t}){return await X().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=X(),n=qle(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,l=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnNativeCoordinates({...n,x:s,y:l})},{name:`Tap at coordinates ${s}, ${l}`}),{success:!0,message:`Tapped at ${s}, ${l}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var as=class extends rr{async doPress({keycode:e,longPress:t}){await X().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Ml=25,PS=class extends rr{async doType(e){let t=X();if(!e.target){if(e.clearContent)throw new C("UserConfigurationError","Clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForPageSourceStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}if(e.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await X().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??Ml};o.attributes.options=i;let{controller:a,browserTarget:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new ju(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForPageSourceStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=X(),n=e.keyPressDelayMs??Ml;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<2e3;){this.throwIfAborted();let s=Date.now();if(await this.driver.isKeyboardShown())return;let l=Date.now()-s;l<500&&await new Promise(c=>setTimeout(c,500-l))}i.attributes.timedOut=!0}),n!==Ml?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:Ml})},{name:`Typing with a ${n}ms delay`}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:`Typing with a ${Ml}ms delay`})}async clearContent(){let e=X();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new as(this.constructPerformerParams()).doPress({keycode:67})}};import Wn from"zod";var yj=.8,Kle=Wn.object({navigationBar:Wn.object({visible:Wn.boolean(),x:Wn.number(),y:Wn.number(),width:Wn.number(),height:Wn.number()}),statusBar:Wn.object({visible:Wn.boolean(),x:Wn.number(),y:Wn.number(),width:Wn.number(),height:Wn.number()})}),Gu=class extends rr{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getContainerBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Kle.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getContainerBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getContainerBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0&&(await this.stateManager.refreshWebviewsManually("get active webview nodes"),o=await this.stateManager.getActiveWebviewNodes()),o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getContainerBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getContainerBoundsFromViewport(e){return{left:e.x,top:e.y,width:Math.max(1,e.width),height:Math.max(1,e.height)}}getContainerBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n;return{left:t,top:n,width:Math.max(1,a),height:Math.max(1,s)}}async executeSwipe(e){let t=X();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i,relativePosition:e.relativePosition})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>X().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}async scrollInNativeContainer({span:e,cmd:t,target:n}){if(!n.bounds||n.bounds.length<4)throw new C("ActionFailureError","Native container cache has no bounds");let o=n.bounds,i=o[2]-o[0],a=o[3]-o[1];await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:o[0],top:o[1],width:Math.max(1,i),height:Math.max(1,a)},relativePosition:t.relativePosition})}async swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,browserTarget:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",l=await i.locator.boundingBox();if(!l)throw new Error("Failed to get bounds for webview container");let c=Math.floor(l.width*la),u=Math.floor(l.height*la),d=Math.max(1,l.width-c*2),m=Math.max(1,l.height-u*2),p,f;t.relativePosition?(p=l.x+t.relativePosition.x,f=l.y+t.relativePosition.y):(p=l.x+l.width/2,f=l.y+l.height/2);let h={x:p,y:f},g=(s?m:d)*(t.viewportPercent??yj)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=h,e.attributes.scrollPixelAmount=g,await o.browser.mouseDragUsingVisualCoordinates({deltaX:s?0:g,deltaY:s?g:0,steps:10,dragDurationMs:t.durationMs,fromTarget:h})}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=yj,durationMs:o=500,containerBounds:i,relativePosition:a}){e.attributes.containerBounds=i;let s=i.width*la,l=i.height*la,c,u;if(t==="up"||t==="down"?(c=(i.height-2*l)*n,u=Math.floor(c/(o/1e3))):(c=(i.width-2*s)*n,u=Math.floor(c/(o/1e3))),e.attributes.pixelDelta=c,e.attributes.pixelsPerSecond=u,a){let d=i.left+a.x,m=i.top+a.y;await this.performRawSwipe({startX:d,startY:m,deltaPixels:c,direction:t,durationMs:o})}else{let d=i.width*la,m=i.height*la,p={left:i.left+d,top:i.top+m,width:Math.max(1,i.width-2*d),height:Math.max(1,i.height-2*m)};await this.driver.executeScript("mobile: swipeGesture",[{...p,direction:t,percent:n,speed:u}])}}};var Yle=5,Sj=.8,Xle=1,IS=class extends Gu{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??Sj,o=await this.tryUseCachedScrollPosition(e,t);return o||this.searchForElement(e,t,n)}async resolveContainer({scrollableElement:e,containerCache:t,aiMetadata:n}){let o=await this.driver.getWindowRect();if(e.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:o.width,height:o.height}};if(e.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(e,o)};let i=X(),a=e.target.description;if(t){let u=this.getBoundsFromNativeCache(t);return this.logger.info({bounds:u},"Got container bounds from native cache"),{bounds:u,cache:t}}let s=await this.findElement({description:a,tracer:i,metadata:n});if(!s.success)throw new C("NoMatchingElementError",s.thoughts??"No matching element found");let{resolvedTarget:l}=s;if(l.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${a}" resolved to a webview element. Custom containers must be native elements.`);let c=this.getBoundsFromNativeCache(l);return this.logger.info({bounds:c},"Got container bounds from AI"),{bounds:c,cache:l}}async tryUseCachedScrollPosition(e,t){let n=e.cache?.target;return n?n.type==="WEBVIEW"?this.tryUseWebviewCache(e,t):n.scrollDetails?this.tryUseNativeScrollCache(e,t,n):null:null}async tryUseWebviewCache(e,t){let n=X();try{let{thoughts:o}=await this.wrapTargetingAction({command:e,tracer:n,description:t,action:async i=>{if(i.type==="NATIVE")throw new Error("Expected WEBVIEW target but got NATIVE");await this.scrollWebviewTargetIntoView(i)}});return{success:!0,message:o}}catch(o){return this.logger.warn({err:o},"Failed to use webview cache, falling back to search"),null}}async tryUseNativeScrollCache(e,t,n){let o=n.scrollDetails,i=X(),a=e.scrollStepPercent??Sj,s=o.scrollableElement.type==="CUSTOM"?o.scrollableElement.cache:void 0;await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:o.direction,scrollStepPercent:a,aiMetadata:{commandId:e.id}});try{let c=await this.tryFindElement({cmd:e,description:t,tracer:i,scrollDetails:o,useAIIfCacheFails:!1});if(c)return c;this.logger.info("Element not found at cached position, undoing scroll")}catch(c){this.logger.warn({err:c},"Error finding element at cached position, will undo scroll")}let l=o.direction==="down"?"up":"down";return this.logger.info({pixelDelta:o.pixelDelta,originalDirection:o.direction,undoDirection:l,scrollableElementType:o.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:l,scrollStepPercent:a,aiMetadata:{commandId:e.id}}),null}async tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:o,useAIIfCacheFails:i=!0}){let a,s,l=e.cache?.target;if(l&&l.resolvedDescription===t&&!e.disableCache){let u=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0});try{let{resolvedTarget:d}=await Vp({target:l,domState:u,stateManager:this.stateManager,logger:this.logger});a=d,s="Successfully resolved scroll to target with cache.",this.logger.info("Successfully resolved scroll to target from cache")}catch(d){this.logger.warn({err:d},"Failed to resolve target from cache")}}if(!a&&!i)return null;if(!a)try{let u=await this.findElement({description:t,tracer:n,metadata:{commandId:e.id}});if(!u.success)return null;a=u.resolvedTarget,s=u.thoughts}catch(u){if(u instanceof C&&u.reason==="NoMatchingElementError")return null;throw this.logger.warn({err:u},"Failed to find scroll-to target with AI"),u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),xl({command:e,updatedCache:_l(a),updatedWithAI:!0,logger:this.logger}),{success:!0,message:s}):(xl({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0,logger:this.logger}),{success:!0,message:s})}async searchForElement(e,t,n){let o=X(),i=await this.resolveContainer({scrollableElement:e.scrollableElement,aiMetadata:{commandId:e.id}});return this.scrollAndSearch(e,t,o,n,i)}async scrollAndSearch(e,t,n,o,i){let a=0,s=i.bounds,l=s.height*o,c=!0,u=e.maxScrollAttempts??Yle;for(let p=0;p<u;p++){this.throwIfAborted();let f=this.buildScrollDetails(e,a,i.cache),h=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:f});if(h)return h;if(!c)throw new Error(`ActionFailureError: Could not find element "${t}" after scrolling to the end`);this.logger.debug({attempt:p,cumulativePixelDelta:a},"Element not found, scrolling further");let g=Jle(e.scrollableElement);c=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:g}),a+=e.direction==="down"?l:-l}let d=this.buildScrollDetails(e,a,i.cache),m=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(m)return m;throw new Error(`ActionFailureError: Could not find element "${t}" after ${u} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollWebviewTargetIntoView(e){let{controller:t,browserTarget:n}=e;await t.browser.hover(n)}async scrollByPage({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o}){return X().startAsyncSpan("EMULATOR_INTERACTION",async a=>(a.attributes.containerBounds=t,a.attributes.direction=e,this.executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o})),{name:`Scroll ${e} by one page`})}async scrollByPixelDelta({pixelDelta:e,scrollableElement:t,containerCache:n,direction:o,scrollStepPercent:i,aiMetadata:a}){if(e===0)return;let s=X(),l,c,u;if(t.type==="CUSTOM_COORDINATES")l=t.startX,c=t.startY,u=t.deltaPixels;else{let p=(await this.resolveContainer({scrollableElement:t,containerCache:n,aiMetadata:a})).bounds,f=p.height*i,h=this.calculateSwipeCoordinates({containerBounds:p,direction:o,desiredDelta:f});l=h.startX,c=h.startY,u=h.actualDelta}let d=Math.ceil(Math.abs(e)/u);this.logger.debug({pixelDelta:e,direction:o,scrollableElementType:t.type,startX:l,startY:c,maxScrollPerStep:u,numScrolls:d},"scrollByPixelDelta calculated parameters"),await s.startAsyncSpan("EMULATOR_INTERACTION",async m=>{m.attributes.pixelDelta=e,m.attributes.numScrolls=d,m.attributes.maxScrollPerStep=u,m.attributes.startX=l,m.attributes.startY=c;let p=0;for(let f=0;f<d;f++){this.throwIfAborted();let h=Math.abs(e)-p,g=Math.min(u,h);await this.performRawSwipe({startX:l,startY:c,deltaPixels:g,direction:this.invertDirection(o)}),p+=g}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=Xle,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,l,c;if(i)s=i.startX,l=i.startY,c=i.deltaPixels;else{let p=t.height*n,f=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:p});s=f.startX,l=f.startY,c=f.actualDelta}await this.performRawSwipe({startX:s,startY:l,deltaPixels:c,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=es(a,u),m=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:m,direction:e,actualDelta:c,rawCoordinates:i},"Scroll gesture visual diff result"),m}};function Jle(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as Zle}from"crypto";import Kp from"fs";import{tmpdir as Qle}from"os";import Wu from"path";var OS=class extends rr{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install -r ${Wu.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(Kp.existsSync(n))o=n;else if(Kp.existsSync(Wu.join("/",n)))o=Wu.join("/",n);else throw new C("UserConfigurationError",`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new C("UserInfrastructureError",`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{Kp.unlinkSync(a)}catch(s){this.logger.warn({err:s,path:a},"Failed to remove temporary APK file")}}}}throw new C("UserConfigurationError",`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Wu.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{Kp.accessSync(e)}catch{throw new C("UserConfigurationError",`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Wu.extname(t)||".apk",o=Wu.join(Qle(),`momentic-apk-${Zle()}${n}`);return Kp.writeFileSync(o,e),o}};var NS=class extends rr{async dragNative(e,t,n){let{left:o,top:i,width:a,height:s}=this.getBoundsFromNativeCache(e),{left:l,top:c,width:u,height:d}=this.getBoundsFromNativeCache(t),m=o+a/2,p=i+s/2,f=l+u/2,h=c+d/2,g=n?.hoverDuration??500,y=n?.dragDuration??1e3;await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:m,y:p},{type:"pointerDown",button:0},{type:"pause",duration:g},{type:"pointerMove",duration:y,x:f,y:h},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}async dragWebview(e,t,n){let{controller:o}=e;if(e.controller!==t.controller)throw new C("UserConfigurationError","Cannot drag and drop between different webviews");let i=n?.dragDuration??1e3,a=n?.hoverDuration??1e3,s;n?.dragDuration&&(s=Math.max(1,Math.floor(i/200))),await o.browser.dragAndDrop(e.browserTarget,t.browserTarget,{hoverDurationMs:a,steps:s,dragDurationMs:i})}async executeDragAndDrop({command:e}){let t=X();if(e.fromTarget.type!=="description"||e.toTarget.type!=="description")throw new C("UserConfigurationError","Drag and drop only supports description targets for now");let n=e.fromTarget.description,{result:o,thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,description:n,cacheKey:"cache",targetName:"fromTarget",action:async c=>c}),a=e.toTarget.description,{result:s,thoughts:l}=await this.wrapTargetingAction({command:e,tracer:t,description:a,cacheKey:"cache",targetName:"toTarget",action:async c=>c});if(o.type!==s.type)throw new C("UserConfigurationError",`Drag and drop targets must be in the same context (both native or both webview). Found: From=${o.type}, To=${s.type}`);return await t.startAsyncSpan("EMULATOR_INTERACTION",async c=>{o.type==="NATIVE"&&s.type==="NATIVE"?await this.dragNative(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}):o.type==="WEBVIEW"&&s.type==="WEBVIEW"&&(c.withinWebview=!0,await this.dragWebview(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}))},{name:"Drag and drop"}),{success:!0,message:`${i}
4886
+ `));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let f=m.nodeValue;f&&f.trim().length>0&&t.appendChild(n.createTextNode(f));continue}if(p===1){let f=m;if(!Ble(f,s?.viewportBounds))continue;let h=n.createElement(aj(f.tagName));sj(r,f,h),t.appendChild(h)}}}function Fle(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;sj(a,e,s);let l=new _le().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:l}}async function lj(r,e,t){let n=new xle,o=n.parseFromString(r,"text/xml"),i=new Map,a=o.documentElement;if(!a)throw new C("InternalWebAgentError","No root element found in XML");if(a.tagName!=="hierarchy")throw new C("InternalWebAgentError","No hierarchy element found in XML");let{prunedDocument:s,prunedIdToElement:l,xml:c}=Fle(n,a,i,t),u=c;try{u=await Rle.format(c,{parser:"xml",plugins:[Cle],printWidth:120,tabWidth:1,singleAttributePerLine:!1})}catch(d){e.warn({err:d},"Failed to format XML")}return{xml:u,originalXml:r,document:o,idToElement:i,prunedDocument:s,prunedIdToElement:l}}function Ule(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function MS(r,e){let t=r.idToElement.get(e);if(t)return Ule(t)}function eR(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Rl(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function Ble(r,e){if(!e)return!0;let t=Rl(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function cj(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function dj({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=Rl(e),!t))throw new C("ActionFailureError","Element to cache has no bounds or unexpected bounds format");return{requiredText:r?.textRequired?e.getAttribute("text")??void 0:void 0,requiredAttributes:cj(e,r?.attributesRequired),requiredBounds:r?.boundsRequired,position:r?.positionSpecificity?{x1:t[0],y1:t[1],x2:t[2],y2:t[3],tolerance:r?.positionSpecificity}:void 0,shape:r?.shapeSpecificity?{width:t[2]-t[0],height:t[3]-t[1],tolerance:r?.shapeSpecificity}:void 0}}function pj({aiResponse:r,description:e,emulatorState:t,memory:n,useMemory:o}){let i=t.graph.idToElement.get(r.id);if(!i)throw new C("InternalWebAgentError",`Could not find node with id: ${r.id}`);let a=Rl(i);if(!a)throw new C("InternalWebAgentError",`Node ${r.id} has no bounding box: ${i.outerHTML}`);let s=MS(t.graph,r.id)??"",l=eR(t.graph,r.id)??"",c=dj({requirements:r.requirements,element:i}),u=[];r.additionalElements&&(u=r.additionalElements.map(({id:m,requirements:p})=>{let f=t.graph.idToElement.get(m);if(!f)return;let h=MS(t.graph,m);return h?{xPath:h,requirements:dj({requirements:p,element:f})}:void 0}).filter(m=>!!m));let d;if(Wp(i)&&r.inWebview!==!1?d={type:"WEBVIEW",resolvedDescription:e,xPath:s}:d={type:"NATIVE",bounds:a,resolvedDescription:e,xPath:s,elementOnlySerializedXml:l,requirements:c,requiredRelatedElements:u},o)if(r.updatedMemory){let m={type:"GCS_TRACES",traces:r.updatedMemory};d.memory=m}else n&&(d.memory=n);return{target:d,resolvedNode:i}}function fj(r){return r?.type==="WEBVIEW"?r.browserCache?.memory:void 0}function zle(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r[0]+r[2])/2;if(!Ri(e.tolerance,n,o,Math.min(1,t)))return!1;let i=e.y2-e.y1,a=(e.y1+e.y2)/2,s=(r[1]+r[3])/2;return Ri(e.tolerance,a,s,Math.min(1,i))}function $le(r,e){return Ri(e.tolerance,e.width,r[2]-r[0],Math.min(1,e.width))?Ri(e.tolerance,e.height,r[3]-r[1],Math.min(1,e.height)):!1}var mj=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i,position:a,shape:s}=e;if(o!==void 0&&o.length>0){let l=Fp(r);if(l!==o)throw new Ze(`Resolved element text mismatch: expected ${o}, got ${l}`)}if(n)for(let[l,c]of Object.entries(n)){let u=r.getAttribute(l)??void 0;if(u!==c)throw new Ze(`Attribute ${l} mismatch: expected ${c}, got ${u}`)}if(i&&t&&!t.targetBounds.every((c,u)=>c===t.newElementBounds[u]))throw new Ze(`Bounds changed from [${t.targetBounds.join(",")} ] to [${t.newElementBounds.join(",")} ]`);if(a&&t&&!zle(t.newElementBounds,a))throw new Ze(`Position mismatch: expected ${JSON.stringify(a)}, got ${JSON.stringify(t.newElementBounds)}`);if(s&&t&&!$le(t.newElementBounds,s))throw new Ze(`Shape mismatch: expected ${JSON.stringify(s)}, got ${JSON.stringify(t.newElementBounds)}`)};async function Vp(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=X();if(e.type==="WEBVIEW")return Hle(e,r);if(!e.xPath)throw new C("ActionFailureError","Native element cache has no XPath");let a=uj.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Ze(`Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let p of m){let f=uj.evaluateXPathToFirstNode(p.xPath,o);if(!f)throw new Ze(`Required related element not found for XPath: ${p.xPath}`);mj(f,p.requirements)}})}let s=Rl(a);if(!s)throw new Ze("Resolved native element has no bounding box");if(!e.bounds)throw new Ze("Native element cache has no bounds");mj(a,e.requirements,{targetBounds:e.bounds,newElementBounds:s});let l;for(let[m,p]of n.idToElement.entries())if(p===a){l=m;break}let c=e.elementOnlySerializedXml,u=e.xPath;return l!==void 0&&(c=eR(n,l)??c,u=MS(n,l)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:c,xPath:u}}}async function Hle(r,e){let{stateManager:t,logger:n,signal:o}=e,i=X(),a=await t.getActiveWebview();if(!a||!a.browserController)throw n.error({webview:a?{...a,browserController:!!a.browserController}:void 0},"resolveTargetCacheInWebView: No browser controller attached"),new Ze("No browser controller is attached to the requested webview");let s=a.browserController;if(!r.browserCache)throw n.error({target:r},"resolveTargetCacheInWebView: No browser target available on cache"),new Ze("No browser target available on cache");let l=r.browserCache,{finalTarget:c}=await i.startAsyncSection("Resolve target in webview",()=>s.resolveCachedTargetForAction({cache:l,options:{resolveTargetOptions:{logger:n,signal:o,skipWaitForPageLoad:!0,skipSavingVisualAttributes:!0}},logger:n}));return{resolvedTarget:{...r,controller:a.browserController,browserTarget:c}}}function xl(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;li(e)&&(e[t]={...e[t],[n]:_c.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date,e[t].updatedAtLoggerTags=Ee(r.logger)))}function _l(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache,memory:r.memory};let{resolvedNode:e,...t}=r;return{...t}}var la=.15,rr=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;aiSettings;options;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId,this.aiSettings=e.aiSettings,this.options=e.options}shouldUseMemoryForCommand(e){return this.aiSettings?.useMemory&&!e?.disableCache}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1,useMemory:i=!1,memory:a,webviewMemory:s,metadata:l,cacheBustReason:c}){let u=this.logger.child({...l}),d=await t.startAsyncSection("Get emulator state",async()=>{let y=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),screenshot:y}}),m;try{m=await t.startAsyncSpan("AI_LOCATOR_CALL",async y=>{c&&(y.attributes.cacheBustReason=c);let b=await this.generator.getAndroidElementLocation({description:e,screenXml:d.emulatorState.graph.xml,screenshot:d.screenshot,memory:i?a:void 0},{logger:u,loggerTags:Ee(u),abortSignal:this.aborter.controller?.signal,useMemory:i,agentConfigVersion:this.aiSettings.agentConfig?.["android-locator"]});return y.result=b,b})}catch(y){throw this.throwIfAborted(),u.error({err:y},"Failed to locate element"),new C("InternalWebAgentError",`Failed to locate element: ${y instanceof Error?y.message:y}`,{errOptions:{cause:y}})}if(m.id===-1){let y=m.updatedMemory?{type:"GCS_TRACES",traces:m.updatedMemory}:void 0;return{success:!1,thoughts:m.thoughts??"No matching element found",updatedLocatorMemory:y}}let{target:p,resolvedNode:f}=pj({aiResponse:m,description:e,emulatorState:d.emulatorState,memory:a,useMemory:i});if(p.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:p.elementOnlySerializedXml??"Unknown element"},attributes:{},subSpans:[]}),{success:!0,resolvedTarget:{...p,resolvedNode:f},thoughts:m.thoughts};let{browserLocateResult:h,browserController:g}=await t.startWebviewTrace(async()=>{let y=await this.stateManager.getActiveWebview();if(!y||!y.browserController)throw new C("InternalWebAgentError","No browser controller is attached to the requested webview");return{browserLocateResult:await y.browserController.locateElement({description:e,disableCache:!1,useMemory:i,memory:i?s:void 0,logger:this.logger,skipWait:!0,skipSavingVisualAttributes:!0}),browserController:y.browserController}});return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:h.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},attributes:{},subSpans:[]}),{success:!0,resolvedTarget:{...p,controller:g,browserTarget:{...h.resolution,serverSideBoundingBox:await h.resolution.locator.boundingBox({timeout:5e3})},browserCache:h.target},thoughts:h.thoughts}}async targetingActionWithAILocator(e){let{action:t,command:n,description:o,tracer:i,cacheKey:a,targetName:s,cache:l,skipFetchingFullWebviewContent:c,removeWebviewContent:u,metadata:d,cacheBustReason:m}=e,p=await this.findElement({description:o,tracer:i,skipFetchingFullWebviewContent:c,removeWebviewContent:u,useMemory:this.shouldUseMemoryForCommand(n),memory:l?.memory,webviewMemory:fj(l),metadata:d,cacheBustReason:m});if(!p.success){if(p.updatedLocatorMemory&&l){let y={...l,memory:p.updatedLocatorMemory};xl({command:n,cacheKey:a,targetName:s,updatedCache:y,updatedWithAI:!0,logger:this.logger})}throw new C("NoMatchingElementError",p.thoughts??"No matching element found")}let f=p.thoughts,{result:h,resolvedTarget:g}=await this.executeActionWithWebviewReconstructRetry({action:t,resolvedTarget:p.resolvedTarget,reason:"webview target closed during AI-located action"});return xl({command:n,cacheKey:a,targetName:s,updatedCache:_l(g),updatedWithAI:!0,logger:this.logger}),{result:h,thoughts:f}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:l,skipFetchingFullWebviewContent:c=!1,removeWebviewContent:u=!1}=e,d,m={commandId:o.id};if(i==="cache"&&"cache"in o&&o.cache){let E=o.cache;a==="target"&&"target"in E?d=E.target:a==="fromTarget"&&"fromTarget"in E?d=E.fromTarget:a==="toTarget"&&"toTarget"in E&&(d=E.toTarget)}let p=!1,f,h=tR(d);if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),p=!0,f="Cache explicitly disabled",h=void 0),s&&(p=!0,f=f??"Cache invalidated after resolution",h=void 0),h&&h?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:h?.resolvedDescription},"Cache description mismatch, clearing it automatically"),p=!0,f="Description mismatch",h=void 0),!h)return this.logger.info({description:n,cacheBustedBeforeAction:p},"Prompting AI for a new element location"),this.targetingActionWithAILocator({action:t,command:o,description:n,tracer:l,cacheKey:i,targetName:a,cache:d,skipFetchingFullWebviewContent:c,removeWebviewContent:u,metadata:m,cacheBustReason:f});let g=h.type==="NATIVE"?!!h.requirements:!!h.browserCache?.requirements,y=h.type==="NATIVE"?!!h.requiredRelatedElements?.length:!!h.browserCache?.additionalElements?.length,b;try{this.options?.emulator?.waitForStability&&await this.stateManager.waitForPageSourceStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let{resolvedTarget:E}=await l.startAsyncSpan("CACHE_RESOLUTION",async L=>{let I=Date.now(),A;for(;Date.now()-I<3e3;){b=await this.stateManager.getDomState({skipFetchingFullWebviewContent:h?.type==="NATIVE"});let _;try{_=(await Vp({target:h,domState:b,stateManager:this.stateManager,logger:this.logger})).resolvedTarget}catch(D){if(A=D,D instanceof Ze){this.logger.warn({err:D},"Failed to resolve target cache, retrying");continue}throw this.logger.error({err:D},"Failed to resolve target cache"),D}let O=_l(_),k=Gle(h,O);return k&&Object.keys(k).length>0&&this.logger.info({cacheDiffs:k},"Successfully resolved target with cache"),L.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml??"Unknown element",{resolvedTarget:_,updatedCache:O}}throw A}),{result:v,resolvedTarget:w}=await this.executeActionWithWebviewReconstructRetry({action:t,resolvedTarget:E,reason:"webview target closed during cached action"});return xl({command:o,cacheKey:i,targetName:a,updatedCache:_l(w),updatedWithAI:!1,logger:this.logger}),gt.increment("cache_target_resolution_v2",1,["outcome:hit",`platform:mobile-${h.type.toLowerCase()}`,`hasRequirements:${g}`,`hasAdditionalElements:${y}`,`orgId:${this.orgId}`,"cliVersion:0.59.1"]),{result:v,thoughts:"Successfully executed preset action with cache"}}catch(E){if(this.throwIfAborted(),E instanceof C&&E.reason!=="InternalWebAgentError")throw this.logger.error({err:E},"Failed to execute action with target cache (fatal)"),E;return gt.increment("cache_target_resolution_v2",1,["outcome:miss",`platform:mobile-${h.type.toLowerCase()}`,`hasRequirements:${g}`,`hasAdditionalElements:${y}`,`orgId:${this.orgId}`,"cliVersion:0.59.1"]),this.logger.warn({err:E},"Failed to execute action with target cache, retrying with AI"),this.targetingActionWithAILocator({action:t,command:o,description:n,tracer:l,cacheKey:i,targetName:a,cache:h,skipFetchingFullWebviewContent:c,removeWebviewContent:u,metadata:m})}}async executeActionWithWebviewReconstructRetry(e){let{action:t,resolvedTarget:n,reason:o}=e;try{return{result:await t(n),resolvedTarget:n}}catch(i){if(this.throwIfAborted(),n.type!=="WEBVIEW"||!this.errorLooksLikeClosedWebviewTarget(i)||(this.logger.warn({err:i},"Webview target appears closed or crashed during action, reconstructing browser and retrying once"),!(await this.stateManager.reconstructActiveWebviewBrowser(o))?.browserController))throw i;let s=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0}),{resolvedTarget:l}=await Vp({target:_l(n),domState:s,stateManager:this.stateManager,logger:this.logger,signal:this.abortSignal});return{result:await t(l),resolvedTarget:l}}}errorLooksLikeClosedWebviewTarget(e){let t=e instanceof Error?e.message:String(e);return["Target closed","Target crashed","Page crashed","Target page, context or browser has been closed","Session closed. Most likely the page has been closed"].some(n=>t.includes(n))}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId,aiSettings:this.aiSettings,options:this.options}}getBoundsFromNativeCache(e){if(!e.bounds)throw new C("ActionFailureError","Native element cache has no bounds");let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new C("ActionFailureError",`Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n}){let o=e.left+e.width/2,i=e.top+e.height/2;if(t==="up"||t==="down"){let a=e.height*la,s=e.top+a,l=e.top+e.height-a,c=l-s,u=Math.min(Math.abs(n),c);return{startX:o,startY:t==="down"?l:s,actualDelta:u}}else{let a=e.width*la,s=e.left+a,l=e.left+e.width-a,c=l-s,u=Math.min(Math.abs(n),c);return{startX:t==="right"?l:s,startY:i,actualDelta:u}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,l=t;o==="up"||o==="down"?l=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:l},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}get aiSettingsCopy(){return tR(this.aiSettings)}get optionsCopy(){return tR(this.options)}};function gj(r){return"iterations"in r}function qle(r){let e={relativePosition:r.relativePosition};if(r.iterations!==void 0&&(!Number.isInteger(r.iterations)||r.iterations<1))throw new Error("UserConfigurationError: iterations must be a positive integer");if(r.tapDelayMs!==void 0&&(!Number.isInteger(r.tapDelayMs)||r.tapDelayMs<0))throw new Error("UserConfigurationError: tapDelayMs must be >= 0");if(r.iterations&&r.iterations>1&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both more than one tap iteration and long press at the same time");if(r.tapDelayMs!==void 0&&(!r.iterations||r.iterations<2))throw new Error("UserConfigurationError: tapDelayMs requires iterations >= 2");if(r.longPress){if(r.tapDelayMs!==void 0)throw new Error("UserConfigurationError: tapDelayMs cannot be used with longPress");return{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}}return r.iterations!==void 0?{...e,iterations:r.iterations,tapDelayMs:r.tapDelayMs}:e}var ju=class extends rr{async tapOnNativeCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),"longPress"in e&&e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(gj(e)){let o=e.tapDelayMs??100;for(let i=0;i<e.iterations;i++)await this.driver.tap({x:t,y:n}),i<e.iterations-1&&await new Promise(a=>setTimeout(a,o));return}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,l=a-o,c=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??l/2;c=Math.max(0,Math.min(c,s)),u=Math.max(0,Math.min(u,l));let d=n+c,m=o+u;return await this.tapOnNativeCoordinates({x:d,y:m,...t}),{x:d,y:m}}async tapOnWebviewTarget(e,t){let{controller:n}=e,o,i=1;return t&&gj(t)?(o=t.tapDelayMs,i=t.iterations):t&&"longPress"in t&&(o=t.longPressDurationMs),(await n.browser.click(e.browserTarget,{createIsolatedFolder:()=>{let s=Math.random().toString(36).substring(4),l=hj.join(Vle(),"momentic","downloads"),c=hj.join(l,this.orgId,s);return Wle(c,{recursive:!0}),c}},{delayMs:o,relativePosition:t?.relativePosition,iterations:i})).coordinates}async tapOnTarget({target:e,options:t}){return await X().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=X(),n=qle(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,l=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnNativeCoordinates({...n,x:s,y:l})},{name:`Tap at coordinates ${s}, ${l}`}),{success:!0,message:`Tapped at ${s}, ${l}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var as=class extends rr{async doPress({keycode:e,longPress:t}){await X().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Ml=25,PS=class extends rr{async doType(e){let t=X();if(!e.target){if(e.clearContent)throw new C("UserConfigurationError","Clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForPageSourceStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}if(e.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await X().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??Ml};o.attributes.options=i;let{controller:a,browserTarget:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new ju(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForPageSourceStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=X(),n=e.keyPressDelayMs??Ml;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<2e3;){this.throwIfAborted();let s=Date.now();if(await this.driver.isKeyboardShown())return;let l=Date.now()-s;l<500&&await new Promise(c=>setTimeout(c,500-l))}i.attributes.timedOut=!0}),n!==Ml?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:Ml})},{name:`Typing with a ${n}ms delay`}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:`Typing with a ${Ml}ms delay`})}async clearContent(){let e=X();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new as(this.constructPerformerParams()).doPress({keycode:67})}};import Wn from"zod";var yj=.8,Kle=Wn.object({navigationBar:Wn.object({visible:Wn.boolean(),x:Wn.number(),y:Wn.number(),width:Wn.number(),height:Wn.number()}),statusBar:Wn.object({visible:Wn.boolean(),x:Wn.number(),y:Wn.number(),width:Wn.number(),height:Wn.number()})}),Gu=class extends rr{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getContainerBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Kle.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getContainerBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getContainerBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0&&(await this.stateManager.refreshWebviewsManually("get active webview nodes"),o=await this.stateManager.getActiveWebviewNodes()),o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getContainerBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getContainerBoundsFromViewport(e){return{left:e.x,top:e.y,width:Math.max(1,e.width),height:Math.max(1,e.height)}}getContainerBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n;return{left:t,top:n,width:Math.max(1,a),height:Math.max(1,s)}}async executeSwipe(e){let t=X();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i,relativePosition:e.relativePosition})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>X().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}async scrollInNativeContainer({span:e,cmd:t,target:n}){if(!n.bounds||n.bounds.length<4)throw new C("ActionFailureError","Native container cache has no bounds");let o=n.bounds,i=o[2]-o[0],a=o[3]-o[1];await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:o[0],top:o[1],width:Math.max(1,i),height:Math.max(1,a)},relativePosition:t.relativePosition})}async swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,browserTarget:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",l=await i.locator.boundingBox();if(!l)throw new Error("Failed to get bounds for webview container");let c=Math.floor(l.width*la),u=Math.floor(l.height*la),d=Math.max(1,l.width-c*2),m=Math.max(1,l.height-u*2),p,f;t.relativePosition?(p=l.x+t.relativePosition.x,f=l.y+t.relativePosition.y):(p=l.x+l.width/2,f=l.y+l.height/2);let h={x:p,y:f},g=(s?m:d)*(t.viewportPercent??yj)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=h,e.attributes.scrollPixelAmount=g,await o.browser.mouseDragUsingVisualCoordinates({deltaX:s?0:g,deltaY:s?g:0,steps:10,dragDurationMs:t.durationMs,fromTarget:h})}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=yj,durationMs:o=500,containerBounds:i,relativePosition:a}){e.attributes.containerBounds=i;let s=i.width*la,l=i.height*la,c,u;if(t==="up"||t==="down"?(c=(i.height-2*l)*n,u=Math.floor(c/(o/1e3))):(c=(i.width-2*s)*n,u=Math.floor(c/(o/1e3))),e.attributes.pixelDelta=c,e.attributes.pixelsPerSecond=u,a){let d=i.left+a.x,m=i.top+a.y;await this.performRawSwipe({startX:d,startY:m,deltaPixels:c,direction:t,durationMs:o})}else{let d=i.width*la,m=i.height*la,p={left:i.left+d,top:i.top+m,width:Math.max(1,i.width-2*d),height:Math.max(1,i.height-2*m)};await this.driver.executeScript("mobile: swipeGesture",[{...p,direction:t,percent:n,speed:u}])}}};var Yle=5,Sj=.8,Xle=1,IS=class extends Gu{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??Sj,o=await this.tryUseCachedScrollPosition(e,t);return o||this.searchForElement(e,t,n)}async resolveContainer({scrollableElement:e,containerCache:t,aiMetadata:n}){let o=await this.driver.getWindowRect();if(e.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:o.width,height:o.height}};if(e.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(e,o)};let i=X(),a=e.target.description;if(t){let u=this.getBoundsFromNativeCache(t);return this.logger.info({bounds:u},"Got container bounds from native cache"),{bounds:u,cache:t}}let s=await this.findElement({description:a,tracer:i,metadata:n});if(!s.success)throw new C("NoMatchingElementError",s.thoughts??"No matching element found");let{resolvedTarget:l}=s;if(l.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${a}" resolved to a webview element. Custom containers must be native elements.`);let c=this.getBoundsFromNativeCache(l);return this.logger.info({bounds:c},"Got container bounds from AI"),{bounds:c,cache:l}}async tryUseCachedScrollPosition(e,t){let n=e.cache?.target;return n?n.type==="WEBVIEW"?this.tryUseWebviewCache(e,t):n.scrollDetails?this.tryUseNativeScrollCache(e,t,n):null:null}async tryUseWebviewCache(e,t){let n=X();try{let{thoughts:o}=await this.wrapTargetingAction({command:e,tracer:n,description:t,action:async i=>{if(i.type==="NATIVE")throw new Error("Expected WEBVIEW target but got NATIVE");await this.scrollWebviewTargetIntoView(i)}});return{success:!0,message:o}}catch(o){return this.logger.warn({err:o},"Failed to use webview cache, falling back to search"),null}}async tryUseNativeScrollCache(e,t,n){let o=n.scrollDetails,i=X(),a=e.scrollStepPercent??Sj,s=o.scrollableElement.type==="CUSTOM"?o.scrollableElement.cache:void 0;await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:o.direction,scrollStepPercent:a,aiMetadata:{commandId:e.id}});try{let c=await this.tryFindElement({cmd:e,description:t,tracer:i,scrollDetails:o,useAIIfCacheFails:!1});if(c)return c;this.logger.info("Element not found at cached position, undoing scroll")}catch(c){this.logger.warn({err:c},"Error finding element at cached position, will undo scroll")}let l=o.direction==="down"?"up":"down";return this.logger.info({pixelDelta:o.pixelDelta,originalDirection:o.direction,undoDirection:l,scrollableElementType:o.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:l,scrollStepPercent:a,aiMetadata:{commandId:e.id}}),null}async tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:o,useAIIfCacheFails:i=!0}){let a,s,l=e.cache?.target;if(l&&l.resolvedDescription===t&&!e.disableCache){let u=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0});try{let{resolvedTarget:d}=await Vp({target:l,domState:u,stateManager:this.stateManager,logger:this.logger});a=d,s="Successfully resolved scroll to target with cache.",this.logger.info("Successfully resolved scroll to target from cache")}catch(d){this.logger.warn({err:d},"Failed to resolve target from cache")}}if(!a&&!i)return null;if(!a)try{let u=await this.findElement({description:t,tracer:n,metadata:{commandId:e.id}});if(!u.success)return null;a=u.resolvedTarget,s=u.thoughts}catch(u){if(u instanceof C&&u.reason==="NoMatchingElementError")return null;throw this.logger.warn({err:u},"Failed to find scroll-to target with AI"),u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),xl({command:e,updatedCache:_l(a),updatedWithAI:!0,logger:this.logger}),{success:!0,message:s}):(xl({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0,logger:this.logger}),{success:!0,message:s})}async searchForElement(e,t,n){let o=X(),i=await this.resolveContainer({scrollableElement:e.scrollableElement,aiMetadata:{commandId:e.id}});return this.scrollAndSearch(e,t,o,n,i)}async scrollAndSearch(e,t,n,o,i){let a=0,s=i.bounds,l=s.height*o,c=!0,u=e.maxScrollAttempts??Yle;for(let p=0;p<u;p++){this.throwIfAborted();let f=this.buildScrollDetails(e,a,i.cache),h=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:f});if(h)return h;if(!c)throw new Error(`ActionFailureError: Could not find element "${t}" after scrolling to the end`);this.logger.debug({attempt:p,cumulativePixelDelta:a},"Element not found, scrolling further");let g=Jle(e.scrollableElement);c=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:g}),a+=e.direction==="down"?l:-l}let d=this.buildScrollDetails(e,a,i.cache),m=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(m)return m;throw new Error(`ActionFailureError: Could not find element "${t}" after ${u} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollWebviewTargetIntoView(e){let{controller:t,browserTarget:n}=e;await t.browser.hover(n)}async scrollByPage({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o}){return X().startAsyncSpan("EMULATOR_INTERACTION",async a=>(a.attributes.containerBounds=t,a.attributes.direction=e,this.executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o})),{name:`Scroll ${e} by one page`})}async scrollByPixelDelta({pixelDelta:e,scrollableElement:t,containerCache:n,direction:o,scrollStepPercent:i,aiMetadata:a}){if(e===0)return;let s=X(),l,c,u;if(t.type==="CUSTOM_COORDINATES")l=t.startX,c=t.startY,u=t.deltaPixels;else{let p=(await this.resolveContainer({scrollableElement:t,containerCache:n,aiMetadata:a})).bounds,f=p.height*i,h=this.calculateSwipeCoordinates({containerBounds:p,direction:o,desiredDelta:f});l=h.startX,c=h.startY,u=h.actualDelta}let d=Math.ceil(Math.abs(e)/u);this.logger.debug({pixelDelta:e,direction:o,scrollableElementType:t.type,startX:l,startY:c,maxScrollPerStep:u,numScrolls:d},"scrollByPixelDelta calculated parameters"),await s.startAsyncSpan("EMULATOR_INTERACTION",async m=>{m.attributes.pixelDelta=e,m.attributes.numScrolls=d,m.attributes.maxScrollPerStep=u,m.attributes.startX=l,m.attributes.startY=c;let p=0;for(let f=0;f<d;f++){this.throwIfAborted();let h=Math.abs(e)-p,g=Math.min(u,h);await this.performRawSwipe({startX:l,startY:c,deltaPixels:g,direction:this.invertDirection(o)}),p+=g}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=Xle,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,l,c;if(i)s=i.startX,l=i.startY,c=i.deltaPixels;else{let p=t.height*n,f=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:p});s=f.startX,l=f.startY,c=f.actualDelta}await this.performRawSwipe({startX:s,startY:l,deltaPixels:c,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=es(a,u),m=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:m,direction:e,actualDelta:c,rawCoordinates:i},"Scroll gesture visual diff result"),m}};function Jle(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as Zle}from"crypto";import Kp from"fs";import{tmpdir as Qle}from"os";import Wu from"path";var OS=class extends rr{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install -r ${Wu.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(Kp.existsSync(n))o=n;else if(Kp.existsSync(Wu.join("/",n)))o=Wu.join("/",n);else throw new C("UserConfigurationError",`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new C("UserInfrastructureError",`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{Kp.unlinkSync(a)}catch(s){this.logger.warn({err:s,path:a},"Failed to remove temporary APK file")}}}}throw new C("UserConfigurationError",`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Wu.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{Kp.accessSync(e)}catch{throw new C("UserConfigurationError",`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Wu.extname(t)||".apk",o=Wu.join(Qle(),`momentic-apk-${Zle()}${n}`);return Kp.writeFileSync(o,e),o}};var NS=class extends rr{async dragNative(e,t,n){let{left:o,top:i,width:a,height:s}=this.getBoundsFromNativeCache(e),{left:l,top:c,width:u,height:d}=this.getBoundsFromNativeCache(t),m=o+a/2,p=i+s/2,f=l+u/2,h=c+d/2,g=n?.hoverDuration??500,y=n?.dragDuration??1e3;await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:m,y:p},{type:"pointerDown",button:0},{type:"pause",duration:g},{type:"pointerMove",duration:y,x:f,y:h},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}async dragWebview(e,t,n){let{controller:o}=e;if(e.controller!==t.controller)throw new C("UserConfigurationError","Cannot drag and drop between different webviews");let i=n?.dragDuration??1e3,a=n?.hoverDuration??1e3,s;n?.dragDuration&&(s=Math.max(1,Math.floor(i/200))),await o.browser.dragAndDrop(e.browserTarget,t.browserTarget,{hoverDurationMs:a,steps:s,dragDurationMs:i})}async executeDragAndDrop({command:e}){let t=X();if(e.fromTarget.type!=="description"||e.toTarget.type!=="description")throw new C("UserConfigurationError","Drag and drop only supports description targets for now");let n=e.fromTarget.description,{result:o,thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,description:n,cacheKey:"cache",targetName:"fromTarget",action:async c=>c}),a=e.toTarget.description,{result:s,thoughts:l}=await this.wrapTargetingAction({command:e,tracer:t,description:a,cacheKey:"cache",targetName:"toTarget",action:async c=>c});if(o.type!==s.type)throw new C("UserConfigurationError",`Drag and drop targets must be in the same context (both native or both webview). Found: From=${o.type}, To=${s.type}`);return await t.startAsyncSpan("EMULATOR_INTERACTION",async c=>{o.type==="NATIVE"&&s.type==="NATIVE"?await this.dragNative(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}):o.type==="WEBVIEW"&&s.type==="WEBVIEW"&&(c.withinWebview=!0,await this.dragWebview(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}))},{name:"Drag and drop"}),{success:!0,message:`${i}
4887
4887
  ${l}`}}};import{cloneDeep as bj}from"lodash-es";var LS=class{async getTextContent(e){return await e.textContent()??""}async getAttribute(e,t){return await e.getAttribute(t,{timeout:3e3})??""}async getTagName(e){return await e.evaluate(t=>t.tagName)}async isEditable(e){return await e.isEditable({timeout:ur*1e3})}async isEnabled(e){return await e.isEnabled({timeout:ur*1e3})}async isFocused(e){return await e.evaluate(t=>t===document.activeElement)}async getStyleProperty(e,t){return await e.evaluate((n,o)=>window.getComputedStyle(n).getPropertyValue(o),t)}},DS=class{async getTextContent(e){return Fp(e)}async getAttribute(e,t){return e.getAttribute(t)??""}async getTagName(e){return e.tagName}async isEditable(e){throw new Error("Cannot perform editable check on native element")}async isEnabled(e){return e.getAttribute("enabled")==="true"}async isFocused(e){return e.getAttribute("focused")==="true"}async getStyleProperty(e,t){throw new Error("Cannot perform computed style checks on native element")}};var ece=5e3,kS=class extends rr{async executeElementCheck(e){let t=Date.now(),n=(e.timeout??ur)*1e3,o=n+1e4,i,a=0,s=500,l=bj(e.cache);if(e.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Element check step");for(;a-t<n;){if(Date.now()-t>o){this.logger.warn("Exceeded max system timeout for element check, exiting...");break}if(this.throwIfAborted(),i=await this.executeElementCheckHelper(e),a=Date.now(),!i.success)e.cache=l,l=bj(l),await ee(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),ece);else return i}let c=await this.executeElementCheckHelper(e,{cacheIsInvalidAfterResolution:!0});if(!c.success&&l&&e.cache){let u=vp({logger:this.logger,originalTarget:Xs(l)?l.target:void 0,newTarget:e.cache.target});u&&na(l.target,u)&&(e.cache={target:u,updatedAt:e.cache.updatedAt})}return c}async executeElementCheckHelper(e,t){let n=X();if(e.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Element check step");let o=yu(e.assertion);try{return(await this.wrapTargetingAction({...t??{},command:e,tracer:n,action:async a=>"type"in a&&a.type==="NATIVE"?await this.executeNativeElementCheck(e,a):await this.executeWebviewElementCheck(e,a),description:e.target.description,skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).result}catch(i){return o&&(i instanceof C&&i.reason==="NoMatchingElementError"||i instanceof ni)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${i instanceof Error?i.message:`${i}`}`}}}async executeNativeElementCheck(e,t){let n=X(),{assertion:o}=e,i=t.resolvedNode;return await n.startAsyncSpan("ELEMENT_ASSERTION",async a=>{let s=await this.executeElementAssertion({assertion:o,element:i,elementPropertyAccessors:new DS,span:a});return a.result=s,s},{name:"Native element check"})}async executeWebviewElementCheck(e,t){let n=X(),o=t.browserTarget.locator,i=e.assertion;return await n.startAsyncSpan("ELEMENT_ASSERTION",async a=>{await t.controller.browser.highlight(o);let s=await this.executeElementAssertion({assertion:i,element:o,elementPropertyAccessors:new LS,span:a});return a.result=s,s},{name:"Webview element check"})}async executeElementAssertion({assertion:e,element:t,elementPropertyAccessors:n,span:o}){switch(e.type){case"ELEMENT_CONTENT":{let i=await n.getTextContent(t)??"";return o.attributes.elementTextContent=Xt(i,500,!0),pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${Ar(e)} '${e.value}': ${i}`}}case"ELEMENT_ATTRIBUTE":{"evaluate"in t&&(o.attributes.elementOuterHtml=Xt(await t.evaluate(a=>a.cloneNode(!1).outerHTML),500,!0));let i;try{i=await n.getAttribute(t,e.attr)}catch{i=null}if(!pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=Ar(e);return{success:!1,message:`The attribute ${e.attr} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}case"ELEMENT_EXISTENCE":{let i=!1;switch(e.condition){case"EDITABLE":i=await n.isEditable(t);break;case"VISIBLE":case"EXISTS":i=!0;break;case"ENABLED":{i=await n.isEnabled(t);break}case"FOCUSED":i=await n.isFocused(t);break;default:throw e.condition,new Error("Unrecognized element condition type")}return i=e.negated?!i:i,i?{success:!0}:{success:!1,message:`The element ${Ar(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${Ar(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=Ar(e);return{success:!1,message:`The style property ${e.property} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}default:throw new Error("Unrecognized element assertion type")}}};var tce=5e3,FS=class extends rr{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??ur)*1e3,i=o+1e4,a=0,s=500;for(;a-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}this.throwIfAborted();let l=await this.executeScreenCheckHelper(e);if(a=Date.now(),!l.success)await ee(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),tce);else return l}return await this.executeScreenCheckHelper(e)}async executeScreenCheckHelper(e){return await X().startAsyncSection("Execute screen check",async(n,o)=>{let[i,a]=await Promise.all([this.executeNativeScreenCheckHelper({span:o,command:e}),this.executeWebviewScreenCheckHelper(e)]);return a?e.assertion.negated?i.success&&a.success?i:i.success?a:i:i.success?i:a:i})}async executeNativeScreenCheckHelper({span:e,command:t}){let{assertion:n}=t;switch(n.type){case"CONTENT":try{let o=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!o)throw new Error("Failed to get screen HTML");let i=o.includes(n.value)===!n.negated;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),i?{success:!0}:(e.attributes.screenContent=o,{success:!1,message:`The screen ${Sp(n)}.`})}catch(o){return{success:!1,message:`Failed to evaluate screen content assertion: ${o instanceof Error?o.message:`${o}`}`}}default:return n.type,{success:!1,message:`Unsupported screen check assertion type: ${n.type}`}}}async executeWebviewScreenCheckHelper(e){let t=await this.stateManager.getActiveWebview();if(!t||!t.browserController)return;let n=t.browserController.browser;return await xS({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var US=class extends rr{async doUninstallApk(e){return await this.uninstallApkPackage(e.packageName),{success:!0,message:"Uninstalled APK."}}async uninstallApkPackage(e){let t=e.replace(/^package:/,""),n=await this.stateManager.executeRawADBCommand(`shell pm list packages | grep -E "^package:${t}$" || true`);if(!n||n.length===0)throw new C("UserConfigurationError",`Package ${t} not found`);if(n.split(`
4888
4888
  `).filter(i=>!!i).length>1)throw new C("UserConfigurationError",`Multiple packages found for ${t}`);try{await this.stateManager.executeRawADBCommand(`uninstall ${t}`)}catch(i){throw new C("UserInfrastructureError",`Failed to uninstall package ${t}: ${i}`)}}};import{createHash as nce}from"crypto";import{_android as oce,chromium as ice}from"playwright";import{z as Gt}from"zod";var Ej=Gt.object({"Android-Package":Gt.string(),Browser:Gt.string(),"Protocol-Version":Gt.string(),"User-Agent":Gt.string(),"V8-Version":Gt.string(),"WebKit-Version":Gt.string(),webSocketDebuggerUrl:Gt.string()}),Tj=Gt.object({description:Gt.string(),devtoolsFrontendUrl:Gt.string(),id:Gt.string(),title:Gt.string(),type:Gt.string(),url:Gt.string(),webSocketDebuggerUrl:Gt.string()}),vj=Gt.object({proc:Gt.string(),webview:Gt.string(),webviewName:Gt.string()}),Aj=Gt.array(vj.extend({info:Ej.optional(),pages:Gt.array(Tj).optional()})),V_t=Gt.array(vj.extend({info:Ej,pages:Gt.array(Tj)}));var BS=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:l,aborter:c}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=l,this.aborter=c;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:l,playwrightDevice:c}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(c)m=c;else{let f=(await oce.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:f.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),f.length===0)throw new C("UserInfrastructureError",`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(f.length>1)throw new C("UserInfrastructureError",`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=f[0]}let p=new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:l,limbarClient:o});return p.startWebviewRefreshInterval(),p}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=X(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{if(this.limbarClient){let a=await this.limbarClient.screenshot();if(a.dataUri.startsWith("data:image/png;base64,"))return a.dataUri.slice(22);throw new C("InternalWebAgentError",`Emulator provider returned unexpected screenshot URI: ${a.dataUri}`)}return await this.driver.takeScreenshot()},{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:2e3})}catch(i){if(n=i,this.logger.warn({err:i},"Failed to take screenshot"),o===e-1)throw i}throw new C("InternalWebAgentError",`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await X().startAsyncSpan("WAIT_FOR_SCREENSHOT_STABILITY",async i=>{i.attributes.reason=n;let a=Date.now(),s,l,c=!1;for(;Date.now()-a<e;){l&&l<500&&await ee(500-l,t),t?.throwIfAborted();let u=Date.now();if(!s){s=await this.getRawScreenshotBase64(),l=u-a;continue}let d=await this.getRawScreenshotBase64();if(l=u-a,es(s,d)<=o){c=!0;break}s=d}c||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async waitForPageSourceStability({timeoutMs:e,signal:t,reason:n}){await X().startAsyncSpan("WAIT_FOR_PAGE_STABILITY",async o=>{o.attributes.reason=n;let i=Date.now(),a,s,l=!1;for(;Date.now()-i<e;){s&&s<250&&await ee(250-s,t),t?.throwIfAborted();let c=Date.now(),u;try{u=await this.getPageSource()}catch(m){this.logger.warn({err:m},"Failed to get page source during stability wait"),s=Date.now()-c;continue}let d=nce("md5").update(u).digest("hex");if(s=Date.now()-c,a&&a===d){l=!0;break}a=d}l||(o.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for page source stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=[];for(let[o,i]of t.idToElement.entries())n.some(a=>a.id===o)||Wp(i)&&n.push({id:o,originalElement:i,bounds:Rl(i)});return n}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await X().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:this.logger,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await X().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent&&!this.options.disableMomenticAccessibilityTree)try{n=await this.getActiveWebviewContent()}catch(l){this.logger.error({err:l},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await lj(a,this.logger,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await X().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let n=Date.now();try{return await this.driver.getPageSource()}finally{let o=Date.now()-n;o>5e3&&this.logger.warn({durationMs:o},"getPageSource took very long")}},{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}refreshPromise;refreshInterval;webviewConnectionPromises=new Map;async refreshWebviewsManually(e){if(!this.options.disableMomenticAccessibilityTree){if(this.refreshPromise){await this.refreshPromise;return}this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=void 0),this.refreshPromise=this.doRefreshWebview(e,{currentAppOnly:!0}).catch(t=>{this.logger.warn({err:t},"Error refreshing webviews, continuing...")}).finally(()=>{this.refreshPromise=void 0,this.startWebviewRefreshInterval()}),await this.refreshPromise}}startWebviewRefreshInterval(){this.options.disableMomenticAccessibilityTree||this.refreshInterval||(this.refreshInterval=setInterval(()=>{if(this.refreshPromise){this.logger.debug("Skipping auto refresh while another refresh is running");return}this.refreshPromise=this.doRefreshWebview("auto refresh",{currentAppOnly:!1}).catch(e=>{this.logger.warn({err:e},"Error refreshing webviews, continuing...")}).finally(()=>{this.refreshPromise=void 0})},15e3))}async doRefreshWebview(e,{currentAppOnly:t}){if(this.options.disableMomenticAccessibilityTree)return;this.logger.info({reason:e,currentAppOnly:t},"Refreshing webviews"),await this.getPageSource(),this.throwIfAborted();let n=await this.getCurrentPackage();if(t&&n==="com.android.permissioncontroller")return;let o=await this.getDetailedContexts();if(!o){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let i=Date.now(),a=new Set;for(let s of o){if(this.throwIfAborted(),s.webview==="NATIVE_APP")continue;let l=s.info["Android-Package"];if(t&&n&&l!==n&&l!=="com.android.chrome"){this.logger.debug({packageName:l,currentPkgName:n},"Skipping webview outside the active package during manual refresh");continue}a.add(s.webview);let c=!this.webviews.has(s.webview),u=!this.webviews.get(s.webview)?.active;if(c||u){let d={contextId:s.webview,packageName:l,active:!1,lastSeen:i,socketName:s.proc.startsWith("@")?s.proc.substring(1):s.proc};this.logger.info({contextId:d.contextId,packageName:d.packageName,socketName:d.socketName},c?"New webview detected":"Inactive webview detected"),this.webviews.set(s.webview,d),this.logger.info({webviewInfo:d},`Connecting Playwright to webview: ${s.webview}`);let m=await this.connectPlaywrightToAvailableWebview(d);if(!m)continue;d.browserController=m,d.active=!0}}for(let[s,l]of this.webviews.entries())t&&n&&l.packageName!==n||!a.has(s)&&l.active&&(this.logger.info(`Disconnecting dead webview ${s}`),this.disconnectPlaywrightFromWebview(l),l.active=!1);this.logger.info("Refreshed webviews")}async getActiveWebview(){if(this.options.disableMomenticAccessibilityTree)return;await this.refreshPromise;let e=await this.driver.execute("mobile: getCurrentPackage"),t=async()=>{e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let a=[];for(let s of this.webviews.values())s.packageName===e&&s.active&&a.push(s);return this.logger.info({currentPkg:e,allWebviews:Array.from(this.webviews.values()).map(s=>({contextId:s.contextId,packageName:s.packageName,active:s.active}))},`getActiveWebview: found ${a.length} matching webviews`),a},n=await t();if(n.length===0&&(await X().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviewsManually("no matching webview during getActiveWebview")}),n=await t()),n.length>1)throw new C("UserInfrastructureError","Multiple active webviews in a single package is currently not supported");let o=n[0];if(!o)return;if(this.hasUsableWebviewBrowser(o)||(this.logger.warn({contextId:o.contextId,packageName:o.packageName},"Active webview browser is unhealthy, reconstructing"),await this.reconstructWebviewBrowser(o,"active webview page or target crashed"),this.hasUsableWebviewBrowser(o)))return o;if(await X().startAsyncSection("Refresh webviews after browser reconstruction failed",async()=>{await this.refreshWebviewsManually("active webview browser reconstruction failed")}),n=await t(),n.length>1)throw new C("UserInfrastructureError","Multiple active webviews in a single package is currently not supported");let i=n[0];if(i){if(this.hasUsableWebviewBrowser(i))return i;this.logger.warn({contextId:i.contextId,packageName:i.packageName},"Refreshed active webview is still unhealthy after reconstruction")}}async reconstructActiveWebviewBrowser(e){if(this.options.disableMomenticAccessibilityTree)return;await this.refreshPromise;let t=await this.driver.execute("mobile: getCurrentPackage");if(t!==void 0&&typeof t!="string"){this.logger.warn({currentPkg:t},"Unexpected getCurrentPackage result");return}let n=[];for(let i of this.webviews.values())i.packageName===t&&i.active&&n.push(i);if(n.length>1)throw new C("UserInfrastructureError","Multiple active webviews in a single package is currently not supported");let o=n[0];if(o)return await this.reconstructWebviewBrowser(o,e),this.hasUsableWebviewBrowser(o)?o:void 0}hasUsableWebviewBrowser(e){let t=e.browserController;if(!t||!e.active)return!1;let n=t.browser;if(n.closed)return!1;let o;try{o=n.getActivePage()}catch(i){return this.logger.warn({err:i,contextId:e.contextId},"Failed to resolve active page for webview browser health check"),!1}return!o.isClosed()}async reconstructWebviewBrowser(e,t){this.logger.info({contextId:e.contextId,packageName:e.packageName,reason:t},"Reconstructing webview browser"),await this.disconnectPlaywrightFromWebview(e),e.active=!1;let n=await this.connectPlaywrightToAvailableWebview(e);n&&(e.browserController=n,e.active=!0)}getDeviceSerial(){let e=this.driver.capabilities,t=n=>{if(!e||typeof e!="object")return;let o=e[n];return typeof o=="string"?o:void 0};return t("deviceUDID")||t("udid")||t("appium:udid")||t("appium:deviceUDID")}async executeRawADBCommand(e){let t=this.getDeviceSerial(),n=e.trim().split(/\s+/).filter(i=>i.length>0);this.logger.info({serial:t,cmdArgs:n},"Executing ADB command");let o=await mr(n,{serial:t,timeoutMs:15e3,throwOnError:!0});return this.logger.info({result:o},"ADB command result"),o}async cleanupWebviews(){this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=void 0);for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await X().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=Aj.parse(t)}catch(o){throw new C("InternalWebAgentError",`Failed to parse contexts. Original error:
4889
4889
  ${o}
4890
4890
  Raw: ${JSON.stringify(t)}`)}return n.filter(o=>o.webviewName?!o.info||!o.pages?!1:o.pages.filter(a=>{if(!a.title)return!1;let s=a.url;return!(!s||s===""||s.startsWith("about:blank")||s.startsWith("chrome-error:"))}).length?!0:(this.logger.debug({context:o},"Webview has no qualified pages, skipping"),!1):!0)},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e,page:t}){return await X().startSection("Run remote Chrome initialization",async(o,i)=>{let a={};i.attributes.timings=a;let s=await jp.fromExistingContext({context:e,page:t,attachTimeoutMs:8e3,logger:this.logger,timingRecorder:a,userBrowserSettings:{...this.options.browserSettings,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});try{return new _S({browser:s,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new ng})}catch(l){throw await s.cleanup(),l}})}async connectPlaywrightToWebview(e,t){return X().startAsyncSection("Connect headless browser client to webview",async()=>{for(let o=0;o<2;o++)try{let i=await this.connectPlaywrightToWebviewHelper(e,t);return i?{kind:"connected",browserController:i}:{kind:"failed"}}catch(i){if(i instanceof Vd)return{kind:"not_found"};if(this.errorLooksLikeUnattachableWebview(i))return this.logger.info({err:i,packageName:e,socketName:t},"Skipping Playwright connection for webview because the target is not attachable"),{kind:"not_attachable"};this.logger.warn({err:i},"Failed to connect Playwright to webview, retrying...")}return{kind:"failed"}},{signal:this.aborter.controller?.signal})}errorLooksLikeUnattachableWebview(e){let t=e instanceof Error?e.message:String(e);return["No page found in existing context","Target closed","Target crashed","Page crashed","Target page, context or browser has been closed","Session closed. Most likely the page has been closed"].some(n=>t.includes(n))}async connectPlaywrightToAvailableWebview(e){let t=this.webviewConnectionPromises.get(e.contextId);if(t)return this.logger.debug({contextId:e.contextId},"Waiting for existing webview connection attempt"),t;let n=X().startAsyncSection("Connect Playwright to available webview",async()=>await this.connectPlaywrightToAvailableWebviewHelper(e),{signal:this.aborter.controller?.signal}).catch(o=>{this.logger.warn({err:o,contextId:e.contextId},"Failed to connect Playwright to webview, continuing...")});return this.webviewConnectionPromises.set(e.contextId,n),n.finally(()=>{this.webviewConnectionPromises.get(e.contextId)===n&&this.webviewConnectionPromises.delete(e.contextId)}),n}async connectPlaywrightToAvailableWebviewHelper(e){let{contextId:t,packageName:n}=e,o=await this.connectPlaywrightToWebview(n??"",e.socketName);if(o.kind==="connected")return this.logger.info(`Connected Playwright to webview ${t}`),o.browserController;if(n!=="com.android.chrome"||o.kind!=="not_found")return;this.logger.info({webviewInfo:e},`Connecting Playwright to Android Chrome: ${t}`);let i=await this.connectPlaywrightToChrome(e);return i&&this.logger.info(`Connected Playwright to Android Chrome: ${t}`),i}extractSocketNameFromWebview(e,t){if("_socketName"in e&&typeof e._socketName=="string")return e._socketName;if("_data"in e&&e._data?.socketName)return e._data.socketName;t.warn({pkg:e.pkg()},"Could not extract socket name from webview")}async connectPlaywrightToWebviewHelper(e,t){let n=this.device.webViews(),o=n.find(c=>!(c.pkg()!==e&&e!=="com.android.chrome"||this.extractSocketNameFromWebview(c,this.logger)!==t));if(!o)throw this.logger.warn({webviews:n.map(c=>({pkg:c.pkg,name:this.extractSocketNameFromWebview(c,this.logger)}))},"Could not find matching webview in Playwright device list"),new Vd(e,t);let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){let c=`Webview ${e} with socket ${t} is not a valid webview`;this.logger.warn({pageUrl:a},c);return}let s=i.context();return await this.createBrowserController({context:s,page:i})}async connectPlaywrightToChrome(e){return await X().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e,o,i=e.forwardedPort;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let a;if(e.forwardedPort)a=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:a,socketName:n},"Using existing forwarded port");else{let c=await this.forwardDevToolsSocket(e.socketName);e.forwardedPort=c,i=c,a=`http://127.0.0.1:${c}`,this.logger.info({contextId:t,endpoint:a,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)}this.logger.info({endpoint:a,socketName:n},"Connecting to CDP endpoint"),o=await ice.connectOverCDP({endpointURL:a,timeout:8e3});let s=o.contexts()[0];if(!s){this.logger.warn("No browser context available after CDP connection"),await o.close(),o=void 0;return}let l=await this.createBrowserController({context:s});return i=void 0,o=void 0,l}catch(a){this.logger.warn({err:a},`Error connecting Playwright to webview ${e.contextId}, continuing...`);return}finally{if(o)try{await o.close()}catch(a){this.logger.warn({err:a,contextId:t},"Failed to close orphaned CDP browser after webview connection failure")}if(i)try{await this.removeDevToolsForwarding(i)}catch(a){this.logger.warn({err:a,contextId:t,forwardedPort:i},"Failed to remove forwarded port after webview connection failure")}finally{e.forwardedPort===i&&(e.forwardedPort=void 0)}}}async disconnectPlaywrightFromWebview(e){if(e.browserController)try{this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup()}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}finally{e.browserController=void 0}if(e.forwardedPort)try{await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error removing forwarded port for webview ${e.contextId}:`)}finally{e.forwardedPort=void 0}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.getDeviceSerial();this.logger.info({deviceId:n},`Device ID from capabilities: ${n||"not found"}`);let o=e&&e.trim().length>0?`localabstract:${e}`:"localabstract:chrome_devtools_remote";return await this.executeRawADBCommand(`forward tcp:${t} ${o}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var ss=class r extends rr{appsWithGrantedPermissions=new Set;parseInstalledPackageLines(e){return e?.split(`
4891
4891
  `).filter(t=>t.trim().startsWith("package:")).map(t=>t.replace("package:","").trim()).filter(t=>t.length>0&&!t.startsWith("io.appium"))??[]}constructor(e){super(e)}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:l,limbarClient:c,playwrightDevice:u,aiSettings:d}){let m={controller:s},p=await BS.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:c,options:a?.emulator??{},aborter:m,adbPort:l,playwrightDevice:u}),f=new r({driver:e,generator:t,stateManager:p,logger:n,fixtures:o,options:a,aborter:m,orgId:i,aiSettings:d,adbPort:l});return await f.initializeSettings(),f}get emulatorSettings(){return this.options?.emulator??{}}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${sce.resolve(e)}`)}async getInstalledApps(){let[e,t]=await Promise.all([this.executeRawADBCommand("shell pm list packages -3"),this.executeRawADBCommand("shell pm list packages")]),n=this.parseInstalledPackageLines(e).sort((a,s)=>a.localeCompare(s)),i=this.parseInstalledPackageLines(t).filter(a=>!n.includes(a)&&!lC(a)).sort((a,s)=>a.localeCompare(s));return{installedApps:n,prunedApps:i}}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Iu({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new C("UserConfigurationError",`Failed to substitute template strings in command: ${o.message}`,{errOptions:{cause:o}})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Ou(e.command,n)}}async executeCommandHelper({command:e}){let t=X();switch(e.type){case"TAP":return new ju(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new PS(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let n=this.shouldUseMemoryForCommand(e),o=15,i=e.timeoutSecs?e.timeoutSecs*1e3:5e3,a=vy(i),s=Date.now(),l=0,c,u=!1,d;for(;l<o&&!u;){this.throwIfAborted(),u||c&&c-s>=i&&(u=!0),l!==0&&await ee(a,this.abortSignal),c=Date.now();try{let m="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{m=await this.getEmulatorDomState(),p=await this.getScreenshotBase64()},{name:"Get emulator state"});let f=await t.startAsyncSpan("AI_ASSERTION_CALL",async h=>{let g=await this.generator.evaluateAndroidAssertion({assertion:e.assertion,screenXml:m,screenshot:p,memory:n?e.cache?.memory:void 0},{logger:this.logger,loggerTags:Ee(this.logger),agentConfigVersion:this.aiSettings.agentConfig?.["android-assertion"],useMemory:n});return h.result={thoughts:g.thoughts,result:g.result},g});if(n&&f.updatedMemory){let h={type:"GCS_TRACES",traces:f.updatedMemory};e.cache={...e.cache??{},memory:h}}if(f.result)return{success:f.result,message:f.thoughts};{let h=`AssertionFailureError: ${f.thoughts}`;d=new Error(h)}}catch(m){this.throwIfAborted(),this.logger.info({err:m},`AI check assert attempt ${l} failed, retrying...`),d=m instanceof Error?m:new Error(`${m}`)}finally{l++}}return{success:!1,message:d?.message}}case"AI_EXTRACT":{if(!e.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(e.schema){let i=Yc(e.schema);if(i)throw new C("UserConfigurationError",i)}let n="",o="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{n=await this.getEmulatorDomState(),o=await this.getScreenshotBase64()},{name:"Get emulator state"});try{let i=await this.generator.getAndroidTextExtraction({goal:e.goal,emulatorState:n,returnSchema:e.schema,screenshot:`data:image/png;base64,${o}`},{disableCache:!!e.disableCache,abortSignal:this.abortSignal,loggerTags:Ee(this.logger),agentConfigVersion:this.aiSettings.agentConfig?.["android-text-extraction"]});if(i.result==="NOT_FOUND")return{success:!1,message:"No relevant data found for extraction goal on this page"};if(i.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",i.thoughts);return{success:!0,output:i.result,message:i.thoughts}}catch(i){let a=i instanceof Error?i.message:String(i);throw a.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step instead."):a.includes("AIProviderError")&&a.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:i}}):i}}case"SWIPE":return new Gu(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new FS(this.constructPerformerParams()).executeScreenCheck(e);case"ELEMENT_CHECK":return await new kS(this.constructPerformerParams()).executeElementCheck(e);case"DRAG_AND_DROP":return await new NS(this.constructPerformerParams()).executeDragAndDrop({command:e});case"SCROLL_TO":return new IS(this.constructPerformerParams()).executeScrollTo(e);case"JAVASCRIPT":{let n;try{n=await bo({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal})}catch(o){throw new C("ActionFailureError",o instanceof C?o.message:`${o}`,{errOptions:{cause:o}})}try{JSON.stringify(n)}catch(o){throw new C("UserConfigurationError",`Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(c){throw new C("UserConfigurationError",`Invalid URL: ${c instanceof Error?c.message:`${c}`}`)}let o=new lce,i=ace(fetch,o),a=Date.now(),s=await $u({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),l=Dc(o,n);return{output:Is.parse({...s,cookies:l}),success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new as(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await J(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new C("UserConfigurationError",`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new C("UserConfigurationError",`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
4892
- `).pop()?.replace(/^.*\//,""),!n)throw new C("UserConfigurationError",`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options?.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new C("UserConfigurationError",`Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForPageSourceStability({timeoutMs:3e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),this.stateManager.refreshWebviewsManually("new app launch"),{success:!0}}case"PRESS":{let n=new as(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new as(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<2e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await ee(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new OS(this.constructPerformerParams()).doInstallApk(e);case"UNINSTALL_APP":return new US(this.constructPerformerParams()).doUninstallApk(e);case"ADD_FILE":{let n=await rS(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"TOGGLE_SETTINGS":{switch(e.settingsType){case"AIRPLANE_MODE":await this.driver.toggleAirplaneMode();break;case"DATA":await this.driver.toggleData();break;case"WIFI":await this.driver.toggleWiFi();break;case"LOCATION":await this.driver.toggleLocationServices();break;default:throw e.settingsType,new C("UserConfigurationError",`Unknown settings type: ${e.settingsType}`)}return{success:!0}}case"ROTATE_ORIENTATION":return await this.driver.execute("mobile: shell",{command:"settings",args:["put","system","accelerometer_rotation","0"]}),await this.driver.execute("mobile: shell",{command:"settings",args:["put","system","user_rotation",e.orientation==="LANDSCAPE"?"1":"0"]}),{success:!0,output:{newViewportBounds:await this.getViewportBounds()}};case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new C("UserConfigurationError","No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await K1({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviewsManually("debug cmd");let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??vc;await this.driver.execute("mobile: setGeolocation",{latitude:e,longitude:t}),await Promise.all([this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),this.driver.updateSettings({keyInjectionDelay:Ml})])}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getEmulatorDomState(){return(await this.stateManager.getDomState({})).graph.xml}async executeRawADBCommand(e){return this.stateManager.executeRawADBCommand(e)}async softReset(){await X1(this,this.logger),this.fixtures.testContext.resetToInitial()}async getViewportBounds(){return this.stateManager.getViewportBounds()}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??3e3,reason:e.reason,signal:this.aborter.controller?.signal})}async getMobileFailureRecoveryPlan(e){return this.generator.getAndroidFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.abortSignal,loggerTags:Ee(this.logger)})}async waitForPageSourceStability(e){return this.stateManager.waitForPageSourceStability({timeoutMs:e.timeoutMs??3e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};import{tmpdir as cce}from"os";import Rj from"path";async function xj({socket:r,logger:e,orgId:t,testMetadata:n,globalOrgSettings:o,androidDriverFactory:i,mobileGeneratorFactory:a,browserGeneratorFactory:s,browserEnricherFactory:l,storageFactory:c,localToolsFactory:u,globalStateManager:d,getGitMetadata:m}){let p=r.id,f=await m(),h=r.handshake.query?.fileName,g=h?Rj.basename(h,".test.yaml"):"",y=n.id,b=n.settings?.defaultChannel,E=n.settings?.defaultTag;e=e.child({sessionId:p,testId:y,orgId:t,branch:f.gitBranchName});let v=await c(t),w=n.settings?.defaultEnv,L={};w&&(L=(await v.fetchEnvironment(w,e))?.variables??{});let I=Hc.parse(L[ji]),A=Hc.parse(L[Th]),_={...o.emulator,...n.settings?.emulator},O=n.settings?.defaultApkFilePath?.trim()||A,k=d.getSession(p);if(k){if(e.info("Reconnecting to existing Android session"),k.local)return r.emit("session",k.metadata),k.softDeleted=!1,k.metadata;throw new Error("Restoring existing remote emulator sessions is not supported. Please reconnect to a new emulator.")}let D;if(_.region==="local"){if(await d.clearSoftDeletedLocalSessions(e),d.hasActiveLocalSession())throw new Error("Another local emulator session is already active. Please close the existing session before creating a new one.");let Io=n.settings?.emulator?.localEmulatorSettings?.avdId?.trim()||I;if(!Io)throw new Error(`AVD ID is required when using a local emulator. Set it on the test (Options \u2192 Emulator \u2192 Local AVD ID) or on the environment via ${ji}.`);D={avdId:Io,apkToInstall:b?{channel:b,tag:E}:void 0,apkFilePath:O}}else D={region:_.region,apkToInstall:b?{channel:b,tag:E}:void 0,osVersion:_.remoteEmulatorSettings?.androidVersion};let j=Date.now(),$=await i({socket:r,logger:e,creationOpts:D}),{driver:xe,cleanup:B,emulatorName:Z,adbPort:ie}=$,se,Pe,we,he,Ie;"limbarClient"in $&&(se=$.limbarClient,Pe=$.limbarToken,we=$.limbarUrl,he=$.limbarRegion,Ie=$.playwrightDevice);let Ot=Rj.join(cce(),`logcat-logs-${t}-${y}-${p}.txt`),ke=await aS({driver:xe,onLogs:Io=>{r.emit("logcatLogs",Io)},logFilePath:Ot});e.info({adbPort:ie,apkChannel:b,apkTag:E,duration:Date.now()-j,emulatorName:Z},"Android emulator session initiated"),e=e.child({emulator:Z});let M=await a(t,e),me=await s(t,e),ye=await l(t,e),Ql=u?await u(t):void 0,Pd=new io({variablesFromEnvironment:L,envName:w,testName:g}),Xf=await ss.init({driver:xe,generator:M,logger:e,limbarClient:se,playwrightDevice:Ie,aiSettings:{...o.ai,useMemory:o.ai?.useMemory!==!1,...n.settings?.ai},options:{emulator:{..._,browserSettings:o.browser}},fixtures:{storage:v,browserEnricher:ye,browserGenerator:me,localCodeEvalTools:Ql,testContext:Pd},orgId:t,adbPort:ie,abortController:new AbortController}),x4=await Xf.getViewportBounds();if(!r.connected)throw await Xf.cleanup(),await ke(),await B(),new Error("Socket not connected anymore, not proceeding with Android session setup");let ge=uce({socket:r,testContext:Pd}),_4=async()=>{clearInterval(ge);try{await Xf.cleanup()}catch(Io){e.warn({err:Io},"Failed to clean up controller in socket server")}try{await ke()}catch(Io){e.warn({err:Io},"Failed to stop log listener in socket server")}try{await B()}catch(Io){e.warn({err:Io},"Failed to clean up emulator in socket server")}},YE={sessionId:p,testId:y,orgId:t,emulatorName:Z,testName:g,limbarUrl:we,limbarToken:Pe,limbarRegion:he,viewportBounds:x4,envName:w};return d.registerSession(p,{platform:"ANDROID",controller:Xf,cleanup:_4,emulatorName:Z,local:_.region==="local",metadata:YE,logFilePath:Ot}),r.emit("session",YE),YE}function uce({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}import zS from"fs/promises";async function _j({socket:r,logger:e,globalStateManager:t,authorization:n}){let o=r.id,i=t.getSession(o);i&&i.platform==="ANDROID"&&n&&i.logFilePath&&dce({testId:i.metadata.testId,sessionId:o,logFilePath:i.logFilePath,authorization:n,logger:e}),await t.removeSession(o,e)}async function dce({testId:r,sessionId:e,logFilePath:t,authorization:n,logger:o}){try{let i;try{i=await zS.stat(t)}catch{o.debug({logFilePath:t},"No logcat file found to upload");return}if(i.size===0){o.debug({logFilePath:t},"Logcat file is empty, skipping upload"),await zS.unlink(t);return}let a=new Or(n),{uploadUrl:s}=await a.generateMobileLogcatUploadUrl({testId:r,sessionId:e}),l=await zS.readFile(t),c=await fetch(s,{headers:{"Content-Length":l.length.toString(),"Content-Type":"text/plain"},method:"PUT",body:l});if(c.status!==200)throw new Error(`Failed to upload logcat: ${c.status} ${await c.text()}`);o.info({testId:r,sessionId:e},"Logcat file uploaded successfully")}catch(i){o.warn({err:i,testId:r,sessionId:e},"Failed to upload logcat file")}finally{try{await zS.unlink(t)}catch(i){o.warn({err:i,logFilePath:t},"Failed to delete temp logcat file")}}}var mce=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Mobile session found");t.controller.abort()},Mj={event:"cancel",createHandler:mce};var pce=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Mobile session found"});return}try{let a=i.controller;a.resetAbortController();let s=await a.getEmulatorDomState();o({screenXml:s})}catch(a){r.error({err:a},"Error fetching screen XML from the session controller"),o({err:a.message})}},Pj={event:"fetchScreenXml",createHandler:pce};var rR=class{parentTracer;socket;step;orgId;interactionTracer;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o,this.interactionTracer=new Eo,Yr.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeXmlSnapshot(){}attachAfterXmlSnapshot(){}recordStepDuration(e){let{durationMs:t,step:n}=e;if(!ag(n))return;let o=ig(n);gt.distribution("test_step_duration",t,[`type:${o}`,"platform:mobile","executor:editor",`orgId:${this.orgId}`])}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={result:e.result,parentStepIdChain:e.parentStepIdChain,trace:Ov.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Vu({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},Vu=class{parentTracer;parentStep;socket;orgId;constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,this.orgId=o}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new rR({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async getScreenshot(e){}},$S=class{constructor(e,t){this.socket=e;this.orgId=t}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Vu({parentStep:null,parentTracer:null,socket:this.socket,orgId:this.orgId})}async startMainStepList(){return new Vu({parentStep:null,parentTracer:null,socket:this.socket,orgId:this.orgId})}async startAfterStepList(){return new Vu({parentStep:null,parentTracer:null,socket:this.socket,orgId:this.orgId})}};var fce=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o,getGitMetadata:i})=>async(a,s)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Mobile session found");let c=await i(),u=e.child({testId:a.testMetadata.id,branch:c.gitBranchName}),d=await o(r.orgId,c),m=l.controller;m.resetAbortController();let p=new $S(n,r.orgId),f=await Nu({platform:l.platform,work:{fastForwardingToStep:!!a.fromStep,state:{failureRecoveryDisabled:!0,failureRecoveryAttempts:0}},fixtures:{controller:m,logger:u,cacheStorage:d,usageTracker:new xa},containerName:"entire test",inputs:{steps:a.steps,fromStep:a.fromStep,toStep:a.toStep,orgId:r.orgId,testName:r.testName,testMetadata:a.testMetadata,interactive:!0},envName:r.envName,tracer:p,callbacks:{step:{onAiActionEvent:g=>{n.emit("aiActionEvent",g)}}}});await p.finish();let h={results:Un.array().parse(f.results),status:f.status};s?.(h)},Ij={event:"execute",createHandler:fce};import{debounce as hce}from"ts-debounce";var gce=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=hce(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Mobile session found");o.emulatorName&&(o.local||n(o.platform,o.emulatorName))}},Oj={event:"keepalive",createHandler:gce};var yce=({socket:r,globalStateManager:e,logger:t})=>async(n,o)=>{let i=e.getSession(r.id);if(!i){let s="No active session found";t.error(s),o?.({success:!1,err:s});return}let a=i.controller;a.abort(),a.resetAbortController(),t.info({platform:i.platform},"Resetting emulator state");try{await a.softReset(),t.info({platform:i.platform},"Emulator reset completed"),o?.({success:!0,message:"Emulator reset successfully"})}catch(s){let l=s instanceof Error?s.message:String(s);t.error({err:s,platform:i.platform},"Failed to reset emulator"),o?.({success:!1,err:`Failed to reset emulator: ${l}`})}},Nj={event:"reset",createHandler:yce};var Lj=[Ij,Mj,Nj,Oj,Pj];var HS="NATIVE_APP";var jS=class{constructor(e){this.driver=e}async executeWebViewScript(e,t,...n){return this.executeInContext(e,async o=>{let i=new Function("...args",`${Bp.safariUtilsLibJs}; const userFn = ${t.toString()}; return userFn(momenticFunctions, ...args);`);return o.execute(i,...n)})}async executeInNativeContext(e){return this.executeInContext(HS,e)}async executeInContext(e,t){return await this.driver.switchContext(e),await t(this.driver)}};var Sce=1e4,bce=1e4;function Dj(r,e,t,n){let o=0;async function i(){try{await J(r.executeScript("mobile: getDeviceTime",[]),{milliseconds:bce}),o>0&&(e.info("iOS driver heartbeat restored"),n?.()),o=0}catch(s){o++;let l=s instanceof Error?s.message:`${s}`;if(e.warn({attempt:o,error:l},"iOS driver heartbeat failed"),o>=3){let c="The iOS driver appears unresponsive, indicating a possible emulator failure";e.error({err:s},c),P.error(c),t?.()}}}let a=setInterval(()=>{i()},Sce);return i(),a}import{createInstanceClient as Ece}from"@limrun/api/ios-client";import{hostname as Tce}from"os";async function kj(r){let{apiClient:e,logger:t,creationOpts:n,logLevel:o,orgId:i,sessionId:a,onStatusUpdate:s,onConnectionStateChange:l}=r,c=n.appToInstall?.channel,u=n.appToInstall?.tag;s(`Creating iOS emulator${c?` with app channel ${c}`:""}${u?` and tag ${u}`:""}`);let{token:d,webRtcUrl:m,wdaUrl:p,apiUrl:f,id:h,region:g}=await e.createIosEmulator({...n,hostname:Tce(),sessionId:a});t.info({emulatorName:h,region:g,sessionId:a},"ios instance creation ok"),s("Connecting to iOS emulator...");let y=await gt.recordDuration({fn:async()=>await Ece({apiUrl:f,token:d,logLevel:o}),name:"test_event_duration",tags:["name:limbar-client-creation","clientOs:ios",`orgId:${i}`]});return l&&y.onConnectionStateChange(l),{close:()=>{y.disconnect()},limbarToken:d,limbarWebRtcUrl:m,limbarApiUrl:f,limbarWdaUrl:p,limbarRegion:g,emulatorName:h,limbarClient:y}}async function Fj({wdaUrl:r,token:e}){try{let t=new AbortController;return setTimeout(()=>t.abort(),3e3),await fetch(r+"/status",{headers:{Authorization:`Bearer ${e}`},signal:t.signal}),!0}catch{return!1}}async function GS({creationOpts:r,apiClient:e,logger:t,driverLogLevel:n,appiumPort:o,orgId:i,sessionId:a,callbacks:s}){let l=Date.now();t.info("Starting ios driver creation");let{onLimbarConnectionStateChange:c}=s,u=[];s.onStatusUpdate("Starting iOS emulator creation...");let d=await kj({apiClient:e,logger:t,creationOpts:r,orgId:i,sessionId:a,onStatusUpdate:s.onStatusUpdate,onConnectionStateChange:c,logLevel:n}),m=d.emulatorName;u.push(()=>e.deleteIosEmulator(m),d.close);let p=async()=>{for(let f=u.length-1;f>=0;f-=1)try{await u[f]()}catch(h){if(h instanceof Error&&["ECONNREFUSED","ECONNRESET","UND_ERR_CLOSED"].some(g=>h.message.includes(g)))continue;t.warn({err:h},"Error running cleanup task")}};try{let f=await vce({logger:t,driverLogLevel:n,appiumPort:o,emulatorStart:l,emulatorCreationParams:d,apiClient:e,creationOpts:r,orgId:i,sessionId:a,callbacks:s});u.push(f.appiumClose),u.push(async()=>f.driver.deleteSession()),f.driver.getPageSource().catch(()=>{});let h=Dj(f.driver,t,s.onHeartbeatFailure,s.onHeartbeatRestored);return u.push(()=>{clearInterval(h)}),{...d,...f,driver:new jS(f.driver),cleanup:p,appiumPort:o}}catch(f){throw await p(),new Error(`Failed to start Appium driver: ${f}`,{cause:f})}}async function vce({logger:r,driverLogLevel:e="error",emulatorStart:t,appiumPort:n,emulatorCreationParams:o,callbacks:{onStatusUpdate:i,onLimbarConnectionStateChange:a}}){let s=[],{emulatorName:l,limbarWdaUrl:c,limbarApiUrl:u,limbarToken:d,limbarClient:m}=o,p=Date.now(),f,h;({close:f,logFile:h}=await Lu({logger:r,logLevel:e,appiumPort:n})),await Fj({wdaUrl:c,token:d})||(i("Starting WebDriverAgent..."),r.debug({emulatorName:l},"WDA is not running on the Limbar iOS emulator"),await m.simctl(["launch","booted","com.facebook.WebDriverAgentRunner.xctrunner"]).wait(),r.debug({emulatorName:l},"WDA launched"));let g={platformName:"iOS","appium:automationName":"XCUITest","appium:noReset":!0,"appium:fullReset":!1,"appium:webDriverAgentUrl":c,"appium:wdaLocalPort":443,"appium:useNewWDA":!1,"appium:usePreinstalledWDA":!0,"appium:newCommandTimeout":3600,"appium:autoWebview":!1,"appium:webviewConnectTimeout":500,"appium:webviewConnectRetries":5,"appium:includeSafariInWebviews":!0,"appium:fullContextList":!1,"appium:additionalWebviewBundleIds":["*"],"appium:waitForIdleTimeout":0,"appium:settings":{customSnapshotTimeout:0},"appium:limInstanceApiUrl":u,"appium:limInstanceToken":d,"appium:wdaRequestHeaders":{Authorization:`Bearer ${d}`}};i("Starting Appium session...");let y={capabilities:g,hostname:"localhost",port:n,path:"/",protocol:"http",logLevel:e},b=Date.now(),{driver:E,appiumLogFile:v,appiumServerClose:w}=await iS({logger:r,onStatusUpdate:i,wdOpts:y,appiumPort:n,appiumLogFile:h,appiumServerClose:f,startAppiumServer:()=>Lu({logger:r,logLevel:e,appiumPort:n}),onFailure:async({err:A,attempt:_})=>{let O=oS(A),k=_<3&&O;return k&&r.warn({err:A,appiumPort:n},"Appium driver manifest race detected on first attempt, restarting Appium and retrying"),{shouldRetry:k}}});h=v,f=w;let L=new Map;return E.on("command",A=>{L.set(A.command,Date.now())}),E.on("result",A=>{let _=L.get(A.command);if(!_)return;let O=Date.now()-_;A.result instanceof Error?r.warn({err:A.result,command:A.command,args:A.body,durationMs:O},"Appium cmd failed"):O>1e4&&r.warn({command:A.command,args:A.body,durationMs:O},"Appium cmd took very long"),L.delete(A.command)}),r.info({timings:{emulatorDuration:p-t,appiumDuration:b-p,wdioDuration:Date.now()-b},capabilities:g,emulatorName:l},"Started Appium driver"),{onStatusUpdate:i,driver:E,appiumClose:async()=>{await f(),await Promise.all(s.map(A=>A()))},appiumPort:n,appiumLogFile:h,emulatorName:l}}import{createHash as Uce}from"crypto";import Bce from"jpeg-js";import{PNG as qj}from"pngjs";import Pce from"@prettier/plugin-xml";import Ice from"prettier";import{DOMParser as Oce,XMLSerializer as Nce}from"slimdom";import{reduce as Ace}from"lodash-es";var wce=new Set(["id","processId","bundleId","type","accessible","index","x","y","width","height"]),Cce=new Set([]),Rce=new Set(["name","label","traits"]),xce=new Set(["live-region","drawing-order"]),_ce=new Set(["visible","enabled"]);function Uj(r){let e={},t=r.tagName,n=Ace(r.attributes,(o,i)=>(o[i.name]=i.value,o),{});for(let[o,i]of Object.entries(n))wce.has(o)||o==="class"&&t===i||o==="focusable"&&i==="true"&&n.clickable==="true"||Cce.has(o)&&i==="false"||Rce.has(o)&&i===""||_ce.has(o)&&i==="true"||xce.has(o)&&i==="0"||(e[o]=i);return e.name&&e.label&&e.name===e.label&&delete e.label,e.name&&e.value&&e.name===e.value&&delete e.value,e}function qu(r){let e=r.getAttribute("x"),t=r.getAttribute("y"),n=r.getAttribute("width"),o=r.getAttribute("height");if(e===null||t===null||n===null||o===null)return;let i=parseFloat(e),a=parseFloat(t),s=parseFloat(n),l=parseFloat(o);if(!(isNaN(i)||isNaN(a)||isNaN(s)||isNaN(l)))return{x1:i,y1:a,x2:i+s,y2:a+l}}function nR(r,e){let{x1:t,y1:n,x2:o,y2:i}=e;r.setAttribute("bounds",`[${t}, ${n}, ${o}, ${i}]`)}function Mce(r){let e=r.match(/\[\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\]/);if(!e)return;let t=parseFloat(e[1]),n=parseFloat(e[2]),o=parseFloat(e[3]),i=parseFloat(e[4]);if(!(isNaN(t)||isNaN(n)||isNaN(o)||isNaN(i)||o<t||i<n))return{x1:t,y1:n,x2:o,y2:i}}function Bj(r){let e=r.getAttribute("bounds");if(e)return Mce(e)}function zj(r,e){if(!e)return!0;let t=qu(r);return t?oR(t,e):!0}function oR(r,e){if(!e)return!0;let{x1:t,y1:n,x2:o,y2:i}=r;return!(o<e.left||t>e.right||i<e.top||n>e.bottom)}function $j(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Hj(r){let e=r.cloneNode(!0);for(let t of Array.from(e.children)){let n=t;for(let o of Array.from(n.children))n.removeChild(o)}return e.outerHTML}var jj=new Set(["XCUIElementTypeWebView"]);function Lce(r){if(jj.has(r.tagName))return!0;let e=r.getAttribute("name");if(e&&(e.startsWith("TabDocument")||e.startsWith("BrowserView"))){let t=e.match(/UUID=([A-F0-9-]+)/),n=e.match(/WebViewProcessID=(\d+)/);if(t&&n)return!0}return!1}function Dce(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}function iR({state:r,originalElement:e,prunedElement:t,isInWebview:n}){let{idCounter:o,idToPrunedElement:i,idToOriginalElement:a,webviewIds:s}=r,l=o.value++;t.setAttribute("id",String(l)),i.set(l,t),n?s.add(l):a.set(l,e)}function aR(r){if(jj.has(r.tagName))return r.children.length>0?aR(r.children[0]):void 0;if(r.tagName==="XCUIElementTypeOther"&&r.hasAttribute("name")&&r.hasAttribute("label"))return r;if(r.children.length===1){let e=r.children[0];return aR(e)}}function Gj(r,e,t,n){let{document:o}=t,{parentFrameBounds:i,pruneElementsOutsideBounds:a}=n;if(e.type==="element"){let s=o.createElement(e.role||e.tag);if(e.name&&s.setAttribute("name",e.name),e.description&&s.setAttribute("description",e.description),e.classes&&e.classes.length>0&&s.setAttribute("classes",e.classes.join(" ")),e.attrs)for(let[u,d]of Object.entries(e.attrs))s.setAttribute(u,d);let l=e.boundingRect,c={x1:i.x1+l.x,y1:i.y1+l.y,x2:i.x1+l.x+l.width,y2:i.y1+l.y+l.height};if(!oR(c,a))return;nR(s,c),iR({state:t,prunedElement:s,isInWebview:!0}),r.appendChild(s);for(let u of e.children)Gj(s,u,t,n)}else if(e.type==="text"){let s=o.createElement("text");iR({state:t,prunedElement:s,isInWebview:!0}),r.appendChild(s);let l=o.createTextNode(e.text);s.appendChild(l)}}function Wj(r,e,t,n){let{pruneElementsOutsideBounds:o}=n,{document:i}=t;iR({state:t,originalElement:r,prunedElement:e,isInWebview:!1});let a=Uj(r);for(let[c,u]of Object.entries(a))e.setAttribute(c,u);let s=qu(r);if(s&&nR(e,s),Lce(r)){let{removeWebviewContent:c,injectedWebviewContent:u}=n;if(c)return;if(u){let d=aR(r);if(d){let m=qu(d);if(m){t.webviewRootElement=d,Gj(e,u,t,{parentFrameBounds:m,pruneElementsOutsideBounds:o});return}}}}let l=Array.from(r.childNodes??[]);for(let c of l){let u=c.nodeType;if(u===3){let d=c.nodeValue;d&&d.trim().length>0&&e.appendChild(i.createTextNode(d));continue}if(u===1){let d=c;if(!zj(d,o))continue;let m=i.createElement(Dce(d.tagName));Wj(d,m,t,n),e.appendChild(m)}}}async function kce(r,e,t){let n=r.parseFromString("<AppiumAUT/>","text/xml"),o=new Map,i=new Map,a=new Set,s={document:n,idToPrunedElement:o,idToOriginalElement:i,webviewIds:a,idCounter:{value:0}},l=n.documentElement;Wj(e,l,s,t);let c=new Nce().serializeToString(n),u=await Ice.format(c,{parser:"xml",plugins:[Pce],printWidth:120,tabWidth:1,singleAttributePerLine:!1});return{prunedDocument:n,idToPrunedElement:o,idToOriginalElement:i,webviewIds:a,webviewRootElement:s.webviewRootElement,prunedXml:u}}async function Vj(r,e){let t=new Oce,o=t.parseFromString(r,"text/xml").documentElement;if(!o)throw new Error("No root element found in XML");if(o.tagName!=="AppiumAUT")throw new Error("No AppiumAUT element found in XML");let{prunedXml:i,idToPrunedElement:a,idToOriginalElement:s,webviewIds:l,prunedDocument:c,webviewRootElement:u}=await kce(t,o,e);return{xml:i,idToPrunedElement:a,idToOriginalElement:s,webviewIds:l,webviewRootElement:u,document:c}}var VS=class r{driver;limbarClient;aborter;constructor({driver:e,limbarClient:t,aborter:n}){this.driver=e,this.limbarClient=t,this.aborter=n}static async init({driver:e,limbarClient:t,orgId:n,options:o,aborter:i}){return new r({driver:e,aborter:i,limbarClient:t})}async getContexts(){let e=await this.driver.executeInNativeContext(async n=>await n.getContexts({})),t=e.filter(n=>n!==HS);return{contexts:e.map(n=>n),webviews:t}}async getRawScreenshotBase64(e,t=2){let n=X(),o;for(let i=0;i<t;i++)try{return await n.startAsyncSpan("EMULATOR_READ_STATE",async()=>{let a=await this.limbarClient.screenshot(),s=Buffer.from(a.base64,"base64"),l=Bce.decode(s),c=new qj({width:l.width,height:l.height});return c.data=Buffer.from(l.data),qj.sync.write(c).toString("base64")},{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:5e3})}catch(a){if(o=a,e.warn({err:a},"Failed to take screenshot"),i===t-1)throw a}throw new C("InternalWebAgentError",`Failed to take screenshot: ${o}`)}async getCurrentScreenshotPngString(e){return`data:image/png;base64,${await this.getRawScreenshotBase64(e,1)}`}async waitForScreenshotStability({logger:e,timeoutMs:t,signal:n,reason:o,tolerancePercent:i=1}){await X().startAsyncSpan("WAIT_FOR_PAGE_STABILITY",async a=>{a.attributes.reason=o;let s=Date.now(),l,c,u=!1;for(;Date.now()-s<t;){c&&c<250&&await ee(250-c,n),n?.throwIfAborted();let d=Date.now(),m;try{m=await this.getRawScreenshotBase64(e)}catch(p){e.warn({err:p},"Failed to get screenshot during stability wait"),c=Date.now()-d;continue}if(c=Date.now()-d,l&&es(l,m)<=i){u=!0;break}l=m}u||(a.attributes.timedOut=!0,e.warn({purpose:o},"Timed out waiting for screenshot stability"))})}async waitForPageSourceStability({logger:e,timeoutMs:t,signal:n,reason:o}){await X().startAsyncSpan("WAIT_FOR_PAGE_STABILITY",async i=>{i.attributes.reason=o;let a=Date.now(),s,l,c=!1;for(;Date.now()-a<t;){l&&l<250&&await ee(250-l,n),n?.throwIfAborted();let u=Date.now(),d;try{d=await this.limbarClient.elementTree()}catch(p){e.warn({err:p},"Failed to get page source during stability wait"),l=Date.now()-u;continue}let m=Uce("md5").update(d).digest("hex");if(l=Date.now()-u,s&&s===m){c=!0;break}s=m}c||(i.attributes.timedOut=!0,e.warn({purpose:o},"Timed out waiting for page source stability"))})}async getActiveWebview(){let t=(await this.getContexts()).webviews;if(t.length>1)throw new C("UserInfrastructureError","Multiple active webviews in a single package is currently not supported");return t[0]}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e)return;this.throwIfAborted();let t=await this.driver.executeWebViewScript(e,n=>n.dumpA11yTree());if(t)return JSON.parse(t)}async getDomState(e,t){let o=t?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,i=await this.getPageSource();this.throwIfAborted();let a;if(!t?.skipFetchingFullWebviewContent)try{a=await this.getActiveWebviewContent()}catch(l){e.error({err:l},"Could not get webview info to get the nested DOM state")}return this.throwIfAborted(),{graph:await Vj(i,{injectedWebviewContent:a,removeWebviewContent:t?.removeWebviewContent,pruneElementsOutsideBounds:o})}}async getPageSource(){return await X().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.executeInNativeContext(async n=>n.getPageSource()),{name:"Get iOS page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.executeInNativeContext(async t=>t.getWindowRect());return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};import iue from"zod";async function Kj({command:r,logger:e,generator:t,aiSettings:n,getEmulatorDomState:o,getScreenshotBase64:i,throwIfAborted:a,abortSignal:s}){let l=X(),c=15,u=r.timeoutSecs?r.timeoutSecs*1e3:5e3,d=vy(u),m=Date.now(),p=0,f,h=!1,g;for(;p<c&&!h;){a(),h||f&&f-m>=u&&(h=!0),p!==0&&await ee(d,s),f=Date.now();try{let y="",b="";await l.startAsyncSpan("EMULATOR_READ_STATE",async()=>{y=await o(),b=await i()},{name:"Get emulator state"});let E=await t.evaluateIosAssertion({assertion:r.assertion,screenXml:y,screenshot:b},{logger:e,loggerTags:Ee(e),agentConfigVersion:n.agentConfig?.["ios-assertion"]});if(E.result)return{success:E.result,message:E.thoughts};{let v=`AssertionFailureError: ${E.thoughts}`;g=new Error(v)}}catch(y){a(),e.info({err:y},`AI check assert attempt ${p} failed, retrying...`),g=y instanceof Error?y:new Error(`${y}`)}finally{p++}}return{success:!1,message:g?.message}}async function Yj({command:r,logger:e,generator:t,aiSettings:n,getEmulatorDomState:o,getScreenshotBase64:i,abortSignal:a}){if(!r.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let u=Yc(r.schema);if(u)throw new C("UserConfigurationError",u)}let s=X(),l="",c="";await s.startAsyncSpan("EMULATOR_READ_STATE",async()=>{l=await o(),c=await i()},{name:"Get emulator state"});try{let u=await t.getIosTextExtraction({goal:r.goal,emulatorState:l,returnSchema:r.schema,screenshot:`data:image/png;base64,${c}`},{disableCache:!!r.disableCache,abortSignal:a,loggerTags:Ee(e),agentConfigVersion:n.agentConfig?.["ios-text-extraction"]});if(u.result==="NOT_FOUND")return{success:!1,message:"No relevant data found for extraction goal on this page"};if(u.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",u.thoughts);return{success:!0,output:u.result,message:u.thoughts}}catch(u){let d=u instanceof Error?u.message:String(u);throw d.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step instead."):d.includes("AIProviderError")&&d.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:u}}):u}}import{cloneDeep as cR}from"lodash-es";function qS(r,e){return Math.abs(r-e)<1}async function zce(r,e){return await r.getElementText(e)}async function $ce(r,e,t){return await r.getElementAttribute(e,t)??null}function Hce(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r.x1+r.x2)/2;if(!Ri(e.tolerance,n,o,Math.min(1,t)))return!1;let i=e.y2-e.y1,a=(e.y1+e.y2)/2,s=(r.y1+r.y2)/2;return Ri(e.tolerance,a,s,Math.min(1,i))}function jce(r,e){let t=r.x2-r.x1,n=r.y2-r.y1;return Ri(e.tolerance,e.width,t,Math.min(1,e.width))?Ri(e.tolerance,e.height,n,Math.min(1,e.height)):!1}async function sR(r,e,t,n,o){if(!n)return;let{requiredAttributes:i,requiredText:a,requiredBounds:s,position:l,shape:c}=n;if(a!==void 0&&a.length>0){let u=await zce(e,t);r.debug({actualText:u,expectedText:a},"Got element text content")}if(i)for(let[u,d]of Object.entries(i)){let m=await $ce(e,t,u)??void 0;if(m!==d)throw new Ze(`Attribute ${u} mismatch: expected ${d}, got ${m}`)}if(s&&o){let{originalBounds:u,newBounds:d}=o;if(!u)throw new Ze("Cannot validate bounds requirements without original bounds in cache");if(!(qS(u.x1,d.x1)&&qS(u.y1,d.y1)&&qS(u.x2,d.x2)&&qS(u.y2,d.y2))){let p=f=>`[${f.x1},${f.y1},${f.x2},${f.y2}]`;throw new Ze(`Bounds changed from ${p(u)} to ${p(d)}`)}}if(l&&o&&!Hce(o.newBounds,l))throw new Ze(`Position mismatch: expected ${JSON.stringify(l)}, got ${JSON.stringify(o.newBounds)}`);if(c&&o&&!jce(o.newBounds,c))throw new Ze(`Shape mismatch: expected ${JSON.stringify(c)}, got ${JSON.stringify(o.newBounds)}`)}function lR(r){let e=[],t=r;for(;t;){let n=t.parentElement;if(!n||n.tagName==="AppiumAUT"){e.unshift(`${t.tagName}[1]`);break}let o=t.tagName,i=Array.from(n.children).filter(s=>s.tagName===o),a=1;for(let s=0;s<i.length;s++)if(i[s]===t){a=s+1;break}e.unshift(`${o}[${a}]`),t=n}return`/${e.join("/")}`}var Ku="element-6066-11e4-a52e-4f735466cecf";async function KS({target:r,driver:e,logger:t}){if(!r.xPath)throw new Ze(`Could not resolve cached target via XPath: ${r.xPath}`);if(r.requiredRelatedElements){let o=r.requiredRelatedElements;for(let i of o)await e.executeInNativeContext(async a=>{let s=await Xj(a,i.xPath);if(!s)throw new Ze(`Could not resolve required related element via XPath: ${i.xPath}`);await sR(t,a,s.elementId,i.requirements)})}let n=await e.executeInNativeContext(async o=>{let i=await Xj(o,r.xPath);if(!i)throw new Ze(`Could not resolve element via XPath: ${r.xPath}`);let{rect:a,elementId:s}=i,l={x1:a.x,y1:a.y,x2:a.x+a.width,y2:a.y+a.height};return await sR(t,o,s,r.requirements,{originalBounds:r.bounds?{x1:r.bounds[0],y1:r.bounds[1],x2:r.bounds[2],y2:r.bounds[3]}:void 0,newBounds:l}),l});return{type:"NATIVE",bounds:n,cache:{...r,bounds:[n.x1,n.y1,n.x2,n.y2]}}}async function Xj(r,e){try{let t=await r.findElement("xpath",e);if(!t)return null;let n=t[Ku];if(!n)return null;let o=await r.getElementRect(n);return{elementId:n,rect:o}}catch{return null}}function Zj({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToPrunedElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Bj(n);if(!o)throw new Error(`Could not determine bounds for element with id: ${r.id}, description: ${e}`);if(t.graph.webviewIds.has(r.id))return{type:"WEBVIEW",cache:{type:"WEBVIEW"},bounds:o};let a=t.graph.idToOriginalElement.get(r.id);if(!a)throw new Error(`Node isn't in a webview but couldn't find original node for id: ${r.id}, description: ${e}`);let s=lR(a),l=Hj(a),c=Jj({requirements:r.requirements,element:a}),u=(r.additionalElements??[]).map(({id:d,requirements:m})=>{let p=t.graph.idToOriginalElement.get(d);return!p||t.graph.webviewIds.has(d)?void 0:{xPath:lR(p),requirements:Jj({requirements:m,element:p})}}).filter(d=>!!d);return{type:"NATIVE",bounds:o,cache:{type:"NATIVE",bounds:[o.x1,o.y1,o.x2,o.y2],resolvedDescription:e,xPath:s,elementOnlySerializedXml:l,requirements:c,requiredRelatedElements:u}}}function Yp(r){return r.type==="WEBVIEW",r.cache}function Xp(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Rv(e)&&(e[t]={...e[t],[n]:Mc.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date,e[t].updatedAtLoggerTags=Ee(r.logger)))}function Jj({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=qu(e),!t))throw new C("ActionFailureError","Element to cache has no bounds or unexpected bounds format");return{requiredText:r?.textRequired?e.getAttribute("text")??void 0:void 0,requiredAttributes:$j(e,r?.attributesRequired),requiredBounds:r?.boundsRequired,position:r?.positionSpecificity?{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,tolerance:r?.positionSpecificity}:void 0,shape:r?.shapeSpecificity?{width:t.x2-t.x1,height:t.y2-t.y1,tolerance:r?.shapeSpecificity}:void 0}}var hr=class{limbarClient;driver;stateManager;generator;fixtures;orgId;aiSettings;emulatorSettings;aborter;constructor(e){this.stateManager=e.stateManager,this.driver=e.driver,this.limbarClient=e.limbarClient,this.aborter=e.aborter,this.fixtures=e.fixtures,this.orgId=e.orgId,this.generator=e.generator,this.aiSettings=e.aiSettings,this.emulatorSettings=e.emulatorSettings}async findElement({logger:e,tracer:t,description:n,skipFetchingFullWebviewContent:o=!1,removeWebviewContent:i=!1,useMemory:a=!1,metadata:s,cacheBustReason:l}){let c=e.child({...s});await this.stateManager.waitForScreenshotStability({logger:e,timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let{emulatorState:u,screenshot:d}=await t.startAsyncSection("Get emulator state",async()=>{let f=await this.stateManager.getCurrentScreenshotPngString(e);return{emulatorState:await this.stateManager.getDomState(e,{skipFetchingFullWebviewContent:o,removeWebviewContent:i}),screenshot:f}}),m;try{m=await t.startAsyncSpan("AI_LOCATOR_CALL",async f=>{l&&(f.attributes.cacheBustReason=l);let h=await this.generator.getIosElementLocation({description:n,screenXml:u.graph.xml,screenshot:d},{logger:c,loggerTags:Ee(c),abortSignal:this.aborter.controller?.signal,useMemory:a,agentConfigVersion:this.aiSettings.agentConfig?.["ios-locator"]});return f.result=h,h})}catch(f){throw this.throwIfAborted(),c.error({err:f},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${f instanceof Error?f.message:f}`,{cause:f})}if(m.id===-1)throw new C("NoMatchingElementError",m.thoughts??"No matching element found");let p=Zj({aiResponse:m,description:n,emulatorState:u});return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:(p.type==="NATIVE"?p.cache.elementOnlySerializedXml:void 0)??"Unknown element"},attributes:{},subSpans:[]}),{resolvedTarget:p,thoughts:m.thoughts}}async targetingActionWithAILocator(e){let{tracer:t,action:n,command:o,description:i,cacheKey:a,targetName:s,skipFetchingFullWebviewContent:l,removeWebviewContent:c,metadata:u,logger:d,cacheBustReason:m}=e,p=await this.findElement({logger:d,tracer:t,description:i,skipFetchingFullWebviewContent:l,removeWebviewContent:c,metadata:u,cacheBustReason:m}),f=p.thoughts,h=await n(p.resolvedTarget);return Xp({command:o,cacheKey:a,targetName:s,updatedCache:Yp(p.resolvedTarget),updatedWithAI:!0,logger:d}),{result:h,thoughts:f}}async targetingActionWithCache({logger:e,tracer:t,action:n,command:o,cacheKey:i,targetName:a,cacheCopyForAttempt:s}){this.emulatorSettings?.waitForStability&&await this.stateManager.waitForPageSourceStability({logger:e,timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let{resolvedTarget:l}=await t.startAsyncSpan("CACHE_RESOLUTION",async u=>{let d=await KS({target:s,driver:this.driver,logger:e});return u.attributes.serializedElement=(d.type==="NATIVE"?d.cache.elementOnlySerializedXml:void 0)??"Unknown element",{resolvedTarget:d}}),c=await n(l);return Xp({command:o,cacheKey:i,targetName:a,updatedCache:Yp(l),updatedWithAI:!1,logger:e}),{result:c,thoughts:"Successfully executed preset action with cache"}}async wrapTargetingAction(e){let{tracer:t,logger:n,action:o,description:i,command:a,cacheKey:s="cache",targetName:l="target",cacheIsInvalidAfterResolution:c,skipFetchingFullWebviewContent:u=!1,removeWebviewContent:d=!1}=e,m={commandId:a.id},p=!1,f,h;if(s==="cache"&&"cache"in a&&a.cache){let g=a.cache;l==="target"&&"target"in g&&g.target?.type==="NATIVE"?h=cR(g.target):l==="fromTarget"&&"fromTarget"in g&&g.fromTarget?.type==="NATIVE"?h=cR(g.fromTarget):l==="toTarget"&&"toTarget"in g&&g.toTarget?.type==="NATIVE"&&(h=cR(g.toTarget))}if(a.disableCache&&(n.debug({command:a},"Cache explicitly disabled for command"),p=!0,f="Cache explicitly disabled",h=void 0),c&&(p=!0,f=f??"Cache invalidated after resolution",h=void 0),h&&h.resolvedDescription!==i&&(n.info({description:i,cacheDescription:h.resolvedDescription},"Cache description mismatch, clearing it automatically"),p=!0,f="Description mismatch",h=void 0),h)try{let g=await this.targetingActionWithCache({logger:n,tracer:t,action:o,command:a,cacheKey:s,targetName:l,cacheCopyForAttempt:h});return gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:mobile-native",`hasRequirements:${!!h.requirements}`,`orgId:${this.orgId}`,"cliVersion:0.59.0"]),g}catch(g){if(this.throwIfAborted(),g instanceof C&&g.reason!=="InternalWebAgentError")throw n.error({err:g},"Failed to execute action with target cache (fatal)"),g;gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:mobile-native",`hasRequirements:${!!h.requirements}`,`orgId:${this.orgId}`,"cliVersion:0.59.0"]),n.warn({err:g},"Failed to execute action with target cache, retrying with AI")}return n.info({description:i,cacheBustedBeforeAction:p},"Prompting AI for a new element location"),await this.targetingActionWithAILocator({tracer:t,action:o,command:a,description:i,cacheKey:s,targetName:l,skipFetchingFullWebviewContent:u,removeWebviewContent:d,metadata:m,logger:n,cacheBustReason:f})}constructPerformerParams(){return{limbarClient:this.limbarClient,stateManager:this.stateManager,driver:this.driver,fixtures:this.fixtures,emulatorSettings:this.emulatorSettings,aborter:this.aborter,orgId:this.orgId,generator:this.generator,aiSettings:this.aiSettings}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};var YS=class extends hr{async doDrag(e,t,n,o){let{x1:i,y1:a,x2:s,y2:l}=t.bounds,c=i+(s-i)/2,u=a+(l-a)/2;e.attributes.startPoint={x:c,y:u};let{x1:d,y1:m,x2:p,y2:f}=n.bounds,h=d+(p-d)/2,g=m+(f-m)/2;e.attributes.endPoint={x:h,y:g};let y=o?.hoverDuration??500,b=o?.dragDuration??1e3;b===0&&(b=1);let v=Math.sqrt(Math.pow(h-c,2)+Math.pow(g-u,2))/b*1e3;await this.driver.executeInNativeContext(async w=>{await w.execute("mobile: dragFromToWithVelocity",{fromX:c,fromY:u,toX:h,toY:g,pressDuration:y/1e3,velocity:v,holdDuration:.5})})}async executeDragAndDrop({logger:e,command:t}){let n=X();if(t.fromTarget.type!=="description"||t.toTarget.type!=="description")throw new C("UserConfigurationError","Drag and drop only supports description targets for now");let o=t.fromTarget.description,{result:i,thoughts:a}=await this.wrapTargetingAction({command:t,tracer:n,description:o,cacheKey:"cache",targetName:"fromTarget",action:async u=>u,logger:e}),s=t.toTarget.description,{result:l,thoughts:c}=await this.wrapTargetingAction({command:t,tracer:n,description:s,cacheKey:"cache",targetName:"toTarget",action:async u=>u,logger:e});return await n.startAsyncSpan("EMULATOR_INTERACTION",async u=>{await this.doDrag(u,i,l,{hoverDuration:t.hoverDuration,dragDuration:t.dragDuration})},{name:"Drag and drop"}),{success:!0,message:`${a}
4893
- ${c}`}}};import{cloneDeep as Qj}from"lodash-es";var XS=class{driver;constructor(e){this.driver=e}async getTextContent(e){let t=e.cache.xPath;return t?await this.driver.executeInNativeContext(async o=>{try{let a=(await o.findElement("xpath",t))[Ku];if(!a)return"";let s=await o.getElementAttribute(a,"label"),l=await o.getElementAttribute(a,"value");return[s,l].filter(u=>!!u&&u.trim().length>0).join(" ").trim()}catch{return""}})??"":""}async getAttribute(e,t){let n=e.cache.xPath;return n?await this.driver.executeInNativeContext(async i=>{try{let s=(await i.findElement("xpath",n))[Ku];return s?await i.getElementAttribute(s,t)??"":""}catch{return""}})??"":""}async getTagName(e){let t=e.cache.xPath;return t?await this.driver.executeInNativeContext(async o=>{try{let a=(await o.findElement("xpath",t))[Ku];return a?await o.getElementTagName(a)??"":""}catch{return""}})??"":""}async isEditable(e){throw new C("UserConfigurationError","Editable checks are not supported on iOS native elements")}async isEnabled(e){let t=e.cache.xPath;return t?await this.driver.executeInNativeContext(async n=>{try{let i=(await n.findElement("xpath",t))[Ku];return i?await n.isElementEnabled(i):!1}catch{return!1}}):!1}async isFocused(e){let t=await this.getAttribute(e,"focused");return t==="true"||t==="1"}async getStyleProperty(e,t){throw new C("UserConfigurationError","Computed style checks are not supported on iOS native elements")}},JS=class{driver;webviewContext;constructor(e,t){this.driver=e,this.webviewContext=t}getCenter(e){let{x1:t,y1:n,x2:o,y2:i}=e.bounds;return{x:(t+o)/2,y:(n+i)/2}}async getTextContent(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?l.innerText??l.textContent??"":""},t,n)??""}async getAttribute(e,t){let{x:n,y:o}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(a,s,l,c)=>{let u=document.elementFromPoint(s,l);return u?u.getAttribute(c)??"":""},n,o,t)??""}async getTagName(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?l.tagName:""},t,n)??""}async isEditable(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);if(!l)return!1;let c=l.tagName;return c==="INPUT"||c==="TEXTAREA"||c==="SELECT"||l.isContentEditable},t,n)}async isEnabled(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?!l.disabled:!1},t,n)}async isFocused(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?document.activeElement===l:!1},t,n)}async getStyleProperty(e,t){let{x:n,y:o}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(a,s,l,c)=>{let u=document.elementFromPoint(s,l);return u?window.getComputedStyle(u).getPropertyValue(c):""},n,o,t)??""}};var Gce=5e3,ZS=class extends hr{async executeElementCheck({logger:e,command:t}){let n=Date.now(),o=(t.timeout??ur)*1e3,i=o+1e4,a,s=0,l=500,c=Qj(t.cache);if(t.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Element check step");for(;s-n<o;){if(Date.now()-n>i){e.warn("Exceeded max system timeout for element check, exiting...");break}if(this.throwIfAborted(),a=await this.executeElementCheckHelper({logger:e,command:t}),s=Date.now(),!a.success)t.cache=c,c=Qj(c),await ee(l,this.abortSignal),l=Math.min(Math.floor(l*1.5),Gce);else return a}let u=await this.executeElementCheckHelper({logger:e,command:t,cacheIsInvalidAfterResolution:!0});if(!u.success&&c&&t.cache){let d=IU({logger:e,originalTarget:Cv(c)?c.target:void 0,newTarget:t.cache.target});d&&na(c.target,d)&&(t.cache={target:d,updatedAt:t.cache.updatedAt})}return u}async executeElementCheckHelper({logger:e,command:t,cacheIsInvalidAfterResolution:n}){let o=X();if(t.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Element check step");let i=yu(t.assertion);try{return(await this.wrapTargetingAction({...n?{cacheIsInvalidAfterResolution:n}:{},command:t,tracer:o,action:async s=>s.type==="NATIVE"?await this.executeNativeElementCheck(t,s):await this.executeWebviewElementCheck(t,s),description:t.target.description,skipFetchingFullWebviewContent:!0,removeWebviewContent:!0,logger:e})).result}catch(a){return i&&(a instanceof C&&a.reason==="NoMatchingElementError"||a instanceof ni)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${a instanceof Error?a.message:`${a}`}`}}}async executeNativeElementCheck(e,t){let n=X(),{assertion:o}=e;return await n.startAsyncSpan("ELEMENT_ASSERTION",async i=>{let a=await this.executeElementAssertion({assertion:o,element:t,elementPropertyAccessors:new XS(this.driver),span:i});return i.result=a,a},{name:"Native element check"})}async executeWebviewElementCheck(e,t){let n=X(),{assertion:o}=e,a=(await this.stateManager.getContexts()).webviews[0];if(!a)throw new C("UserConfigurationError","No active webview context found for element check");return await n.startAsyncSpan("ELEMENT_ASSERTION",async s=>{let l=await this.executeElementAssertion({assertion:o,element:t,elementPropertyAccessors:new JS(this.driver,a),span:s});return s.result=l,l},{name:"Webview element check"})}async executeElementAssertion({assertion:e,element:t,elementPropertyAccessors:n,span:o}){switch(e.type){case"ELEMENT_CONTENT":{let i=await n.getTextContent(t)??"";return o.attributes.elementTextContent=Xt(i,500,!0),pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${Ar(e)} '${e.value}': ${i}`}}case"ELEMENT_ATTRIBUTE":{let i=null;try{i=await n.getAttribute(t,e.attr)}catch{i=null}if(!pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=Ar(e);return{success:!1,message:`The attribute ${e.attr} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}case"ELEMENT_EXISTENCE":{let i=!1;switch(e.condition){case"EDITABLE":i=await n.isEditable(t);break;case"VISIBLE":case"EXISTS":i=!0;break;case"ENABLED":{i=await n.isEnabled(t);break}case"FOCUSED":i=await n.isFocused(t);break;default:throw e.condition,new Error("Unrecognized element condition type")}return i=e.negated?!i:i,i?{success:!0}:{success:!1,message:`The element ${Ar(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${Ar(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=Ar(e);return{success:!1,message:`The style property ${e.property} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}default:throw new Error("Unrecognized element assertion type")}}};async function eG({command:r,orgId:e,logger:t,fixtures:n,abortSignal:o}){let i;try{i=await bo({orgId:e,code:r.code,fragment:!1,context:n.testContext,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:t,localTools:n.localCodeEvalTools,signal:o})}catch(a){throw new C("ActionFailureError",a instanceof C?a.message:`${a}`,{errOptions:{cause:a}})}try{JSON.stringify(i)}catch(a){throw new C("UserConfigurationError",`Return value is not serializable: ${a instanceof Error?a.message:`${a}`}`)}return{success:!0,output:i}}async function tG({command:r,driver:e}){switch(r.key){case"ENTER":await e.executeInNativeContext(t=>t.keys(["\uE007"]));break;case"BACKSPACE":await e.executeInNativeContext(t=>t.keys(["\uE003"]));break;default:{let t=r.key}}return{success:!0}}import QS from"zod";var rG=QS.object({name:QS.string(),pid:QS.number(),bundleId:QS.string()});var Yu=class extends hr{async doPress({name:e,longPress:t}){return this.driver.executeInNativeContext(n=>n.executeScript("mobile: pressButton",[{name:e,isLongPress:t}]))}};var eb=class extends hr{async execute(){let e;try{let n=await this.driver.executeInNativeContext(i=>i.executeScript("mobile: activeAppInfo",[]));e=rG.parse(n).bundleId}catch(n){throw new C("UserConfigurationError",`Failed to get active app info: ${n.message}`)}return await new Yu(this.constructPerformerParams()).doPress({name:"home"}),await this.limbarClient.terminateApp(e),{success:!0}}};import Wce from"fetch-cookie";import{CookieJar as Vce}from"tough-cookie";async function nG({command:r,logger:e}){let t;try{t=new URL(r.url).hostname}catch(l){throw new C("UserConfigurationError",`Invalid URL: ${l instanceof Error?l.message:`${l}`}`)}let n=new Vce,o=Wce(fetch,n),i=Date.now(),a=await $u({command:r,baseUrl:void 0,logger:e,fetchImplementation:o}),s=Dc(n,t);return{output:Is.parse({...a,cookies:s}),success:!0,message:`Successfully executed request in ${Date.now()-i}ms`}}async function oG({command:r,limbarClient:e,getViewportBounds:t}){return await e.setOrientation(r.orientation==="LANDSCAPE"?"Landscape":"Portrait"),{success:!0,output:{newViewportBounds:await t()}}}var qce=5e3,tb=class extends hr{async executeScreenCheck(e,t){let{timeout:n}=t,o=Date.now(),i=(n??ur)*1e3,a=i+1e4,s=0,l=500;for(;s-o<i;){if(Date.now()-o>a){e.warn("Exceeded max system timeout for screen check, exiting...");break}this.throwIfAborted();let c=await this.executeScreenCheckHelper(e,t);if(s=Date.now(),!c.success)await ee(l,this.abortSignal),l=Math.min(Math.floor(l*1.5),qce);else return c}return await this.executeScreenCheckHelper(e,t)}async executeScreenCheckHelper(e,t){let{assertion:n}=t;switch(n.type){case"CONTENT":try{let i=(await this.stateManager.getDomState(e,{skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.xml;if(!i)throw new Error("Failed to get screen XML");let a=i.includes(n.value)===!n.negated;return i.length>1e4&&(i=i.slice(0,1e4)+"...TRUNCATED"),a?{success:!0}:{success:!1,message:`The screen ${Sp(n)}.`}}catch(o){return{success:!1,message:`Failed to evaluate screen content assertion: ${o instanceof Error?o.message:`${o}`}`}}default:return n.type,{success:!1,message:`Unsupported screen check assertion type: ${n.type}`}}}};var Kce=.8,Jp=.2,Xu=class extends hr{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getContainerBoundsFromViewport(t);break;case"OPEN_APP":n=this.getContainerBoundsFromViewport(t);break;case"OPEN_WEBVIEW":{n=this.getContainerBoundsFromViewport(t);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getContainerBoundsFromViewport(e){return{left:e.x,top:e.y,width:e.width,height:e.height}}getContainerBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n;return{left:t,top:n,width:a,height:s}}async executeSwipe({logger:e,command:t}){let n=X();if(t.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:i,startY:a,deltaPixels:s}=t.scrollableElement;return await n.startAsyncSpan("EMULATOR_INTERACTION",async l=>{await this.performSwipe({span:l,startX:i,startY:a,deltaPixels:s,direction:t.direction,durationMs:t.durationMs})},{name:`Swipe ${t.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(t.scrollableElement.type!=="CUSTOM"){let i=await this.driver.executeInNativeContext(async s=>s.getWindowRect()),a=await this.getHardcodedScrollableElementBounds(t.scrollableElement,i);return await n.startAsyncSpan("EMULATOR_INTERACTION",async s=>{await this.swipeByAbsoluteCoordinates({span:s,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:a,relativePosition:t.relativePosition})},{name:`Swipe ${t.direction} in the entire ${t.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:o}=await this.wrapTargetingAction({command:t,description:t.scrollableElement.target.description,action:async i=>X().startAsyncSpan("EMULATOR_INTERACTION",async s=>this.scrollInNativeContainer({span:s,cmd:t,target:i}),{name:`Swipe ${t.direction} in the specified container`}),tracer:n,logger:e});return{success:!0,message:o}}async scrollInNativeContainer({span:e,cmd:t,target:n}){if(n.type!=="NATIVE")throw new C("ActionFailureError","Swipe in webview containers is not yet supported on iOS");let o=n.cache;if(!o.bounds||o.bounds.length<4)throw new C("ActionFailureError","Native container cache has no bounds");let i=o.bounds,a=this.getContainerBoundsFromBounds(i);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:a,relativePosition:t.relativePosition})}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=Kce,durationMs:o=500,containerBounds:i,relativePosition:a}){e.attributes.containerBounds=i;let s=t==="up"||t==="down",l=i.width*Jp,c=i.height*Jp,u=s?(i.height-2*c)*n:(i.width-2*l)*n,d,m;a?(d=i.left+a.x,m=i.top+a.y):(d=i.left+i.width/2,m=i.top+i.height/2),await this.performSwipe({span:e,startX:d,startY:m,deltaPixels:u,direction:t,durationMs:o})}async performSwipe({span:e,startX:t,startY:n,deltaPixels:o,direction:i,durationMs:a=300}){let s=Math.abs(o),l=t,c=n;i==="up"||i==="down"?c=i==="up"?n-s:n+s:l=i==="left"?t-s:t+s,e.attributes.pixelDelta=s,e.attributes.startPoint={x:t,y:n},e.attributes.endPoint={x:l,y:c},e.attributes.durationMs=a,await this.driver.executeInNativeContext(async u=>{let d={type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:t,y:n},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:a,x:l,y:c},{type:"pointerUp",button:0}]};await u.performActions([d]),await u.releaseActions()})}};var Yce=5,iG=.8,Xce=1;function Jce(r){return r.type==="NATIVE"&&r.scrollDetails!==void 0}var rb=class extends Xu{async executeScrollTo({logger:e,command:t}){let n=t.target.description,o=t.scrollStepPercent??iG,i=await this.tryUseCachedScrollPosition(e,t,n);return i||this.searchForElement(e,t,n,o)}async resolveContainer({logger:e,scrollableElement:t,containerCache:n}){let o=await this.driver.executeInNativeContext(async c=>c.getWindowRect());if(t.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:o.width,height:o.height}};if(t.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(t,o)};let i=X(),a=t.target.description;if(n){let c=this.getBoundsFromNativeCache(n);return e.info({bounds:c},"Got container bounds from native cache"),{bounds:c,cache:n}}let{resolvedTarget:s}=await this.findElement({logger:e,description:a,tracer:i});if(s.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${a}" resolved to a webview element. Custom containers must be native elements.`);let l=this.getBoundsFromNativeCache(s.cache);return e.info({bounds:l},"Got container bounds from AI"),{bounds:l,cache:s.cache}}getBoundsFromNativeCache(e){if(!e.bounds||e.bounds.length<4)throw new C("ActionFailureError","Native target cache has no bounds");let[t,n,o,i]=e.bounds;return{left:t,top:n,width:o-t,height:i-n}}async tryUseCachedScrollPosition(e,t,n){let o=t.cache?.target;if(o&&Jce(o)&&o.scrollDetails!==void 0)return this.tryUseNativeScrollCache(e,t,n,o)}async tryUseNativeScrollCache(e,t,n,o){let i=o.scrollDetails,a=X(),s=t.scrollStepPercent??iG,l=i.scrollableElement.type==="CUSTOM"&&i.scrollableElement.cache?.type==="NATIVE"?i.scrollableElement.cache:void 0;await this.scrollByPixelDelta({logger:e,pixelDelta:i.pixelDelta,scrollableElement:i.scrollableElement,containerCache:l,direction:i.direction,scrollStepPercent:s});try{let u=await this.tryFindElement({logger:e,cmd:t,description:n,tracer:a,scrollDetails:i,useAIIfCacheFails:!1});if(u)return u;e.info("Element not found at cached position, undoing scroll")}catch(u){e.warn({err:u},"Error finding element at cached position, will undo scroll")}let c=i.direction==="down"?"up":"down";e.info({pixelDelta:i.pixelDelta,originalDirection:i.direction,undoDirection:c,scrollableElementType:i.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({logger:e,pixelDelta:i.pixelDelta,scrollableElement:i.scrollableElement,containerCache:l,direction:c,scrollStepPercent:s})}async tryFindElement({logger:e,cmd:t,description:n,tracer:o,scrollDetails:i,useAIIfCacheFails:a=!0}){let s,l,c=t.cache?.target;if(c&&c.type==="NATIVE"&&c.resolvedDescription===n&&!t.disableCache)try{s=await KS({target:c,driver:this.driver,logger:e}),l="Successfully resolved scroll to target with cache.",e.info("Successfully resolved scroll to target from cache")}catch(d){e.warn({err:d},"Failed to resolve target from cache")}if(!s&&!a)return null;if(!s)try{let d=await this.findElement({logger:e,description:n,tracer:o,metadata:{commandId:t.id}});if(d.resolvedTarget.type!=="NATIVE")return null;s=d.resolvedTarget,l=d.thoughts}catch(d){if(d instanceof C&&d.reason==="NoMatchingElementError")return null;throw e.warn({err:d},"Failed to find scroll-to target with AI"),d}return Xp({command:t,updatedCache:{...Yp(s),...i?{scrollDetails:i}:{}},updatedWithAI:!0,logger:e}),{success:!0,message:l}}async searchForElement(e,t,n,o){let i=X(),a=await this.resolveContainer({logger:e,scrollableElement:t.scrollableElement});return this.scrollAndSearch(e,t,n,i,o,a)}async scrollAndSearch(e,t,n,o,i,a){let s=0,l=a.bounds,c=l.height*Jp,u=(l.height-2*c)*i,d=!0,m=t.maxScrollAttempts??Yce;for(let h=0;h<m;h++){this.throwIfAborted();let g=this.buildScrollDetails(t,s,a.cache),y=await this.tryFindElement({logger:e,cmd:t,description:n,tracer:o,scrollDetails:g});if(y)return y;if(!d)throw new Error(`ActionFailureError: Could not find element "${n}" after scrolling to the end`);e.debug({attempt:h,cumulativePixelDelta:s},"Element not found, scrolling further");let b=Zce(t.scrollableElement);d=await this.scrollByPage({logger:e,direction:t.direction,containerBounds:l,scrollStepPercent:i,rawCoordinates:b}),s+=t.direction==="down"?u:-u}let p=this.buildScrollDetails(t,s,a.cache),f=await this.tryFindElement({logger:e,cmd:t,description:n,tracer:o,scrollDetails:p});if(f)return f;throw new Error(`ActionFailureError: Could not find element "${n}" after ${m} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollByPage({logger:e,direction:t,containerBounds:n,scrollStepPercent:o,rawCoordinates:i}){return X().startAsyncSpan("EMULATOR_INTERACTION",async s=>(s.attributes.containerBounds=n,s.attributes.direction=t,this.executeScrollGesture({logger:e,direction:t,containerBounds:n,scrollStepPercent:o,rawCoordinates:i})),{name:`Scroll ${t} by one page`})}async scrollByPixelDelta({logger:e,pixelDelta:t,scrollableElement:n,containerCache:o,direction:i,scrollStepPercent:a}){if(t===0)return;let s=X(),l,c,u;if(n.type==="CUSTOM_COORDINATES")l=n.startX,c=n.startY,u=n.deltaPixels;else{let p=(await this.resolveContainer({logger:e,scrollableElement:n,containerCache:o})).bounds,f=p.height*a,h=this.calculateSwipeCoordinates({containerBounds:p,direction:i,desiredDelta:f});l=h.startX,c=h.startY,u=h.actualDelta}let d=Math.ceil(Math.abs(t)/u);e.debug({pixelDelta:t,direction:i,scrollableElementType:n.type,startX:l,startY:c,maxScrollPerStep:u,numScrolls:d},"scrollByPixelDelta calculated parameters"),await s.startAsyncSpan("EMULATOR_INTERACTION",async m=>{m.attributes.pixelDelta=t,m.attributes.numScrolls=d,m.attributes.maxScrollPerStep=u,m.attributes.startX=l,m.attributes.startY=c;let p=0;for(let f=0;f<d;f++){this.throwIfAborted();let h=Math.abs(t)-p,g=Math.min(u,h);await this.performRawSwipe({startX:l,startY:c,deltaPixels:g,direction:this.invertDirection(i)}),p+=g}},{name:`Scroll ${i} by ${t}px`})}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n}){let o=e.left+e.width/2,i=e.height/2,a=e.height*Jp,s=Math.min(n,i-a),l=t==="down"?e.top+i+s/2:e.top+i-s/2;return{startX:o,startY:l,actualDelta:s}}invertDirection(e){return e==="up"?"down":"up"}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,l=o==="up"?t-a:t+a;await this.driver.executeInNativeContext(async c=>{let u={type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:l},{type:"pointerUp",button:0}]};await c.performActions([u]),await c.releaseActions()})}async executeScrollGesture({logger:e,direction:t,containerBounds:n,scrollStepPercent:o,diffThresholdPercent:i=Xce,rawCoordinates:a}){let s=await this.stateManager.getRawScreenshotBase64(e),l,c,u;if(a)l=a.startX,c=a.startY,u=a.deltaPixels;else{let f=n.height*o,h=this.calculateSwipeCoordinates({containerBounds:n,direction:t,desiredDelta:f});l=h.startX,c=h.startY,u=h.actualDelta}await this.performRawSwipe({startX:l,startY:c,deltaPixels:u,direction:this.invertDirection(t)});let d=await this.stateManager.getRawScreenshotBase64(e),m=es(s,d),p=m>i;return e.debug({diffPercent:m,diffThresholdPercent:i,canScrollMore:p,direction:t,actualDelta:u,rawCoordinates:a},"Scroll gesture visual diff result"),p}};function Zce(r){if(r.type==="CUSTOM_COORDINATES")return r}function Qce(r){return"iterations"in r}function eue(r){let e={relativePosition:r.relativePosition},t=r.iterations??(r.doubleTap?2:void 0),n=r.tapDelayMs??r.doubleTapDelayMs;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw new C("UserConfigurationError","iterations must be a positive integer");if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new C("UserConfigurationError","tapDelayMs must be >= 0");if(t&&t>1&&r.longPress)throw new C("UserConfigurationError","Cannot specify both more than one tap iteration and long press at the same time");if(n!==void 0&&(!t||t<2))throw new C("UserConfigurationError","tapDelayMs requires iterations >= 2");if(r.longPress){if(n!==void 0)throw new C("UserConfigurationError","tapDelayMs cannot be used with longPress");return{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}}return t!==void 0?{...e,iterations:t,tapDelayMs:n}:e}var Ju=class extends hr{async tapOnAbsoluteCoordinates(e,t){let n=t.x,o=t.y;if(e.info({x:n,y:o},"Tap at coordinates"),"longPress"in t&&t.longPress){let i=(t.longPressDurationMs??2e3)/1e3;await this.driver.executeInNativeContext(a=>a.executeScript("mobile: touchAndHold",[{x:n,y:o,duration:i}]));return}if(Qce(t)){let i=t.tapDelayMs??100;for(let a=0;a<t.iterations;a++)await this.driver.executeInNativeContext(s=>s.tap({x:n,y:o})),a<t.iterations-1&&await ee(i);return}await this.driver.executeInNativeContext(i=>i.tap({x:n,y:o}))}async tapOnTarget({logger:e,target:t,options:n}){return await X().startAsyncSpan("EMULATOR_INTERACTION",async i=>{i.attributes.options=n;let{x1:a,y1:s,x2:l,y2:c}=t.bounds,u=l-a,d=c-s,m=n?.relativePosition?.x??u/2,p=n?.relativePosition?.y??d/2;m=Math.max(0,Math.min(m,u)),p=Math.max(0,Math.min(p,d));let f=a+m,h=s+p;await this.tapOnAbsoluteCoordinates(e,{x:f,y:h,...n}),i.attributes.point={x:f,y:h}},{name:"Tap on target"})}async executeTap({logger:e,command:t}){let n=eue(t),o=X();if(t.target.type==="coordinates"){let s=await this.driver.executeInNativeContext(async u=>u.getWindowSize()),l=t.target.xPercent*s.width,c=t.target.yPercent*s.height;return await o.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates(e,{...n,x:l,y:c})},{name:`Tap at coordinates ${l}, ${c}`}),{success:!0,message:`Tapped at ${l}, ${c}`}}let i=t.target.description,{thoughts:a}=await this.wrapTargetingAction({logger:e,tracer:o,command:t,action:s=>this.tapOnTarget({logger:e,target:s,options:n}),description:i});return{success:!0,message:a}}};var Ol=25,nb=class extends hr{async doType(e,t){let n=X();if(!t.target){if(t.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForScreenshotStability({logger:e,timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(t),{success:!0,message:"Successfully executed type action"}}if(t.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:o}=await this.wrapTargetingAction({logger:e,tracer:n,command:t,action:async i=>{if("type"in i&&i.type==="NATIVE")await this.doNativeType(e,t,i);else throw new Error("UserConfigurationError: Webview targets are not supported for the Type step on iOS devices")},description:t.target.description});return{success:!0,message:o}}async doNativeType(e,t,n){let o=new Ju(this.constructPerformerParams());t.clearContent?(await o.tapOnTarget({logger:e,target:n,options:{longPress:!0}}),await this.clearContent(e)):await o.tapOnTarget({logger:e,target:n,options:{}}),await this.sendKeys(t)}async sendKeys(e){let t=X(),n=e.keyPressDelayMs??Ol;n<=0&&(n=Ol),await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){if(this.throwIfAborted(),await this.driver.executeInNativeContext(s=>s.isKeyboardShown()))return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.executeInNativeContext(async o=>{try{n!==Ol&&await o.updateSettings({maxTypingFrequency:1e3/n}),await o.performActions(tue(e.text)),await o.releaseActions()}finally{n!==Ol&&await o.updateSettings({maxTypingFrequency:1e3/Ol})}})},{name:`Typing "${e.text}"${n?` with a ${n}ms delay`:""}`})}async clearContent(e){let t=X();try{await t.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(n){e.warn({err:n},"Failed to find select all button, continuing...")}}async clearContentHelper(){await this.driver.executeInNativeContext(async e=>{let t=e.$('-ios predicate string:label == "Select All"');await t.waitForExist({timeout:750}),await t.click()}),await this.driver.executeInNativeContext(async e=>{await e.keys(["\uE003"])})}};function tue(r){let e={type:"key",id:"pressKeys",actions:[]};for(let t of[...r])e.actions.push({type:"keyDown",value:t},{type:"keyUp",value:t});return[e]}async function sG({command:r,abortSignal:e}){return await ee(r.timeoutSecs*1e3,e),{success:!0}}async function rue(r,e){try{await r.executeInNativeContext(t=>t.executeScript("mobile: pressButton",[{name:"home"}])),e.info("Navigated to home screen")}catch(t){e.warn({err:t},"Failed to press home button")}}var uR=["io.appium."],dR=["com.facebook.WebDriverAgentRunner.xctrunner"];async function nue(r,e){let t;try{t=await r.listApps()}catch(a){e.warn({err:a},"Failed to list installed apps");return}let n=t.filter(({bundleId:a})=>!dR.includes(a)&&!uR.some(s=>a.startsWith(s)));e.info({count:n.length},"Terminating all apps");let i=(await Promise.allSettled(n.map(async a=>{try{return await r.terminateApp(a.bundleId),a.bundleId}catch(s){return e.debug({err:s,bundleId:a.bundleId},"Failed to terminate app (may not be running)"),null}}))).filter(a=>a.status==="fulfilled"&&a.value!==null).length;i>0&&e.info({count:i},"Terminated apps")}async function oue(r,e){e.info("Resetting privacy settings for all apps");try{let t=await r.simctl(["privacy","booted","reset","all"]).wait();t.code!==0&&e.warn({stderr:t.stderr,exitCode:t.code},"simctl privacy reset returned non-zero exit code")}catch(t){e.warn({err:t},"Failed to reset privacy settings")}}async function lG(r){let{limbarClient:e,driver:t,logger:n}=r;await rue(t,n),await nue(e,n),await oue(e,n)}var Zu=class r extends hr{emulatorSettings;logger;splitInstalledApps(e){let t=[],n=[];for(let{bundleId:o}of e)if(!(dR.includes(o)||uR.some(i=>o.startsWith(i)))){if(o.startsWith("com.apple.")){n.push(o);continue}t.push(o)}return{installedApps:t,prunedApps:n}}constructor(e){super(e),this.logger=e.logger,this.emulatorSettings=e.emulatorSettings}static async init({driver:e,logger:t,fixtures:n,orgId:o,options:i,abortController:a,limbarClient:s,generator:l,aiSettings:c}){let u={controller:a},d=i?.emulator??{},m=await VS.init({driver:e,orgId:o,limbarClient:s,options:d,aborter:u}),p=new r({generator:l,aiSettings:c,limbarClient:s,driver:e,stateManager:m,logger:t,fixtures:n,aborter:u,orgId:o,emulatorSettings:d});return await p.initializeSettings(),p}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Iu({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Ou(e.command,n)}}async executeCommandHelper({command:e}){switch(e.type){case"TAP":return new Ju(this.constructPerformerParams()).executeTap({logger:this.logger,command:e});case"SWIPE":return new Xu(this.constructPerformerParams()).executeSwipe({logger:this.logger,command:e});case"DRAG_AND_DROP":return new YS(this.constructPerformerParams()).executeDragAndDrop({logger:this.logger,command:e});case"SCROLL_TO":return new rb(this.constructPerformerParams()).executeScrollTo({logger:this.logger,command:e});case"TYPE":return new nb(this.constructPerformerParams()).doType(this.logger,e);case"STATE":{let t=await this.stateManager.getDomState(this.logger),n=await this.stateManager.getContexts();return{output:{xml:t.graph.xml,contexts:n},success:!0}}case"OPEN_APP":{let t=[];if(e.intentExtras)try{let n=JSON.parse(e.intentExtras);t=iue.string().array().parse(n)}catch(n){throw new C("UserConfigurationError",`Invalid launch arguments: expected a JSON array of strings. ${n instanceof Error?n.message:`${n}`}`)}return await this.driver.executeInNativeContext(n=>n.execute("mobile: launchApp",{bundleId:e.packageName,arguments:t})),{success:!0}}case"KILL_APP":return new eb(this.constructPerformerParams()).execute();case"PRESS":{let t=new Yu(this.constructPerformerParams());switch(e.key){case"HOME":await t.doPress({name:"home"});break;case"POWER":await this.driver.executeInNativeContext(n=>n.isLocked())?await this.driver.executeInNativeContext(n=>n.unlock()):await this.driver.executeInNativeContext(n=>n.lock());break}return{success:!0}}case"PRESS_KEYBOARD":return tG({command:e,driver:this.driver});case"AI_CHECK":return Kj({command:e,logger:this.logger,generator:this.generator,aiSettings:this.aiSettings,getEmulatorDomState:()=>this.getEmulatorDomState(),getScreenshotBase64:()=>this.getScreenshotBase64(),throwIfAborted:()=>this.throwIfAborted(),abortSignal:this.abortSignal});case"AI_EXTRACT":return Yj({command:e,logger:this.logger,generator:this.generator,aiSettings:this.aiSettings,getEmulatorDomState:()=>this.getEmulatorDomState(),getScreenshotBase64:()=>this.getScreenshotBase64(),abortSignal:this.abortSignal});case"JAVASCRIPT":return eG({command:e,orgId:this.orgId,logger:this.logger,fixtures:this.fixtures,abortSignal:this.abortSignal});case"WAIT":return sG({command:e,abortSignal:this.aborter.controller?.signal});case"REQUEST":return nG({command:e,logger:this.logger});case"ROTATE_ORIENTATION":return oG({command:e,limbarClient:this.limbarClient,getViewportBounds:()=>this.getViewportBounds()});case"ADD_FILE":{let t=await rS(e.file);return await this.driver.executeInNativeContext(n=>n.pushFile(e.storageLocation,t)),{success:!0}}case"SCREEN_CHECK":return new tb(this.constructPerformerParams()).executeScreenCheck(this.logger,e);case"ELEMENT_CHECK":return new ZS(this.constructPerformerParams()).executeElementCheck({logger:this.logger,command:e});default:{let t=e;throw new Error(`Unsupported mobile command type: ${t}`)}}}async getMobileFailureRecoveryPlan(e){return{thoughts:"Failure recovery is not yet supported for iOS.",scenario:"INELIGIBLE",instructions:void 0}}async waitForPageSourceStability(e){return this.stateManager.waitForPageSourceStability({logger:this.logger,timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}async getInstalledApps(){let e=await this.limbarClient.listApps();return this.splitInstalledApps(e)}async initializeSettings(){let{latitude:e,longitude:t}=this.emulatorSettings?.geolocation??vc;await this.driver.executeInNativeContext(async n=>{await n.setGeoLocation({latitude:e,longitude:t}),await n.updateSettings({maxTypingFrequency:1e3/Ol})})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64(this.logger)}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString(this.logger)}async getEmulatorDomState(){return(await this.stateManager.getDomState(this.logger)).graph.xml}async getViewportBounds(){return this.stateManager.getViewportBounds()}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({logger:this.logger,timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async softReset(){await lG({limbarClient:this.limbarClient,driver:this.driver,logger:this.logger}),this.fixtures.testContext.resetToInitial()}async cleanup(){}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};import aue from"path";async function cG({socket:r,logger:e,orgId:t,testMetadata:n,globalOrgSettings:o,iosDriverFactory:i,mobileGeneratorFactory:a,browserGeneratorFactory:s,browserEnricherFactory:l,storageFactory:c,localToolsFactory:u,globalStateManager:d,getGitMetadata:m}){let p=r.id,f=await m(),h=r.handshake.query?.fileName,g=h?aue.basename(h,".test.yaml"):"",y=n.id,b=n.settings?.defaultChannel,E=n.settings?.defaultTag;e=e.child({sessionId:p,testId:y,orgId:t,branch:f.gitBranchName});let v=await c(t),w=n.settings?.defaultEnv,L={};w&&(L=(await v.fetchEnvironment(w,e))?.variables??{});let I={...o.emulator,...n.settings?.emulator},A=d.getSession(p);if(A){if(e.info("Reconnecting to existing iOS session"),A.local)return r.emit("session",A.metadata),A.softDeleted=!1,A.metadata;throw new Error("Restoring existing remote emulator sessions is not supported. Please reconnect to a new emulator.")}if(I.region==="local")throw new Error("Local region is not supported for iOS tests, as we do not support local iOS emulators.");let _={region:I.region,appToInstall:b?{channel:b,tag:E}:void 0},O=Date.now(),{driver:k,cleanup:D,emulatorName:j,limbarClient:$,limbarWebRtcUrl:xe,limbarToken:B,limbarRegion:Z}=await i({socket:r,logger:e,creationOpts:_});e.info({duration:Date.now()-O,emulatorName:j},"iOS emulator session initiated"),e=e.child({emulator:j});let ie=await a(t,e),se=await s(t,e),Pe=await l(t,e),we=u?await u(t):void 0,he=new io({variablesFromEnvironment:L,envName:w,testName:g}),Ie=await Zu.init({driver:k,generator:ie,logger:e,limbarClient:$,aiSettings:{...o.ai,useMemory:o.ai?.useMemory!==!1,...n.settings?.ai},options:{emulator:{...I,browserSettings:o.browser}},fixtures:{storage:v,browserEnricher:Pe,browserGenerator:se,localCodeEvalTools:we,testContext:he},orgId:t,abortController:new AbortController}),Ot=await Ie.getViewportBounds();if(!r.connected)throw await Ie.cleanup(),await D(),new Error("Socket not connected anymore, not proceeding with iOS session setup");let ke=sue({socket:r,testContext:he}),M=async()=>{clearInterval(ke);try{await Ie.cleanup()}catch(ye){e.warn({err:ye},"Failed to clean up controller in socket server")}try{await D()}catch(ye){e.warn({err:ye},"Failed to clean up emulator in socket server")}},me={sessionId:p,testId:y,orgId:t,emulatorName:j,testName:g,limbarUrl:xe,limbarToken:B,limbarRegion:Z,viewportBounds:Ot,envName:w};return d.registerSession(p,{platform:"IOS",controller:Ie,cleanup:M,emulatorName:j,local:!1,metadata:me}),r.emit("session",me),me}function sue({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}var ob=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async clearSoftDeletedLocalSessions(e){for(let t of this.sessions.values())t.softDeleted===!0&&t.local===!0&&await this.removeSession(t.metadata.sessionId,e)}hasActiveLocalSession(){for(let e of this.sessions.values())if(e.local===!0)return!0;return!1}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up by removeSession")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};function uG(r){let{logger:e,baseServer:t,globalStateManager:n,settingsFactory:o,getOrgId:i}=r,a=new lue(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0,connectionStateRecovery:{maxDisconnectionDuration:60*60*1e3,skipMiddlewares:!0}}),s=async()=>{await n.removeAllSessions(e)};a.on("connection",async c=>{let u=c.id,d=e.child({sessionId:u});d.info({event:"connection",transport:c.conn.transport.name},"Mobile websocket connection initiated"),c.on("disconnect",async f=>{if(e.info({reason:f},"Disconnect received"),f.includes("namespace disconnect")){await _j({socket:c,globalStateManager:n,logger:d,authorization:r.authorization});return}let h=n.getSession(u);h&&(h.softDeleted=!0)});let m,p;try{let f=c.handshake.query?.testMetadata,h=Ma.parse(JSON.parse(f??"")),g=h.id,y=await i({testId:g});switch(p=await o(y,e),h.platform){case"ANDROID":m=await xj({...r,orgId:y,socket:c,globalStateManager:n,logger:d,globalOrgSettings:p,testMetadata:h});break;case"IOS":m=await cG({...r,orgId:y,socket:c,globalStateManager:n,logger:d,globalOrgSettings:p,testMetadata:h});break;default:throw new Error("Unsupported platform")}}catch(f){d.error({err:f},"Failed to setup mobile connection"),c.emit("error",{message:f instanceof Error?f.message:JSON.stringify(f)}),c.disconnect(!0);return}Lj.forEach(f=>l(f,{...r,socket:c,metadata:m,globalOrgSettings:p,logger:d}))});let l=(c,u)=>{let d=c.createHandler(u),m=(...p)=>{c.event!=="keepalive"&&u.logger.debug({event:c.event},`Websocket event (${c.event})`);let f=h=>{u.logger.error({event:c.event,err:h instanceof Error?h:new Error(`${h}`)},"Unhandled exception in socket handler"),u.socket.emit("error",{message:h instanceof Error?h.message:typeof h=="string"?h:JSON.stringify(h)})};try{let h=d.apply(this,p);h&&typeof h.catch=="function"&&h.catch(f)}catch(h){f(h)}};u.socket.on(c.event,m)};return{server:a,dispose:s}}import cue from"adm-zip";import dG from"crypto";import uue from"fs";async function due(r,e){switch(r){case"ANDROID":return uue.promises.readFile(e);case"IOS":{let t=new cue;return t.addLocalFolder(e,void 0,n=>n!==".DS_Store"),t.toBuffer()}}}async function ib({tag:r,channel:e,filePath:t,apiClient:n,logger:o,platform:i}){let a=await due(i,t),s=dG.createHash("md5").update(a).digest("base64"),l=dG.createHash("md5").update(a).digest("hex"),c=await n.generateAssetUploadUrl({channel:e,tag:r??"latest",md5:s,platform:i});if(c.md5&&(c.md5===s||c.md5===l)){o.info({channel:e,tag:r,md5:s,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:s,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let u=await fetch(c.uploadUrl,{headers:{"Content-Length":a.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:a});if(u.status!==200)throw new C("InternalPlatformError",`Got error response from emulator platform: ${u.status} ${await u.text()}`);o.info({channel:e,tag:r,md5:s},`Asset ${t} was uploaded successfully!`);return}catch(u){try{await n.deleteAsset(e,r??"latest",i)}catch(d){o.warn({err:d,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:u},"Failed to upload asset"),u}}throw new C("InternalPlatformError",`No upload URL was given for asset ${t}`)}import zK from"body-parser";import wbe from"cors";import Cbe from"dedent";import{Router as yue}from"express";import ab from"fs";import mue from"path";var pue=new my(30,60*1e3),hR="https://api.momentic.ai",pR,mG,lb=r=>{hR=r},Zp=()=>hR;var cb=r=>{mG=r},ed=()=>mG,nr=()=>pR;var Qu,fR,sb,ub=async r=>{if(pR&&Qu&&sb)return Qu;let e=new Or({baseUrl:hR,apiKey:r,logger:P});pR=e;try{let t=await e.getAuthInfo();return Qu=t.orgId,fR=t.userId,sb=r,Qu}catch(t){throw new Error(`Error checking API key against server: ${t}`,{cause:t})}},Xr=()=>{if(!Qu)throw new Error("Your organization ID is invalid.");return Qu},td=()=>{if(!fR)throw new Error("Your user ID is invalid.");return fR},pG=()=>{if(!sb)throw new Error("Your API key is invalid.");return sb},gR,mR,db=(r,e)=>{gR=r,mR?.abort(),mR=new AbortController;let t=mR.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=mue.resolve(r.rootDir,o.envFile);try{if(ab.lstatSync(i).isSymbolicLink())return;ab.existsSync(i)&&n.push(i)}catch(a){P.warn({err:a},`Failed to check if env file ${i} exists`)}});try{fue({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){P.error({err:o},"Failed to start config file watchers")}},st=()=>gR;function fue({filesToWatch:r,revalidator:e,signal:t,project:n}){P.debug("Starting watch on the following files:"),r.forEach(o=>{P.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,l)=>{s.mtime.getTime()!==l.mtime.getTime()&&(pue.increment("setLocalProject")&&P.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),gR=await Promise.resolve(e(n.configFilePath)))};ab.watchFile(o,{persistent:!1},i);let a=()=>{ab.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ye(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}import{hostname as hue}from"os";var gue="0.59.0",Nl=Zc({app:"desktop-server",hostname:hue(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:gue});(async()=>{try{let r=await Cp(Nl);r.gitBranchName&&Nl.addBinding("branch",r.gitBranchName)}catch{}})();var fG=yue();fG.get("/",async(r,e)=>{let t=st(),n=nr();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Wr(Nl,n,t),i=o?.gitProtectedBranches&&o?.gitBranchName&&o.gitProtectedBranches.includes(o.gitBranchName),{noCache:a,alwaysSaveCache:s}=ed(),l=!a&&(s||!i);e.status(200).json({saveCaches:l,checkedOutBranch:o?.gitBranchName})});var yR=fG;import{Router as Sue}from"express";import Jr from"fs";import{glob as bue}from"glob";import Rr from"path";var Eue=5e3;function SR(r={}){let e=Sue();function t(i){let a=st(),s=Rr.dirname(a.configFilePath);return Rr.join(s,...i)}function n(i){let a=st(),s=Rr.dirname(a.configFilePath),l=Rr.relative(s,i);return l?l.split(Rr.sep):[]}function o(i,a){let s=Jr.statSync(i),l=n(i);return kv.parse({name:a,absolutePath:i,relativePath:l.join(Rr.sep),pathSegments:l,isDirectory:s.isDirectory(),size:s.size,createdAt:s.birthtime,modifiedAt:s.mtime,accessedAt:s.atime})}return e.post("/",Ye(async(i,a,s)=>{let l;try{l=GN.parse(i.body).pathSegments}catch(y){a.status(400).json({error:`Failed to parse folder read body: ${y}`});return}let c=t(l);if(!Jr.existsSync(c)){a.status(404).json({error:`Path not found: ${l.join(Rr.sep)}`});return}if(!Jr.statSync(c).isDirectory()){a.status(400).json({error:`Path is not a directory: ${l.join(Rr.sep)}`});return}let d=st(),m=Array.from(d.config.exclude??[]).concat(Yh),p=AbortSignal.timeout(Eue),f;try{f=await bue("*",{absolute:!1,cwd:c,ignore:m,dotRelative:!1,maxDepth:1,nodir:!1,signal:p})}catch(y){if(y instanceof Error&&y.name==="TimeoutError"){a.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw y}let h=f.map(y=>{let b=Rr.join(c,y);return o(b,y)});if(r.allowedFileTypes){let y=new Set(r.allowedFileTypes);h=(await Promise.all(h.map(async b=>{if(b.isDirectory||!(b.name.endsWith(".test.yaml")||b.name.endsWith(".module.yaml")))return b;let v=await Tue(b.absolutePath);return v!==void 0&&y.has(v)?b:null}))).filter(b=>b!==null)}let g={absolutePath:c,pathSegments:l,contents:h};a.status(200).json(g)})),e.put("/",Ye(async(i,a,s)=>{let l;try{l=WN.parse(i.body).pathSegments}catch(d){a.status(400).json({error:`Failed to parse folder create body: ${d}`});return}let c=t(l);if(Jr.existsSync(c)){a.status(200).json({success:!0,message:`Folder already exists: ${l.join(Rr.sep)}`,pathSegments:l});return}Jr.mkdirSync(c,{recursive:!0});let u={success:!0,message:`Folder created: ${l.join(Rr.sep)}`,pathSegments:l};a.status(201).json(u)})),e.patch("/",Ye(async(i,a,s)=>{let l,c;try{let f=VN.parse(i.body);l=f.pathSegments,c=f.newPathSegments}catch(f){a.status(400).json({error:`Failed to parse folder update body: ${f}`});return}let u=t(l),d=t(c);if(!Jr.existsSync(u)){a.status(400).json({error:`Folder not found: ${l.join(Rr.sep)}`});return}if(Jr.existsSync(d)){a.status(400).json({error:`Destination already exists: ${c.join(Rr.sep)}`});return}let m=Rr.dirname(d);Jr.existsSync(m)||Jr.mkdirSync(m,{recursive:!0}),Jr.renameSync(u,d);let p={success:!0,message:`Folder moved from ${l.join(Rr.sep)} to ${c.join(Rr.sep)}`,pathSegments:c};a.status(200).json(p)})),e.delete("/",Ye(async(i,a,s)=>{let l,c=!0;try{let p=qN.parse(i.body);l=p.pathSegments,c=p.recursive??!0}catch(p){a.status(400).json({error:`Failed to parse folder delete body: ${p}`});return}let u=t(l);if(!Jr.existsSync(u)){a.status(200).json({success:!0,message:`Folder not found: ${l.join(Rr.sep)}`,pathSegments:l});return}if(!Jr.statSync(u).isDirectory()){a.status(400).json({error:`Path is not a directory: ${l.join(Rr.sep)}`});return}if(c)Jr.rmSync(u,{recursive:!0,force:!0});else{if(Jr.readdirSync(u).length>0){a.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${l.join("/")}`});return}Jr.rmdirSync(u)}let m={success:!0,message:`Folder deleted: ${l.join("/")}`,pathSegments:l};a.status(200).json(m)})),e}async function Tue(r){try{let e=await Jr.promises.open(r,"r");try{let t=Buffer.alloc(4096),{bytesRead:n}=await e.read(t,0,t.length,0);return t.toString("utf-8",0,n).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await e.close()}}catch{}}import{Router as vue}from"express";var hG=vue();hG.get("/",async(r,e)=>{let t=st(),n=nr();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Wr(Nl,n,t);e.status(200).json(o)});var bR=hG;import Rbe from"events";import $K,{Router as xbe}from"express";import _be from"http";import Mbe from"path";var mb=new ob;import{Router as wue}from"express";import{existsSync as Cue,statSync as Rue}from"fs";import xue from"path";import{hostname as Aue}from"os";var ER="0.59.0",Tt=Zc({app:"mobile-desktop-server",hostname:Aue(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:ER});(async()=>{try{let r=await Cp(Tt);r.gitBranchName&&Tt.addBinding("branch",r.gitBranchName)}catch{}})();var TR=wue();TR.get("/",Ye(async(r,e)=>{let t=nr();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getMobileAssets();e.status(200).json(n)}));TR.post("/upload-url",Ye(async(r,e)=>{let t;try{t=nL.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}let n=nr();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=xue.resolve(t.filePath);if(!Cue(o)){e.status(400).json({error:`File not found: ${o}`});return}let i=/\.apk$/i.test(o),a=o.endsWith(".app")&&Rue(o).isDirectory();if(!i&&!a){e.status(400).json({error:"Unsupported file type. Only .apk files and .app directories are supported."});return}await ib({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Tt,platform:i?"ANDROID":"IOS"}),e.sendStatus(204)}));var gG=TR;import{Router as Pue}from"express";import{Router as _ue}from"express";import yG from"fs";import Mue from"path";var rd=_ue();async function pb(r){return(await QU(r,Tt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){P.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}rd.get("/",Ye(async(r,e)=>{let t=st(),n=await xt(t),o=await pb(n);e.status(200).json(o)}));rd.get("/tests-join",Ye(async(r,e)=>{let t=st(),n=await xt(t),o=await pb(n),i={};for(let s of o)i[s.id]={...s,tests:[]};let a=await Promise.all(Object.values(n.mobileTests).map(async s=>({id:s.id,name:s.name,relativePath:s.relativePath,test:await Er(s.fullFilePath,Tt,n)})));for(let{id:s,name:l,relativePath:c,test:u}of a){let d=new Set;Ga({steps:u.steps,onPreset:()=>!1,onModule:m=>(d.add(m.moduleId),!1)});for(let m of d){let p=i[m];p&&p.tests.push({id:s,name:l,relativePath:c})}}e.status(200).json(i)}));rd.get("/:moduleId",Ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await xt(st()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await hl(n,t,P);e.json(o)}catch(o){e.status(400).json({err:o})}}));rd.patch("/:moduleId/metadata",Ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=iL.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=st(),o=await xt(n);ZU({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:P,project:n}),e.status(201).json({message:"ok"})}));rd.post("/",Ye(async(r,e)=>{let t;try{t=sL.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{eo(t.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=st(),i=(await xt(n)).mobileModules;if(Object.values(i).find(s=>s.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=Mue.join(n.rootDir,t.folderPath??"");if(!yG.existsSync(a)||!yG.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}switch(t.platform){case"ANDROID":{let s=await _p({...t,folder:a,project:n});e.status(201).json(s);return}case"IOS":{let s=await _p({...t,folder:a,project:n});e.status(201).json(s);return}}}));var SG=rd;var bG=Pue();bG.get("/",Ye(async(r,e)=>{let t=st(),n=await xt(t),o=await pb(n),i=new Set;n?.mobileTests&&Object.values(n.mobileTests).forEach(c=>{c.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),l={labels:a,modules:o,tests:s};e.status(200).json(l)}));var EG=bG;import{Router as Iue}from"express";var fb=Iue();fb.get("/",Ye((r,e)=>{let t=Ry(st(),Tt);e.status(200).json(t)}));fb.get("/names",Ye((r,e)=>{let n=st().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));fb.post("/",Ye((r,e)=>{let t;try{t=oL.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{eo(t.name)}catch(s){e.status(400).json({error:`Invalid environment name: ${s}`});return}let n=st();if(n.config.environments?.find(s=>s.name===t.name)){e.status(400).json({error:`An environment with the name "${t.name}" already exists. Please choose a different name.`});return}let i={...n.config,environments:[...n.config.environments??[],{name:t.name}]};n.config=i,My(i,n.configFilePath);let a=pl(t.name,n,Tt);e.status(201).json(a)}));var TG=fb;import{Router as Oue}from"express";var vG=Oue();vG.get("/",(r,e)=>{e.status(200).json({userId:td(),orgId:Xr(),cliVersion:ER??"0.0.0"})});var AG=vG;import{Router as Nue}from"express";var wG=Nue();wG.get("/",Ye(async(r,e)=>{let t=r.query.sessionId;if(!t){e.status(400).json({packages:[]});return}let n=mb.getSession(t);if(!n?.controller){e.status(200).json({packages:[]});return}try{let o=n.controller,{installedApps:i}=await o.getInstalledApps();e.status(200).json({packages:i})}catch(o){Tt.error({err:o},"Error fetching installed packages from the session controller"),e.status(200).json({packages:[]})}}));var CG=wG;import{Router as Lue}from"express";var vR=Lue(),Due=async({platform:r,steps:e,cacheStorage:t,stepId:n,parentStepIdChain:o,testId:i,environment:a})=>{let{result:s}=Su(e,n,o);if(s)return await t.getCacheKeyForStep({platform:r,logger:Tt,testId:i,environment:a,parentStepIdChain:o,step:s})};vR.patch("/",Ye(async(r,e)=>{let t=st(),n=Xr(),o=nr();if(!o){e.status(500).json({error:"API client not initialized"});return}let i;try{i=uL.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let a=await Wr(Tt,o,t),s=yo({logger:Tt,orgId:n,client:o,gitMetadata:a,regenerateCache:!1,noCache:!1,alwaysSaveCache:!1,isolateCachesByEnvironment:t.config?.advanced?.isolateCachesByEnvironment}),l=await Due({cacheStorage:s,platform:i.platform,steps:i.steps,stepId:i.stepId,parentStepIdChain:i.parentStepIdChain,testId:i.testId,environment:i.environment});if(!l){e.status(400).json({error:"Cache-supporting step not found"});return}await o.updateMobileStepCaches({platform:i.platform,body:{entries:[{key:l,organizationId:n,value:i.value,testId:i.testId,environment:i.environment}]},headers:$m(a)}),e.status(204).send()}));vR.post("/traces",Ye(async(r,e)=>{let t=nr();if(!t){e.status(500).json({error:"API client not initialized"});return}let n;try{n=dL.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o=await t.getMobileStepCacheMemoryTraces(n.platform,n);e.status(200).json(o)}));var RG=vR;import{Router as kue}from"express";import AR from"fs";import ls from"path";import{v4 as Fue}from"uuid";import Uue from"yaml";var nd=kue();nd.patch("/:testPath",Ye(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=tL.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}if(n.steps===void 0&&n.settings===void 0&&n.labels===void 0){e.status(400).json({error:"At least one of steps, settings, or labels is required"});return}let o=st(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await xt(o);await wu({platform:n.platform,filePath:i,steps:n.steps,settings:n.settings,labels:n.labels,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:vn});let s={message:"ok"};e.status(200).json(s)}));nd.post("/",Ye((r,e)=>{let t;try{t=QN.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}let{name:n,description:o,settings:i,pathSegments:a,platform:s}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{eo(n)}catch(h){e.status(400).json({error:h.message});return}let l=st(),c=ls.join(l.rootDir,...a??[]),{fullPath:u,testId:d}=Ny({name:n,description:o,settings:i,folder:c,platform:s}),m=ls.basename(u),p=ls.relative(l.rootDir,u),f={id:d,fileName:m,fullPath:u,relativeFilePath:p};e.status(201).json(f)}));nd.get("/:fileName",Ye(async(r,e)=>{let t=nr(),n=Xr(),o=r.params.fileName;if(!o){e.status(400).json({error:"Missing fileName in path"});return}if(!t){e.status(500).json({error:"API client not initialized"});return}let i=o.endsWith(".test.yaml")?o:`${o}.test.yaml`,a=ls.basename(i).replace(".test.yaml",""),s=st(),l=await xt(s),[c,u]=await Promise.all([Er(i,Tt,l),Wr(Tt,t,s,{includeHostingUsername:!1})]);await yo({logger:Tt,orgId:n,client:t,gitMetadata:u,regenerateCache:!1,noCache:!1,alwaysSaveCache:!1,isolateCachesByEnvironment:s.config?.advanced?.isolateCachesByEnvironment}).resolveEntries({logger:Tt,platform:c.platform,testId:c.id,environment:c.settings?.defaultEnv,stepLists:{steps:c.steps}});let m={...c,name:a};e.status(200).json(m)}));nd.patch("/:testPath/metadata",Ye(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=rL.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}let o=st(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,s={message:"ok",newRelativeTestPath:eB(i,n,o).newRelativeTestPath};e.status(200).json(s)}));nd.post("/:testPath/duplicate",Ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=lL.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{eo(n.name)}catch(h){e.status(400).json({error:h.message});return}let o=st(),i=ls.join(o.rootDir,t);if(!AR.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=await xt(o),s;try{s=await Er(i,Tt,a)}catch(h){e.status(400).json({error:h.message});return}let l=Fue(),{stepsToSave:c}=await _n({...s,createNewCacheIds:!0}),u=ra({fileType:pt.MOBILE_TEST,id:l,schemaVersion:vn,description:s.description,platform:s.platform,settings:s.settings,labels:s.labels,steps:c});RN.parse(u);let d=ls.dirname(i),m=ls.join(d,`${n.name}.test.yaml`);if(AR.existsSync(m)){e.status(409).send("A test with this name already exists");return}let p=Uue.stringify(u);AR.writeFileSync(m,p,"utf-8");let f={relativeFilePath:ls.relative(o.rootDir,m)};e.status(201).json(f)}));var xG=nd;import{Router as Bue}from"express";var _G=Bue();_G.get("/",Ye((r,e)=>{let t=st(),n={ai:t.config.ai,displayRoot:t.config.displayRoot};e.status(200).json(n)}));var MG=_G;import{Router as zue}from"express";var PG=zue();PG.post("/traces",Ye(async(r,e)=>{let t=nr();if(!t){e.status(500).json({error:"API client not initialized"});return}let n;try{n=mL.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o=await t.getWebStepCacheMemoryTraces(n);e.status(200).json(o)}));var IG=PG;var od=class extends xu{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=st();return pl(t,o,P)}};import{randomUUID as vbe}from"crypto";import{existsSync as DG,mkdirSync as $ue}from"fs";import{readdir as Hue,stat as jue,unlink as Gue,writeFile as Wue}from"fs/promises";import Qp from"path";import wR from"path";function vt({text:r,section:e}){if(!e)return[{type:"text",text:r}];let t=`### ${e}`;return r.length===0?[{type:"text",text:t}]:[{type:"text",text:`${t}
4892
+ `).pop()?.replace(/^.*\//,""),!n)throw new C("UserConfigurationError",`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options?.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new C("UserConfigurationError",`Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForPageSourceStability({timeoutMs:3e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),this.stateManager.refreshWebviewsManually("new app launch"),{success:!0}}case"PRESS":{let n=new as(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new as(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<2e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await ee(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new OS(this.constructPerformerParams()).doInstallApk(e);case"UNINSTALL_APP":return new US(this.constructPerformerParams()).doUninstallApk(e);case"ADD_FILE":{let n=await rS(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"TOGGLE_SETTINGS":{switch(e.settingsType){case"AIRPLANE_MODE":await this.driver.toggleAirplaneMode();break;case"DATA":await this.driver.toggleData();break;case"WIFI":await this.driver.toggleWiFi();break;case"LOCATION":await this.driver.toggleLocationServices();break;default:throw e.settingsType,new C("UserConfigurationError",`Unknown settings type: ${e.settingsType}`)}return{success:!0}}case"ROTATE_ORIENTATION":return await this.driver.execute("mobile: shell",{command:"settings",args:["put","system","accelerometer_rotation","0"]}),await this.driver.execute("mobile: shell",{command:"settings",args:["put","system","user_rotation",e.orientation==="LANDSCAPE"?"1":"0"]}),{success:!0,output:{newViewportBounds:await this.getViewportBounds()}};case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new C("UserConfigurationError","No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await K1({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviewsManually("debug cmd");let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??vc;await this.driver.execute("mobile: setGeolocation",{latitude:e,longitude:t}),await Promise.all([this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),this.driver.updateSettings({keyInjectionDelay:Ml})])}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getEmulatorDomState(){return(await this.stateManager.getDomState({})).graph.xml}async executeRawADBCommand(e){return this.stateManager.executeRawADBCommand(e)}async softReset(){await X1(this,this.logger),this.fixtures.testContext.resetToInitial()}async getViewportBounds(){return this.stateManager.getViewportBounds()}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??3e3,reason:e.reason,signal:this.aborter.controller?.signal})}async getMobileFailureRecoveryPlan(e){return this.generator.getAndroidFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.abortSignal,loggerTags:Ee(this.logger)})}async waitForPageSourceStability(e){return this.stateManager.waitForPageSourceStability({timeoutMs:e.timeoutMs??3e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};import{tmpdir as cce}from"os";import Rj from"path";async function xj({socket:r,logger:e,orgId:t,testMetadata:n,globalOrgSettings:o,androidDriverFactory:i,mobileGeneratorFactory:a,browserGeneratorFactory:s,browserEnricherFactory:l,storageFactory:c,localToolsFactory:u,globalStateManager:d,getGitMetadata:m}){let p=r.id,f=await m(),h=r.handshake.query?.fileName,g=h?Rj.basename(h,".test.yaml"):"",y=n.id,b=n.settings?.defaultChannel,E=n.settings?.defaultTag;e=e.child({sessionId:p,testId:y,orgId:t,branch:f.gitBranchName});let v=await c(t),w=n.settings?.defaultEnv,L={};w&&(L=(await v.fetchEnvironment(w,e))?.variables??{});let I=Hc.parse(L[ji]),A=Hc.parse(L[Th]),_={...o.emulator,...n.settings?.emulator},O=n.settings?.defaultApkFilePath?.trim()||A,k=d.getSession(p);if(k){if(e.info("Reconnecting to existing Android session"),k.local)return r.emit("session",k.metadata),k.softDeleted=!1,k.metadata;throw new Error("Restoring existing remote emulator sessions is not supported. Please reconnect to a new emulator.")}let D;if(_.region==="local"){if(await d.clearSoftDeletedLocalSessions(e),d.hasActiveLocalSession())throw new Error("Another local emulator session is already active. Please close the existing session before creating a new one.");let Io=n.settings?.emulator?.localEmulatorSettings?.avdId?.trim()||I;if(!Io)throw new Error(`AVD ID is required when using a local emulator. Set it on the test (Options \u2192 Emulator \u2192 Local AVD ID) or on the environment via ${ji}.`);D={avdId:Io,apkToInstall:b?{channel:b,tag:E}:void 0,apkFilePath:O}}else D={region:_.region,apkToInstall:b?{channel:b,tag:E}:void 0,osVersion:_.remoteEmulatorSettings?.androidVersion};let j=Date.now(),$=await i({socket:r,logger:e,creationOpts:D}),{driver:xe,cleanup:B,emulatorName:Z,adbPort:ie}=$,se,Pe,we,he,Ie;"limbarClient"in $&&(se=$.limbarClient,Pe=$.limbarToken,we=$.limbarUrl,he=$.limbarRegion,Ie=$.playwrightDevice);let Ot=Rj.join(cce(),`logcat-logs-${t}-${y}-${p}.txt`),ke=await aS({driver:xe,onLogs:Io=>{r.emit("logcatLogs",Io)},logFilePath:Ot});e.info({adbPort:ie,apkChannel:b,apkTag:E,duration:Date.now()-j,emulatorName:Z},"Android emulator session initiated"),e=e.child({emulator:Z});let M=await a(t,e),me=await s(t,e),ye=await l(t,e),Ql=u?await u(t):void 0,Pd=new io({variablesFromEnvironment:L,envName:w,testName:g}),Xf=await ss.init({driver:xe,generator:M,logger:e,limbarClient:se,playwrightDevice:Ie,aiSettings:{...o.ai,useMemory:o.ai?.useMemory!==!1,...n.settings?.ai},options:{emulator:{..._,browserSettings:o.browser}},fixtures:{storage:v,browserEnricher:ye,browserGenerator:me,localCodeEvalTools:Ql,testContext:Pd},orgId:t,adbPort:ie,abortController:new AbortController}),x4=await Xf.getViewportBounds();if(!r.connected)throw await Xf.cleanup(),await ke(),await B(),new Error("Socket not connected anymore, not proceeding with Android session setup");let ge=uce({socket:r,testContext:Pd}),_4=async()=>{clearInterval(ge);try{await Xf.cleanup()}catch(Io){e.warn({err:Io},"Failed to clean up controller in socket server")}try{await ke()}catch(Io){e.warn({err:Io},"Failed to stop log listener in socket server")}try{await B()}catch(Io){e.warn({err:Io},"Failed to clean up emulator in socket server")}},YE={sessionId:p,testId:y,orgId:t,emulatorName:Z,testName:g,limbarUrl:we,limbarToken:Pe,limbarRegion:he,viewportBounds:x4,envName:w};return d.registerSession(p,{platform:"ANDROID",controller:Xf,cleanup:_4,emulatorName:Z,local:_.region==="local",metadata:YE,logFilePath:Ot}),r.emit("session",YE),YE}function uce({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}import zS from"fs/promises";async function _j({socket:r,logger:e,globalStateManager:t,authorization:n}){let o=r.id,i=t.getSession(o);i&&i.platform==="ANDROID"&&n&&i.logFilePath&&dce({testId:i.metadata.testId,sessionId:o,logFilePath:i.logFilePath,authorization:n,logger:e}),await t.removeSession(o,e)}async function dce({testId:r,sessionId:e,logFilePath:t,authorization:n,logger:o}){try{let i;try{i=await zS.stat(t)}catch{o.debug({logFilePath:t},"No logcat file found to upload");return}if(i.size===0){o.debug({logFilePath:t},"Logcat file is empty, skipping upload"),await zS.unlink(t);return}let a=new Or(n),{uploadUrl:s}=await a.generateMobileLogcatUploadUrl({testId:r,sessionId:e}),l=await zS.readFile(t),c=await fetch(s,{headers:{"Content-Length":l.length.toString(),"Content-Type":"text/plain"},method:"PUT",body:l});if(c.status!==200)throw new Error(`Failed to upload logcat: ${c.status} ${await c.text()}`);o.info({testId:r,sessionId:e},"Logcat file uploaded successfully")}catch(i){o.warn({err:i,testId:r,sessionId:e},"Failed to upload logcat file")}finally{try{await zS.unlink(t)}catch(i){o.warn({err:i,logFilePath:t},"Failed to delete temp logcat file")}}}var mce=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Mobile session found");t.controller.abort()},Mj={event:"cancel",createHandler:mce};var pce=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Mobile session found"});return}try{let a=i.controller;a.resetAbortController();let s=await a.getEmulatorDomState();o({screenXml:s})}catch(a){r.error({err:a},"Error fetching screen XML from the session controller"),o({err:a.message})}},Pj={event:"fetchScreenXml",createHandler:pce};var rR=class{parentTracer;socket;step;orgId;interactionTracer;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o,this.interactionTracer=new Eo,Yr.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeXmlSnapshot(){}attachAfterXmlSnapshot(){}recordStepDuration(e){let{durationMs:t,step:n}=e;if(!ag(n))return;let o=ig(n);gt.distribution("test_step_duration",t,[`type:${o}`,"platform:mobile","executor:editor",`orgId:${this.orgId}`])}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={result:e.result,parentStepIdChain:e.parentStepIdChain,trace:Ov.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Vu({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},Vu=class{parentTracer;parentStep;socket;orgId;constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,this.orgId=o}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new rR({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async getScreenshot(e){}},$S=class{constructor(e,t){this.socket=e;this.orgId=t}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Vu({parentStep:null,parentTracer:null,socket:this.socket,orgId:this.orgId})}async startMainStepList(){return new Vu({parentStep:null,parentTracer:null,socket:this.socket,orgId:this.orgId})}async startAfterStepList(){return new Vu({parentStep:null,parentTracer:null,socket:this.socket,orgId:this.orgId})}};var fce=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o,getGitMetadata:i})=>async(a,s)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Mobile session found");let c=await i(),u=e.child({testId:a.testMetadata.id,branch:c.gitBranchName}),d=await o(r.orgId,c),m=l.controller;m.resetAbortController();let p=new $S(n,r.orgId),f=await Nu({platform:l.platform,work:{fastForwardingToStep:!!a.fromStep,state:{failureRecoveryDisabled:!0,failureRecoveryAttempts:0}},fixtures:{controller:m,logger:u,cacheStorage:d,usageTracker:new xa},containerName:"entire test",inputs:{steps:a.steps,fromStep:a.fromStep,toStep:a.toStep,orgId:r.orgId,testName:r.testName,testMetadata:a.testMetadata,interactive:!0},envName:r.envName,tracer:p,callbacks:{step:{onAiActionEvent:g=>{n.emit("aiActionEvent",g)}}}});await p.finish();let h={results:Un.array().parse(f.results),status:f.status};s?.(h)},Ij={event:"execute",createHandler:fce};import{debounce as hce}from"ts-debounce";var gce=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=hce(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Mobile session found");o.emulatorName&&(o.local||n(o.platform,o.emulatorName))}},Oj={event:"keepalive",createHandler:gce};var yce=({socket:r,globalStateManager:e,logger:t})=>async(n,o)=>{let i=e.getSession(r.id);if(!i){let s="No active session found";t.error(s),o?.({success:!1,err:s});return}let a=i.controller;a.abort(),a.resetAbortController(),t.info({platform:i.platform},"Resetting emulator state");try{await a.softReset(),t.info({platform:i.platform},"Emulator reset completed"),o?.({success:!0,message:"Emulator reset successfully"})}catch(s){let l=s instanceof Error?s.message:String(s);t.error({err:s,platform:i.platform},"Failed to reset emulator"),o?.({success:!1,err:`Failed to reset emulator: ${l}`})}},Nj={event:"reset",createHandler:yce};var Lj=[Ij,Mj,Nj,Oj,Pj];var HS="NATIVE_APP";var jS=class{constructor(e){this.driver=e}async executeWebViewScript(e,t,...n){return this.executeInContext(e,async o=>{let i=new Function("...args",`${Bp.safariUtilsLibJs}; const userFn = ${t.toString()}; return userFn(momenticFunctions, ...args);`);return o.execute(i,...n)})}async executeInNativeContext(e){return this.executeInContext(HS,e)}async executeInContext(e,t){return await this.driver.switchContext(e),await t(this.driver)}};var Sce=1e4,bce=1e4;function Dj(r,e,t,n){let o=0;async function i(){try{await J(r.executeScript("mobile: getDeviceTime",[]),{milliseconds:bce}),o>0&&(e.info("iOS driver heartbeat restored"),n?.()),o=0}catch(s){o++;let l=s instanceof Error?s.message:`${s}`;if(e.warn({attempt:o,error:l},"iOS driver heartbeat failed"),o>=3){let c="The iOS driver appears unresponsive, indicating a possible emulator failure";e.error({err:s},c),P.error(c),t?.()}}}let a=setInterval(()=>{i()},Sce);return i(),a}import{createInstanceClient as Ece}from"@limrun/api/ios-client";import{hostname as Tce}from"os";async function kj(r){let{apiClient:e,logger:t,creationOpts:n,logLevel:o,orgId:i,sessionId:a,onStatusUpdate:s,onConnectionStateChange:l}=r,c=n.appToInstall?.channel,u=n.appToInstall?.tag;s(`Creating iOS emulator${c?` with app channel ${c}`:""}${u?` and tag ${u}`:""}`);let{token:d,webRtcUrl:m,wdaUrl:p,apiUrl:f,id:h,region:g}=await e.createIosEmulator({...n,hostname:Tce(),sessionId:a});t.info({emulatorName:h,region:g,sessionId:a},"ios instance creation ok"),s("Connecting to iOS emulator...");let y=await gt.recordDuration({fn:async()=>await Ece({apiUrl:f,token:d,logLevel:o}),name:"test_event_duration",tags:["name:limbar-client-creation","clientOs:ios",`orgId:${i}`]});return l&&y.onConnectionStateChange(l),{close:()=>{y.disconnect()},limbarToken:d,limbarWebRtcUrl:m,limbarApiUrl:f,limbarWdaUrl:p,limbarRegion:g,emulatorName:h,limbarClient:y}}async function Fj({wdaUrl:r,token:e}){try{let t=new AbortController;return setTimeout(()=>t.abort(),3e3),await fetch(r+"/status",{headers:{Authorization:`Bearer ${e}`},signal:t.signal}),!0}catch{return!1}}async function GS({creationOpts:r,apiClient:e,logger:t,driverLogLevel:n,appiumPort:o,orgId:i,sessionId:a,callbacks:s}){let l=Date.now();t.info("Starting ios driver creation");let{onLimbarConnectionStateChange:c}=s,u=[];s.onStatusUpdate("Starting iOS emulator creation...");let d=await kj({apiClient:e,logger:t,creationOpts:r,orgId:i,sessionId:a,onStatusUpdate:s.onStatusUpdate,onConnectionStateChange:c,logLevel:n}),m=d.emulatorName;u.push(()=>e.deleteIosEmulator(m),d.close);let p=async()=>{for(let f=u.length-1;f>=0;f-=1)try{await u[f]()}catch(h){if(h instanceof Error&&["ECONNREFUSED","ECONNRESET","UND_ERR_CLOSED"].some(g=>h.message.includes(g)))continue;t.warn({err:h},"Error running cleanup task")}};try{let f=await vce({logger:t,driverLogLevel:n,appiumPort:o,emulatorStart:l,emulatorCreationParams:d,apiClient:e,creationOpts:r,orgId:i,sessionId:a,callbacks:s});u.push(f.appiumClose),u.push(async()=>f.driver.deleteSession()),f.driver.getPageSource().catch(()=>{});let h=Dj(f.driver,t,s.onHeartbeatFailure,s.onHeartbeatRestored);return u.push(()=>{clearInterval(h)}),{...d,...f,driver:new jS(f.driver),cleanup:p,appiumPort:o}}catch(f){throw await p(),new Error(`Failed to start Appium driver: ${f}`,{cause:f})}}async function vce({logger:r,driverLogLevel:e="error",emulatorStart:t,appiumPort:n,emulatorCreationParams:o,callbacks:{onStatusUpdate:i,onLimbarConnectionStateChange:a}}){let s=[],{emulatorName:l,limbarWdaUrl:c,limbarApiUrl:u,limbarToken:d,limbarClient:m}=o,p=Date.now(),f,h;({close:f,logFile:h}=await Lu({logger:r,logLevel:e,appiumPort:n})),await Fj({wdaUrl:c,token:d})||(i("Starting WebDriverAgent..."),r.debug({emulatorName:l},"WDA is not running on the Limbar iOS emulator"),await m.simctl(["launch","booted","com.facebook.WebDriverAgentRunner.xctrunner"]).wait(),r.debug({emulatorName:l},"WDA launched"));let g={platformName:"iOS","appium:automationName":"XCUITest","appium:noReset":!0,"appium:fullReset":!1,"appium:webDriverAgentUrl":c,"appium:wdaLocalPort":443,"appium:useNewWDA":!1,"appium:usePreinstalledWDA":!0,"appium:newCommandTimeout":3600,"appium:autoWebview":!1,"appium:webviewConnectTimeout":500,"appium:webviewConnectRetries":5,"appium:includeSafariInWebviews":!0,"appium:fullContextList":!1,"appium:additionalWebviewBundleIds":["*"],"appium:waitForIdleTimeout":0,"appium:settings":{customSnapshotTimeout:0},"appium:limInstanceApiUrl":u,"appium:limInstanceToken":d,"appium:wdaRequestHeaders":{Authorization:`Bearer ${d}`}};i("Starting Appium session...");let y={capabilities:g,hostname:"localhost",port:n,path:"/",protocol:"http",logLevel:e},b=Date.now(),{driver:E,appiumLogFile:v,appiumServerClose:w}=await iS({logger:r,onStatusUpdate:i,wdOpts:y,appiumPort:n,appiumLogFile:h,appiumServerClose:f,startAppiumServer:()=>Lu({logger:r,logLevel:e,appiumPort:n}),onFailure:async({err:A,attempt:_})=>{let O=oS(A),k=_<3&&O;return k&&r.warn({err:A,appiumPort:n},"Appium driver manifest race detected on first attempt, restarting Appium and retrying"),{shouldRetry:k}}});h=v,f=w;let L=new Map;return E.on("command",A=>{L.set(A.command,Date.now())}),E.on("result",A=>{let _=L.get(A.command);if(!_)return;let O=Date.now()-_;A.result instanceof Error?r.warn({err:A.result,command:A.command,args:A.body,durationMs:O},"Appium cmd failed"):O>1e4&&r.warn({command:A.command,args:A.body,durationMs:O},"Appium cmd took very long"),L.delete(A.command)}),r.info({timings:{emulatorDuration:p-t,appiumDuration:b-p,wdioDuration:Date.now()-b},capabilities:g,emulatorName:l},"Started Appium driver"),{onStatusUpdate:i,driver:E,appiumClose:async()=>{await f(),await Promise.all(s.map(A=>A()))},appiumPort:n,appiumLogFile:h,emulatorName:l}}import{createHash as Uce}from"crypto";import Bce from"jpeg-js";import{PNG as qj}from"pngjs";import Pce from"@prettier/plugin-xml";import Ice from"prettier";import{DOMParser as Oce,XMLSerializer as Nce}from"slimdom";import{reduce as Ace}from"lodash-es";var wce=new Set(["id","processId","bundleId","type","accessible","index","x","y","width","height"]),Cce=new Set([]),Rce=new Set(["name","label","traits"]),xce=new Set(["live-region","drawing-order"]),_ce=new Set(["visible","enabled"]);function Uj(r){let e={},t=r.tagName,n=Ace(r.attributes,(o,i)=>(o[i.name]=i.value,o),{});for(let[o,i]of Object.entries(n))wce.has(o)||o==="class"&&t===i||o==="focusable"&&i==="true"&&n.clickable==="true"||Cce.has(o)&&i==="false"||Rce.has(o)&&i===""||_ce.has(o)&&i==="true"||xce.has(o)&&i==="0"||(e[o]=i);return e.name&&e.label&&e.name===e.label&&delete e.label,e.name&&e.value&&e.name===e.value&&delete e.value,e}function qu(r){let e=r.getAttribute("x"),t=r.getAttribute("y"),n=r.getAttribute("width"),o=r.getAttribute("height");if(e===null||t===null||n===null||o===null)return;let i=parseFloat(e),a=parseFloat(t),s=parseFloat(n),l=parseFloat(o);if(!(isNaN(i)||isNaN(a)||isNaN(s)||isNaN(l)))return{x1:i,y1:a,x2:i+s,y2:a+l}}function nR(r,e){let{x1:t,y1:n,x2:o,y2:i}=e;r.setAttribute("bounds",`[${t}, ${n}, ${o}, ${i}]`)}function Mce(r){let e=r.match(/\[\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\]/);if(!e)return;let t=parseFloat(e[1]),n=parseFloat(e[2]),o=parseFloat(e[3]),i=parseFloat(e[4]);if(!(isNaN(t)||isNaN(n)||isNaN(o)||isNaN(i)||o<t||i<n))return{x1:t,y1:n,x2:o,y2:i}}function Bj(r){let e=r.getAttribute("bounds");if(e)return Mce(e)}function zj(r,e){if(!e)return!0;let t=qu(r);return t?oR(t,e):!0}function oR(r,e){if(!e)return!0;let{x1:t,y1:n,x2:o,y2:i}=r;return!(o<e.left||t>e.right||i<e.top||n>e.bottom)}function $j(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Hj(r){let e=r.cloneNode(!0);for(let t of Array.from(e.children)){let n=t;for(let o of Array.from(n.children))n.removeChild(o)}return e.outerHTML}var jj=new Set(["XCUIElementTypeWebView"]);function Lce(r){if(jj.has(r.tagName))return!0;let e=r.getAttribute("name");if(e&&(e.startsWith("TabDocument")||e.startsWith("BrowserView"))){let t=e.match(/UUID=([A-F0-9-]+)/),n=e.match(/WebViewProcessID=(\d+)/);if(t&&n)return!0}return!1}function Dce(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}function iR({state:r,originalElement:e,prunedElement:t,isInWebview:n}){let{idCounter:o,idToPrunedElement:i,idToOriginalElement:a,webviewIds:s}=r,l=o.value++;t.setAttribute("id",String(l)),i.set(l,t),n?s.add(l):a.set(l,e)}function aR(r){if(jj.has(r.tagName))return r.children.length>0?aR(r.children[0]):void 0;if(r.tagName==="XCUIElementTypeOther"&&r.hasAttribute("name")&&r.hasAttribute("label"))return r;if(r.children.length===1){let e=r.children[0];return aR(e)}}function Gj(r,e,t,n){let{document:o}=t,{parentFrameBounds:i,pruneElementsOutsideBounds:a}=n;if(e.type==="element"){let s=o.createElement(e.role||e.tag);if(e.name&&s.setAttribute("name",e.name),e.description&&s.setAttribute("description",e.description),e.classes&&e.classes.length>0&&s.setAttribute("classes",e.classes.join(" ")),e.attrs)for(let[u,d]of Object.entries(e.attrs))s.setAttribute(u,d);let l=e.boundingRect,c={x1:i.x1+l.x,y1:i.y1+l.y,x2:i.x1+l.x+l.width,y2:i.y1+l.y+l.height};if(!oR(c,a))return;nR(s,c),iR({state:t,prunedElement:s,isInWebview:!0}),r.appendChild(s);for(let u of e.children)Gj(s,u,t,n)}else if(e.type==="text"){let s=o.createElement("text");iR({state:t,prunedElement:s,isInWebview:!0}),r.appendChild(s);let l=o.createTextNode(e.text);s.appendChild(l)}}function Wj(r,e,t,n){let{pruneElementsOutsideBounds:o}=n,{document:i}=t;iR({state:t,originalElement:r,prunedElement:e,isInWebview:!1});let a=Uj(r);for(let[c,u]of Object.entries(a))e.setAttribute(c,u);let s=qu(r);if(s&&nR(e,s),Lce(r)){let{removeWebviewContent:c,injectedWebviewContent:u}=n;if(c)return;if(u){let d=aR(r);if(d){let m=qu(d);if(m){t.webviewRootElement=d,Gj(e,u,t,{parentFrameBounds:m,pruneElementsOutsideBounds:o});return}}}}let l=Array.from(r.childNodes??[]);for(let c of l){let u=c.nodeType;if(u===3){let d=c.nodeValue;d&&d.trim().length>0&&e.appendChild(i.createTextNode(d));continue}if(u===1){let d=c;if(!zj(d,o))continue;let m=i.createElement(Dce(d.tagName));Wj(d,m,t,n),e.appendChild(m)}}}async function kce(r,e,t){let n=r.parseFromString("<AppiumAUT/>","text/xml"),o=new Map,i=new Map,a=new Set,s={document:n,idToPrunedElement:o,idToOriginalElement:i,webviewIds:a,idCounter:{value:0}},l=n.documentElement;Wj(e,l,s,t);let c=new Nce().serializeToString(n),u=await Ice.format(c,{parser:"xml",plugins:[Pce],printWidth:120,tabWidth:1,singleAttributePerLine:!1});return{prunedDocument:n,idToPrunedElement:o,idToOriginalElement:i,webviewIds:a,webviewRootElement:s.webviewRootElement,prunedXml:u}}async function Vj(r,e){let t=new Oce,o=t.parseFromString(r,"text/xml").documentElement;if(!o)throw new Error("No root element found in XML");if(o.tagName!=="AppiumAUT")throw new Error("No AppiumAUT element found in XML");let{prunedXml:i,idToPrunedElement:a,idToOriginalElement:s,webviewIds:l,prunedDocument:c,webviewRootElement:u}=await kce(t,o,e);return{xml:i,idToPrunedElement:a,idToOriginalElement:s,webviewIds:l,webviewRootElement:u,document:c}}var VS=class r{driver;limbarClient;aborter;constructor({driver:e,limbarClient:t,aborter:n}){this.driver=e,this.limbarClient=t,this.aborter=n}static async init({driver:e,limbarClient:t,orgId:n,options:o,aborter:i}){return new r({driver:e,aborter:i,limbarClient:t})}async getContexts(){let e=await this.driver.executeInNativeContext(async n=>await n.getContexts({})),t=e.filter(n=>n!==HS);return{contexts:e.map(n=>n),webviews:t}}async getRawScreenshotBase64(e,t=2){let n=X(),o;for(let i=0;i<t;i++)try{return await n.startAsyncSpan("EMULATOR_READ_STATE",async()=>{let a=await this.limbarClient.screenshot(),s=Buffer.from(a.base64,"base64"),l=Bce.decode(s),c=new qj({width:l.width,height:l.height});return c.data=Buffer.from(l.data),qj.sync.write(c).toString("base64")},{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:5e3})}catch(a){if(o=a,e.warn({err:a},"Failed to take screenshot"),i===t-1)throw a}throw new C("InternalWebAgentError",`Failed to take screenshot: ${o}`)}async getCurrentScreenshotPngString(e){return`data:image/png;base64,${await this.getRawScreenshotBase64(e,1)}`}async waitForScreenshotStability({logger:e,timeoutMs:t,signal:n,reason:o,tolerancePercent:i=1}){await X().startAsyncSpan("WAIT_FOR_PAGE_STABILITY",async a=>{a.attributes.reason=o;let s=Date.now(),l,c,u=!1;for(;Date.now()-s<t;){c&&c<250&&await ee(250-c,n),n?.throwIfAborted();let d=Date.now(),m;try{m=await this.getRawScreenshotBase64(e)}catch(p){e.warn({err:p},"Failed to get screenshot during stability wait"),c=Date.now()-d;continue}if(c=Date.now()-d,l&&es(l,m)<=i){u=!0;break}l=m}u||(a.attributes.timedOut=!0,e.warn({purpose:o},"Timed out waiting for screenshot stability"))})}async waitForPageSourceStability({logger:e,timeoutMs:t,signal:n,reason:o}){await X().startAsyncSpan("WAIT_FOR_PAGE_STABILITY",async i=>{i.attributes.reason=o;let a=Date.now(),s,l,c=!1;for(;Date.now()-a<t;){l&&l<250&&await ee(250-l,n),n?.throwIfAborted();let u=Date.now(),d;try{d=await this.limbarClient.elementTree()}catch(p){e.warn({err:p},"Failed to get page source during stability wait"),l=Date.now()-u;continue}let m=Uce("md5").update(d).digest("hex");if(l=Date.now()-u,s&&s===m){c=!0;break}s=m}c||(i.attributes.timedOut=!0,e.warn({purpose:o},"Timed out waiting for page source stability"))})}async getActiveWebview(){let t=(await this.getContexts()).webviews;if(t.length>1)throw new C("UserInfrastructureError","Multiple active webviews in a single package is currently not supported");return t[0]}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e)return;this.throwIfAborted();let t=await this.driver.executeWebViewScript(e,n=>n.dumpA11yTree());if(t)return JSON.parse(t)}async getDomState(e,t){let o=t?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,i=await this.getPageSource();this.throwIfAborted();let a;if(!t?.skipFetchingFullWebviewContent)try{a=await this.getActiveWebviewContent()}catch(l){e.error({err:l},"Could not get webview info to get the nested DOM state")}return this.throwIfAborted(),{graph:await Vj(i,{injectedWebviewContent:a,removeWebviewContent:t?.removeWebviewContent,pruneElementsOutsideBounds:o})}}async getPageSource(){return await X().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.executeInNativeContext(async n=>n.getPageSource()),{name:"Get iOS page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.executeInNativeContext(async t=>t.getWindowRect());return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};import iue from"zod";async function Kj({command:r,logger:e,generator:t,aiSettings:n,getEmulatorDomState:o,getScreenshotBase64:i,throwIfAborted:a,abortSignal:s}){let l=X(),c=15,u=r.timeoutSecs?r.timeoutSecs*1e3:5e3,d=vy(u),m=Date.now(),p=0,f,h=!1,g;for(;p<c&&!h;){a(),h||f&&f-m>=u&&(h=!0),p!==0&&await ee(d,s),f=Date.now();try{let y="",b="";await l.startAsyncSpan("EMULATOR_READ_STATE",async()=>{y=await o(),b=await i()},{name:"Get emulator state"});let E=await t.evaluateIosAssertion({assertion:r.assertion,screenXml:y,screenshot:b},{logger:e,loggerTags:Ee(e),agentConfigVersion:n.agentConfig?.["ios-assertion"]});if(E.result)return{success:E.result,message:E.thoughts};{let v=`AssertionFailureError: ${E.thoughts}`;g=new Error(v)}}catch(y){a(),e.info({err:y},`AI check assert attempt ${p} failed, retrying...`),g=y instanceof Error?y:new Error(`${y}`)}finally{p++}}return{success:!1,message:g?.message}}async function Yj({command:r,logger:e,generator:t,aiSettings:n,getEmulatorDomState:o,getScreenshotBase64:i,abortSignal:a}){if(!r.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let u=Yc(r.schema);if(u)throw new C("UserConfigurationError",u)}let s=X(),l="",c="";await s.startAsyncSpan("EMULATOR_READ_STATE",async()=>{l=await o(),c=await i()},{name:"Get emulator state"});try{let u=await t.getIosTextExtraction({goal:r.goal,emulatorState:l,returnSchema:r.schema,screenshot:`data:image/png;base64,${c}`},{disableCache:!!r.disableCache,abortSignal:a,loggerTags:Ee(e),agentConfigVersion:n.agentConfig?.["ios-text-extraction"]});if(u.result==="NOT_FOUND")return{success:!1,message:"No relevant data found for extraction goal on this page"};if(u.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",u.thoughts);return{success:!0,output:u.result,message:u.thoughts}}catch(u){let d=u instanceof Error?u.message:String(u);throw d.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step instead."):d.includes("AIProviderError")&&d.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:u}}):u}}import{cloneDeep as cR}from"lodash-es";function qS(r,e){return Math.abs(r-e)<1}async function zce(r,e){return await r.getElementText(e)}async function $ce(r,e,t){return await r.getElementAttribute(e,t)??null}function Hce(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r.x1+r.x2)/2;if(!Ri(e.tolerance,n,o,Math.min(1,t)))return!1;let i=e.y2-e.y1,a=(e.y1+e.y2)/2,s=(r.y1+r.y2)/2;return Ri(e.tolerance,a,s,Math.min(1,i))}function jce(r,e){let t=r.x2-r.x1,n=r.y2-r.y1;return Ri(e.tolerance,e.width,t,Math.min(1,e.width))?Ri(e.tolerance,e.height,n,Math.min(1,e.height)):!1}async function sR(r,e,t,n,o){if(!n)return;let{requiredAttributes:i,requiredText:a,requiredBounds:s,position:l,shape:c}=n;if(a!==void 0&&a.length>0){let u=await zce(e,t);r.debug({actualText:u,expectedText:a},"Got element text content")}if(i)for(let[u,d]of Object.entries(i)){let m=await $ce(e,t,u)??void 0;if(m!==d)throw new Ze(`Attribute ${u} mismatch: expected ${d}, got ${m}`)}if(s&&o){let{originalBounds:u,newBounds:d}=o;if(!u)throw new Ze("Cannot validate bounds requirements without original bounds in cache");if(!(qS(u.x1,d.x1)&&qS(u.y1,d.y1)&&qS(u.x2,d.x2)&&qS(u.y2,d.y2))){let p=f=>`[${f.x1},${f.y1},${f.x2},${f.y2}]`;throw new Ze(`Bounds changed from ${p(u)} to ${p(d)}`)}}if(l&&o&&!Hce(o.newBounds,l))throw new Ze(`Position mismatch: expected ${JSON.stringify(l)}, got ${JSON.stringify(o.newBounds)}`);if(c&&o&&!jce(o.newBounds,c))throw new Ze(`Shape mismatch: expected ${JSON.stringify(c)}, got ${JSON.stringify(o.newBounds)}`)}function lR(r){let e=[],t=r;for(;t;){let n=t.parentElement;if(!n||n.tagName==="AppiumAUT"){e.unshift(`${t.tagName}[1]`);break}let o=t.tagName,i=Array.from(n.children).filter(s=>s.tagName===o),a=1;for(let s=0;s<i.length;s++)if(i[s]===t){a=s+1;break}e.unshift(`${o}[${a}]`),t=n}return`/${e.join("/")}`}var Ku="element-6066-11e4-a52e-4f735466cecf";async function KS({target:r,driver:e,logger:t}){if(!r.xPath)throw new Ze(`Could not resolve cached target via XPath: ${r.xPath}`);if(r.requiredRelatedElements){let o=r.requiredRelatedElements;for(let i of o)await e.executeInNativeContext(async a=>{let s=await Xj(a,i.xPath);if(!s)throw new Ze(`Could not resolve required related element via XPath: ${i.xPath}`);await sR(t,a,s.elementId,i.requirements)})}let n=await e.executeInNativeContext(async o=>{let i=await Xj(o,r.xPath);if(!i)throw new Ze(`Could not resolve element via XPath: ${r.xPath}`);let{rect:a,elementId:s}=i,l={x1:a.x,y1:a.y,x2:a.x+a.width,y2:a.y+a.height};return await sR(t,o,s,r.requirements,{originalBounds:r.bounds?{x1:r.bounds[0],y1:r.bounds[1],x2:r.bounds[2],y2:r.bounds[3]}:void 0,newBounds:l}),l});return{type:"NATIVE",bounds:n,cache:{...r,bounds:[n.x1,n.y1,n.x2,n.y2]}}}async function Xj(r,e){try{let t=await r.findElement("xpath",e);if(!t)return null;let n=t[Ku];if(!n)return null;let o=await r.getElementRect(n);return{elementId:n,rect:o}}catch{return null}}function Zj({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToPrunedElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Bj(n);if(!o)throw new Error(`Could not determine bounds for element with id: ${r.id}, description: ${e}`);if(t.graph.webviewIds.has(r.id))return{type:"WEBVIEW",cache:{type:"WEBVIEW"},bounds:o};let a=t.graph.idToOriginalElement.get(r.id);if(!a)throw new Error(`Node isn't in a webview but couldn't find original node for id: ${r.id}, description: ${e}`);let s=lR(a),l=Hj(a),c=Jj({requirements:r.requirements,element:a}),u=(r.additionalElements??[]).map(({id:d,requirements:m})=>{let p=t.graph.idToOriginalElement.get(d);return!p||t.graph.webviewIds.has(d)?void 0:{xPath:lR(p),requirements:Jj({requirements:m,element:p})}}).filter(d=>!!d);return{type:"NATIVE",bounds:o,cache:{type:"NATIVE",bounds:[o.x1,o.y1,o.x2,o.y2],resolvedDescription:e,xPath:s,elementOnlySerializedXml:l,requirements:c,requiredRelatedElements:u}}}function Yp(r){return r.type==="WEBVIEW",r.cache}function Xp(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Rv(e)&&(e[t]={...e[t],[n]:Mc.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date,e[t].updatedAtLoggerTags=Ee(r.logger)))}function Jj({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=qu(e),!t))throw new C("ActionFailureError","Element to cache has no bounds or unexpected bounds format");return{requiredText:r?.textRequired?e.getAttribute("text")??void 0:void 0,requiredAttributes:$j(e,r?.attributesRequired),requiredBounds:r?.boundsRequired,position:r?.positionSpecificity?{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,tolerance:r?.positionSpecificity}:void 0,shape:r?.shapeSpecificity?{width:t.x2-t.x1,height:t.y2-t.y1,tolerance:r?.shapeSpecificity}:void 0}}var hr=class{limbarClient;driver;stateManager;generator;fixtures;orgId;aiSettings;emulatorSettings;aborter;constructor(e){this.stateManager=e.stateManager,this.driver=e.driver,this.limbarClient=e.limbarClient,this.aborter=e.aborter,this.fixtures=e.fixtures,this.orgId=e.orgId,this.generator=e.generator,this.aiSettings=e.aiSettings,this.emulatorSettings=e.emulatorSettings}async findElement({logger:e,tracer:t,description:n,skipFetchingFullWebviewContent:o=!1,removeWebviewContent:i=!1,useMemory:a=!1,metadata:s,cacheBustReason:l}){let c=e.child({...s});await this.stateManager.waitForScreenshotStability({logger:e,timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let{emulatorState:u,screenshot:d}=await t.startAsyncSection("Get emulator state",async()=>{let f=await this.stateManager.getCurrentScreenshotPngString(e);return{emulatorState:await this.stateManager.getDomState(e,{skipFetchingFullWebviewContent:o,removeWebviewContent:i}),screenshot:f}}),m;try{m=await t.startAsyncSpan("AI_LOCATOR_CALL",async f=>{l&&(f.attributes.cacheBustReason=l);let h=await this.generator.getIosElementLocation({description:n,screenXml:u.graph.xml,screenshot:d},{logger:c,loggerTags:Ee(c),abortSignal:this.aborter.controller?.signal,useMemory:a,agentConfigVersion:this.aiSettings.agentConfig?.["ios-locator"]});return f.result=h,h})}catch(f){throw this.throwIfAborted(),c.error({err:f},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${f instanceof Error?f.message:f}`,{cause:f})}if(m.id===-1)throw new C("NoMatchingElementError",m.thoughts??"No matching element found");let p=Zj({aiResponse:m,description:n,emulatorState:u});return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:(p.type==="NATIVE"?p.cache.elementOnlySerializedXml:void 0)??"Unknown element"},attributes:{},subSpans:[]}),{resolvedTarget:p,thoughts:m.thoughts}}async targetingActionWithAILocator(e){let{tracer:t,action:n,command:o,description:i,cacheKey:a,targetName:s,skipFetchingFullWebviewContent:l,removeWebviewContent:c,metadata:u,logger:d,cacheBustReason:m}=e,p=await this.findElement({logger:d,tracer:t,description:i,skipFetchingFullWebviewContent:l,removeWebviewContent:c,metadata:u,cacheBustReason:m}),f=p.thoughts,h=await n(p.resolvedTarget);return Xp({command:o,cacheKey:a,targetName:s,updatedCache:Yp(p.resolvedTarget),updatedWithAI:!0,logger:d}),{result:h,thoughts:f}}async targetingActionWithCache({logger:e,tracer:t,action:n,command:o,cacheKey:i,targetName:a,cacheCopyForAttempt:s}){this.emulatorSettings?.waitForStability&&await this.stateManager.waitForPageSourceStability({logger:e,timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let{resolvedTarget:l}=await t.startAsyncSpan("CACHE_RESOLUTION",async u=>{let d=await KS({target:s,driver:this.driver,logger:e});return u.attributes.serializedElement=(d.type==="NATIVE"?d.cache.elementOnlySerializedXml:void 0)??"Unknown element",{resolvedTarget:d}}),c=await n(l);return Xp({command:o,cacheKey:i,targetName:a,updatedCache:Yp(l),updatedWithAI:!1,logger:e}),{result:c,thoughts:"Successfully executed preset action with cache"}}async wrapTargetingAction(e){let{tracer:t,logger:n,action:o,description:i,command:a,cacheKey:s="cache",targetName:l="target",cacheIsInvalidAfterResolution:c,skipFetchingFullWebviewContent:u=!1,removeWebviewContent:d=!1}=e,m={commandId:a.id},p=!1,f,h;if(s==="cache"&&"cache"in a&&a.cache){let g=a.cache;l==="target"&&"target"in g&&g.target?.type==="NATIVE"?h=cR(g.target):l==="fromTarget"&&"fromTarget"in g&&g.fromTarget?.type==="NATIVE"?h=cR(g.fromTarget):l==="toTarget"&&"toTarget"in g&&g.toTarget?.type==="NATIVE"&&(h=cR(g.toTarget))}if(a.disableCache&&(n.debug({command:a},"Cache explicitly disabled for command"),p=!0,f="Cache explicitly disabled",h=void 0),c&&(p=!0,f=f??"Cache invalidated after resolution",h=void 0),h&&h.resolvedDescription!==i&&(n.info({description:i,cacheDescription:h.resolvedDescription},"Cache description mismatch, clearing it automatically"),p=!0,f="Description mismatch",h=void 0),h)try{let g=await this.targetingActionWithCache({logger:n,tracer:t,action:o,command:a,cacheKey:s,targetName:l,cacheCopyForAttempt:h});return gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:mobile-native",`hasRequirements:${!!h.requirements}`,`orgId:${this.orgId}`,"cliVersion:0.59.1"]),g}catch(g){if(this.throwIfAborted(),g instanceof C&&g.reason!=="InternalWebAgentError")throw n.error({err:g},"Failed to execute action with target cache (fatal)"),g;gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:mobile-native",`hasRequirements:${!!h.requirements}`,`orgId:${this.orgId}`,"cliVersion:0.59.1"]),n.warn({err:g},"Failed to execute action with target cache, retrying with AI")}return n.info({description:i,cacheBustedBeforeAction:p},"Prompting AI for a new element location"),await this.targetingActionWithAILocator({tracer:t,action:o,command:a,description:i,cacheKey:s,targetName:l,skipFetchingFullWebviewContent:u,removeWebviewContent:d,metadata:m,logger:n,cacheBustReason:f})}constructPerformerParams(){return{limbarClient:this.limbarClient,stateManager:this.stateManager,driver:this.driver,fixtures:this.fixtures,emulatorSettings:this.emulatorSettings,aborter:this.aborter,orgId:this.orgId,generator:this.generator,aiSettings:this.aiSettings}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};var YS=class extends hr{async doDrag(e,t,n,o){let{x1:i,y1:a,x2:s,y2:l}=t.bounds,c=i+(s-i)/2,u=a+(l-a)/2;e.attributes.startPoint={x:c,y:u};let{x1:d,y1:m,x2:p,y2:f}=n.bounds,h=d+(p-d)/2,g=m+(f-m)/2;e.attributes.endPoint={x:h,y:g};let y=o?.hoverDuration??500,b=o?.dragDuration??1e3;b===0&&(b=1);let v=Math.sqrt(Math.pow(h-c,2)+Math.pow(g-u,2))/b*1e3;await this.driver.executeInNativeContext(async w=>{await w.execute("mobile: dragFromToWithVelocity",{fromX:c,fromY:u,toX:h,toY:g,pressDuration:y/1e3,velocity:v,holdDuration:.5})})}async executeDragAndDrop({logger:e,command:t}){let n=X();if(t.fromTarget.type!=="description"||t.toTarget.type!=="description")throw new C("UserConfigurationError","Drag and drop only supports description targets for now");let o=t.fromTarget.description,{result:i,thoughts:a}=await this.wrapTargetingAction({command:t,tracer:n,description:o,cacheKey:"cache",targetName:"fromTarget",action:async u=>u,logger:e}),s=t.toTarget.description,{result:l,thoughts:c}=await this.wrapTargetingAction({command:t,tracer:n,description:s,cacheKey:"cache",targetName:"toTarget",action:async u=>u,logger:e});return await n.startAsyncSpan("EMULATOR_INTERACTION",async u=>{await this.doDrag(u,i,l,{hoverDuration:t.hoverDuration,dragDuration:t.dragDuration})},{name:"Drag and drop"}),{success:!0,message:`${a}
4893
+ ${c}`}}};import{cloneDeep as Qj}from"lodash-es";var XS=class{driver;constructor(e){this.driver=e}async getTextContent(e){let t=e.cache.xPath;return t?await this.driver.executeInNativeContext(async o=>{try{let a=(await o.findElement("xpath",t))[Ku];if(!a)return"";let s=await o.getElementAttribute(a,"label"),l=await o.getElementAttribute(a,"value");return[s,l].filter(u=>!!u&&u.trim().length>0).join(" ").trim()}catch{return""}})??"":""}async getAttribute(e,t){let n=e.cache.xPath;return n?await this.driver.executeInNativeContext(async i=>{try{let s=(await i.findElement("xpath",n))[Ku];return s?await i.getElementAttribute(s,t)??"":""}catch{return""}})??"":""}async getTagName(e){let t=e.cache.xPath;return t?await this.driver.executeInNativeContext(async o=>{try{let a=(await o.findElement("xpath",t))[Ku];return a?await o.getElementTagName(a)??"":""}catch{return""}})??"":""}async isEditable(e){throw new C("UserConfigurationError","Editable checks are not supported on iOS native elements")}async isEnabled(e){let t=e.cache.xPath;return t?await this.driver.executeInNativeContext(async n=>{try{let i=(await n.findElement("xpath",t))[Ku];return i?await n.isElementEnabled(i):!1}catch{return!1}}):!1}async isFocused(e){let t=await this.getAttribute(e,"focused");return t==="true"||t==="1"}async getStyleProperty(e,t){throw new C("UserConfigurationError","Computed style checks are not supported on iOS native elements")}},JS=class{driver;webviewContext;constructor(e,t){this.driver=e,this.webviewContext=t}getCenter(e){let{x1:t,y1:n,x2:o,y2:i}=e.bounds;return{x:(t+o)/2,y:(n+i)/2}}async getTextContent(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?l.innerText??l.textContent??"":""},t,n)??""}async getAttribute(e,t){let{x:n,y:o}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(a,s,l,c)=>{let u=document.elementFromPoint(s,l);return u?u.getAttribute(c)??"":""},n,o,t)??""}async getTagName(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?l.tagName:""},t,n)??""}async isEditable(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);if(!l)return!1;let c=l.tagName;return c==="INPUT"||c==="TEXTAREA"||c==="SELECT"||l.isContentEditable},t,n)}async isEnabled(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?!l.disabled:!1},t,n)}async isFocused(e){let{x:t,y:n}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(i,a,s)=>{let l=document.elementFromPoint(a,s);return l?document.activeElement===l:!1},t,n)}async getStyleProperty(e,t){let{x:n,y:o}=this.getCenter(e);return await this.driver.executeWebViewScript(this.webviewContext,(a,s,l,c)=>{let u=document.elementFromPoint(s,l);return u?window.getComputedStyle(u).getPropertyValue(c):""},n,o,t)??""}};var Gce=5e3,ZS=class extends hr{async executeElementCheck({logger:e,command:t}){let n=Date.now(),o=(t.timeout??ur)*1e3,i=o+1e4,a,s=0,l=500,c=Qj(t.cache);if(t.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Element check step");for(;s-n<o;){if(Date.now()-n>i){e.warn("Exceeded max system timeout for element check, exiting...");break}if(this.throwIfAborted(),a=await this.executeElementCheckHelper({logger:e,command:t}),s=Date.now(),!a.success)t.cache=c,c=Qj(c),await ee(l,this.abortSignal),l=Math.min(Math.floor(l*1.5),Gce);else return a}let u=await this.executeElementCheckHelper({logger:e,command:t,cacheIsInvalidAfterResolution:!0});if(!u.success&&c&&t.cache){let d=IU({logger:e,originalTarget:Cv(c)?c.target:void 0,newTarget:t.cache.target});d&&na(c.target,d)&&(t.cache={target:d,updatedAt:t.cache.updatedAt})}return u}async executeElementCheckHelper({logger:e,command:t,cacheIsInvalidAfterResolution:n}){let o=X();if(t.target.type!=="description")throw new C("UserConfigurationError","x/y targets are not supported for the Element check step");let i=yu(t.assertion);try{return(await this.wrapTargetingAction({...n?{cacheIsInvalidAfterResolution:n}:{},command:t,tracer:o,action:async s=>s.type==="NATIVE"?await this.executeNativeElementCheck(t,s):await this.executeWebviewElementCheck(t,s),description:t.target.description,skipFetchingFullWebviewContent:!0,removeWebviewContent:!0,logger:e})).result}catch(a){return i&&(a instanceof C&&a.reason==="NoMatchingElementError"||a instanceof ni)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${a instanceof Error?a.message:`${a}`}`}}}async executeNativeElementCheck(e,t){let n=X(),{assertion:o}=e;return await n.startAsyncSpan("ELEMENT_ASSERTION",async i=>{let a=await this.executeElementAssertion({assertion:o,element:t,elementPropertyAccessors:new XS(this.driver),span:i});return i.result=a,a},{name:"Native element check"})}async executeWebviewElementCheck(e,t){let n=X(),{assertion:o}=e,a=(await this.stateManager.getContexts()).webviews[0];if(!a)throw new C("UserConfigurationError","No active webview context found for element check");return await n.startAsyncSpan("ELEMENT_ASSERTION",async s=>{let l=await this.executeElementAssertion({assertion:o,element:t,elementPropertyAccessors:new JS(this.driver,a),span:s});return s.result=l,l},{name:"Webview element check"})}async executeElementAssertion({assertion:e,element:t,elementPropertyAccessors:n,span:o}){switch(e.type){case"ELEMENT_CONTENT":{let i=await n.getTextContent(t)??"";return o.attributes.elementTextContent=Xt(i,500,!0),pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${Ar(e)} '${e.value}': ${i}`}}case"ELEMENT_ATTRIBUTE":{let i=null;try{i=await n.getAttribute(t,e.attr)}catch{i=null}if(!pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=Ar(e);return{success:!1,message:`The attribute ${e.attr} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}case"ELEMENT_EXISTENCE":{let i=!1;switch(e.condition){case"EDITABLE":i=await n.isEditable(t);break;case"VISIBLE":case"EXISTS":i=!0;break;case"ENABLED":{i=await n.isEnabled(t);break}case"FOCUSED":i=await n.isFocused(t);break;default:throw e.condition,new Error("Unrecognized element condition type")}return i=e.negated?!i:i,i?{success:!0}:{success:!1,message:`The element ${Ar(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${Ar(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!pn(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=Ar(e);return{success:!1,message:`The style property ${e.property} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}default:throw new Error("Unrecognized element assertion type")}}};async function eG({command:r,orgId:e,logger:t,fixtures:n,abortSignal:o}){let i;try{i=await bo({orgId:e,code:r.code,fragment:!1,context:n.testContext,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:t,localTools:n.localCodeEvalTools,signal:o})}catch(a){throw new C("ActionFailureError",a instanceof C?a.message:`${a}`,{errOptions:{cause:a}})}try{JSON.stringify(i)}catch(a){throw new C("UserConfigurationError",`Return value is not serializable: ${a instanceof Error?a.message:`${a}`}`)}return{success:!0,output:i}}async function tG({command:r,driver:e}){switch(r.key){case"ENTER":await e.executeInNativeContext(t=>t.keys(["\uE007"]));break;case"BACKSPACE":await e.executeInNativeContext(t=>t.keys(["\uE003"]));break;default:{let t=r.key}}return{success:!0}}import QS from"zod";var rG=QS.object({name:QS.string(),pid:QS.number(),bundleId:QS.string()});var Yu=class extends hr{async doPress({name:e,longPress:t}){return this.driver.executeInNativeContext(n=>n.executeScript("mobile: pressButton",[{name:e,isLongPress:t}]))}};var eb=class extends hr{async execute(){let e;try{let n=await this.driver.executeInNativeContext(i=>i.executeScript("mobile: activeAppInfo",[]));e=rG.parse(n).bundleId}catch(n){throw new C("UserConfigurationError",`Failed to get active app info: ${n.message}`)}return await new Yu(this.constructPerformerParams()).doPress({name:"home"}),await this.limbarClient.terminateApp(e),{success:!0}}};import Wce from"fetch-cookie";import{CookieJar as Vce}from"tough-cookie";async function nG({command:r,logger:e}){let t;try{t=new URL(r.url).hostname}catch(l){throw new C("UserConfigurationError",`Invalid URL: ${l instanceof Error?l.message:`${l}`}`)}let n=new Vce,o=Wce(fetch,n),i=Date.now(),a=await $u({command:r,baseUrl:void 0,logger:e,fetchImplementation:o}),s=Dc(n,t);return{output:Is.parse({...a,cookies:s}),success:!0,message:`Successfully executed request in ${Date.now()-i}ms`}}async function oG({command:r,limbarClient:e,getViewportBounds:t}){return await e.setOrientation(r.orientation==="LANDSCAPE"?"Landscape":"Portrait"),{success:!0,output:{newViewportBounds:await t()}}}var qce=5e3,tb=class extends hr{async executeScreenCheck(e,t){let{timeout:n}=t,o=Date.now(),i=(n??ur)*1e3,a=i+1e4,s=0,l=500;for(;s-o<i;){if(Date.now()-o>a){e.warn("Exceeded max system timeout for screen check, exiting...");break}this.throwIfAborted();let c=await this.executeScreenCheckHelper(e,t);if(s=Date.now(),!c.success)await ee(l,this.abortSignal),l=Math.min(Math.floor(l*1.5),qce);else return c}return await this.executeScreenCheckHelper(e,t)}async executeScreenCheckHelper(e,t){let{assertion:n}=t;switch(n.type){case"CONTENT":try{let i=(await this.stateManager.getDomState(e,{skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.xml;if(!i)throw new Error("Failed to get screen XML");let a=i.includes(n.value)===!n.negated;return i.length>1e4&&(i=i.slice(0,1e4)+"...TRUNCATED"),a?{success:!0}:{success:!1,message:`The screen ${Sp(n)}.`}}catch(o){return{success:!1,message:`Failed to evaluate screen content assertion: ${o instanceof Error?o.message:`${o}`}`}}default:return n.type,{success:!1,message:`Unsupported screen check assertion type: ${n.type}`}}}};var Kce=.8,Jp=.2,Xu=class extends hr{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getContainerBoundsFromViewport(t);break;case"OPEN_APP":n=this.getContainerBoundsFromViewport(t);break;case"OPEN_WEBVIEW":{n=this.getContainerBoundsFromViewport(t);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getContainerBoundsFromViewport(e){return{left:e.x,top:e.y,width:e.width,height:e.height}}getContainerBoundsFromBounds(e){let t=e.x1,n=e.y1,o=e.x2,i=e.y2,a=o-t,s=i-n;return{left:t,top:n,width:a,height:s}}async executeSwipe({logger:e,command:t}){let n=X();if(t.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:i,startY:a,deltaPixels:s}=t.scrollableElement;return await n.startAsyncSpan("EMULATOR_INTERACTION",async l=>{await this.performSwipe({span:l,startX:i,startY:a,deltaPixels:s,direction:t.direction,durationMs:t.durationMs})},{name:`Swipe ${t.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(t.scrollableElement.type!=="CUSTOM"){let i=await this.driver.executeInNativeContext(async s=>s.getWindowRect()),a=await this.getHardcodedScrollableElementBounds(t.scrollableElement,i);return await n.startAsyncSpan("EMULATOR_INTERACTION",async s=>{await this.swipeByAbsoluteCoordinates({span:s,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:a,relativePosition:t.relativePosition})},{name:`Swipe ${t.direction} in the entire ${t.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:o}=await this.wrapTargetingAction({command:t,description:t.scrollableElement.target.description,action:async i=>X().startAsyncSpan("EMULATOR_INTERACTION",async s=>this.scrollInNativeContainer({span:s,cmd:t,target:i}),{name:`Swipe ${t.direction} in the specified container`}),tracer:n,logger:e});return{success:!0,message:o}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds,i=this.getContainerBoundsFromBounds(o);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:i,relativePosition:t.relativePosition})}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=Kce,durationMs:o=500,containerBounds:i,relativePosition:a}){e.attributes.containerBounds=i;let s=t==="up"||t==="down",l=i.width*Jp,c=i.height*Jp,u=s?(i.height-2*c)*n:(i.width-2*l)*n,d,m;a?(d=i.left+a.x,m=i.top+a.y):(d=i.left+i.width/2,m=i.top+i.height/2),await this.performSwipe({span:e,startX:d,startY:m,deltaPixels:u,direction:t,durationMs:o})}async performSwipe({span:e,startX:t,startY:n,deltaPixels:o,direction:i,durationMs:a=300}){let s=Math.abs(o),l=t,c=n;i==="up"||i==="down"?c=i==="up"?n-s:n+s:l=i==="left"?t-s:t+s,e.attributes.pixelDelta=s,e.attributes.startPoint={x:t,y:n},e.attributes.endPoint={x:l,y:c},e.attributes.durationMs=a,await this.driver.executeInNativeContext(async u=>{let d={type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:t,y:n},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:a,x:l,y:c},{type:"pointerUp",button:0}]};await u.performActions([d]),await u.releaseActions()})}};var Yce=5,iG=.8,Xce=1;function Jce(r){return r.type==="NATIVE"&&r.scrollDetails!==void 0}var rb=class extends Xu{async executeScrollTo({logger:e,command:t}){let n=t.target.description,o=t.scrollStepPercent??iG,i=await this.tryUseCachedScrollPosition(e,t,n);return i||this.searchForElement(e,t,n,o)}async resolveContainer({logger:e,scrollableElement:t,containerCache:n}){let o=await this.driver.executeInNativeContext(async c=>c.getWindowRect());if(t.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:o.width,height:o.height}};if(t.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(t,o)};let i=X(),a=t.target.description;if(n){let c=this.getBoundsFromNativeCache(n);return e.info({bounds:c},"Got container bounds from native cache"),{bounds:c,cache:n}}let{resolvedTarget:s}=await this.findElement({logger:e,description:a,tracer:i});if(s.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${a}" resolved to a webview element. Custom containers must be native elements.`);let l=this.getBoundsFromNativeCache(s.cache);return e.info({bounds:l},"Got container bounds from AI"),{bounds:l,cache:s.cache}}getBoundsFromNativeCache(e){if(!e.bounds||e.bounds.length<4)throw new C("ActionFailureError","Native target cache has no bounds");let[t,n,o,i]=e.bounds;return{left:t,top:n,width:o-t,height:i-n}}async tryUseCachedScrollPosition(e,t,n){let o=t.cache?.target;if(o&&Jce(o)&&o.scrollDetails!==void 0)return this.tryUseNativeScrollCache(e,t,n,o)}async tryUseNativeScrollCache(e,t,n,o){let i=o.scrollDetails,a=X(),s=t.scrollStepPercent??iG,l=i.scrollableElement.type==="CUSTOM"&&i.scrollableElement.cache?.type==="NATIVE"?i.scrollableElement.cache:void 0;await this.scrollByPixelDelta({logger:e,pixelDelta:i.pixelDelta,scrollableElement:i.scrollableElement,containerCache:l,direction:i.direction,scrollStepPercent:s});try{let u=await this.tryFindElement({logger:e,cmd:t,description:n,tracer:a,scrollDetails:i,useAIIfCacheFails:!1});if(u)return u;e.info("Element not found at cached position, undoing scroll")}catch(u){e.warn({err:u},"Error finding element at cached position, will undo scroll")}let c=i.direction==="down"?"up":"down";e.info({pixelDelta:i.pixelDelta,originalDirection:i.direction,undoDirection:c,scrollableElementType:i.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({logger:e,pixelDelta:i.pixelDelta,scrollableElement:i.scrollableElement,containerCache:l,direction:c,scrollStepPercent:s})}async tryFindElement({logger:e,cmd:t,description:n,tracer:o,scrollDetails:i,useAIIfCacheFails:a=!0}){let s,l,c=t.cache?.target;if(c&&c.type==="NATIVE"&&c.resolvedDescription===n&&!t.disableCache)try{s=await KS({target:c,driver:this.driver,logger:e}),l="Successfully resolved scroll to target with cache.",e.info("Successfully resolved scroll to target from cache")}catch(d){e.warn({err:d},"Failed to resolve target from cache")}if(!s&&!a)return null;if(!s)try{let d=await this.findElement({logger:e,description:n,tracer:o,metadata:{commandId:t.id}});if(d.resolvedTarget.type!=="NATIVE")return null;s=d.resolvedTarget,l=d.thoughts}catch(d){if(d instanceof C&&d.reason==="NoMatchingElementError")return null;throw e.warn({err:d},"Failed to find scroll-to target with AI"),d}return Xp({command:t,updatedCache:{...Yp(s),...i?{scrollDetails:i}:{}},updatedWithAI:!0,logger:e}),{success:!0,message:l}}async searchForElement(e,t,n,o){let i=X(),a=await this.resolveContainer({logger:e,scrollableElement:t.scrollableElement});return this.scrollAndSearch(e,t,n,i,o,a)}async scrollAndSearch(e,t,n,o,i,a){let s=0,l=a.bounds,c=l.height*Jp,u=(l.height-2*c)*i,d=!0,m=t.maxScrollAttempts??Yce;for(let h=0;h<m;h++){this.throwIfAborted();let g=this.buildScrollDetails(t,s,a.cache),y=await this.tryFindElement({logger:e,cmd:t,description:n,tracer:o,scrollDetails:g});if(y)return y;if(!d)throw new Error(`ActionFailureError: Could not find element "${n}" after scrolling to the end`);e.debug({attempt:h,cumulativePixelDelta:s},"Element not found, scrolling further");let b=Zce(t.scrollableElement);d=await this.scrollByPage({logger:e,direction:t.direction,containerBounds:l,scrollStepPercent:i,rawCoordinates:b}),s+=t.direction==="down"?u:-u}let p=this.buildScrollDetails(t,s,a.cache),f=await this.tryFindElement({logger:e,cmd:t,description:n,tracer:o,scrollDetails:p});if(f)return f;throw new Error(`ActionFailureError: Could not find element "${n}" after ${m} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollByPage({logger:e,direction:t,containerBounds:n,scrollStepPercent:o,rawCoordinates:i}){return X().startAsyncSpan("EMULATOR_INTERACTION",async s=>(s.attributes.containerBounds=n,s.attributes.direction=t,this.executeScrollGesture({logger:e,direction:t,containerBounds:n,scrollStepPercent:o,rawCoordinates:i})),{name:`Scroll ${t} by one page`})}async scrollByPixelDelta({logger:e,pixelDelta:t,scrollableElement:n,containerCache:o,direction:i,scrollStepPercent:a}){if(t===0)return;let s=X(),l,c,u;if(n.type==="CUSTOM_COORDINATES")l=n.startX,c=n.startY,u=n.deltaPixels;else{let p=(await this.resolveContainer({logger:e,scrollableElement:n,containerCache:o})).bounds,f=p.height*a,h=this.calculateSwipeCoordinates({containerBounds:p,direction:i,desiredDelta:f});l=h.startX,c=h.startY,u=h.actualDelta}let d=Math.ceil(Math.abs(t)/u);e.debug({pixelDelta:t,direction:i,scrollableElementType:n.type,startX:l,startY:c,maxScrollPerStep:u,numScrolls:d},"scrollByPixelDelta calculated parameters"),await s.startAsyncSpan("EMULATOR_INTERACTION",async m=>{m.attributes.pixelDelta=t,m.attributes.numScrolls=d,m.attributes.maxScrollPerStep=u,m.attributes.startX=l,m.attributes.startY=c;let p=0;for(let f=0;f<d;f++){this.throwIfAborted();let h=Math.abs(t)-p,g=Math.min(u,h);await this.performRawSwipe({startX:l,startY:c,deltaPixels:g,direction:this.invertDirection(i)}),p+=g}},{name:`Scroll ${i} by ${t}px`})}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n}){let o=e.left+e.width/2,i=e.height/2,a=e.height*Jp,s=Math.min(n,i-a),l=t==="down"?e.top+i+s/2:e.top+i-s/2;return{startX:o,startY:l,actualDelta:s}}invertDirection(e){return e==="up"?"down":"up"}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,l=o==="up"?t-a:t+a;await this.driver.executeInNativeContext(async c=>{let u={type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:l},{type:"pointerUp",button:0}]};await c.performActions([u]),await c.releaseActions()})}async executeScrollGesture({logger:e,direction:t,containerBounds:n,scrollStepPercent:o,diffThresholdPercent:i=Xce,rawCoordinates:a}){let s=await this.stateManager.getRawScreenshotBase64(e),l,c,u;if(a)l=a.startX,c=a.startY,u=a.deltaPixels;else{let f=n.height*o,h=this.calculateSwipeCoordinates({containerBounds:n,direction:t,desiredDelta:f});l=h.startX,c=h.startY,u=h.actualDelta}await this.performRawSwipe({startX:l,startY:c,deltaPixels:u,direction:this.invertDirection(t)});let d=await this.stateManager.getRawScreenshotBase64(e),m=es(s,d),p=m>i;return e.debug({diffPercent:m,diffThresholdPercent:i,canScrollMore:p,direction:t,actualDelta:u,rawCoordinates:a},"Scroll gesture visual diff result"),p}};function Zce(r){if(r.type==="CUSTOM_COORDINATES")return r}function Qce(r){return"iterations"in r}function eue(r){let e={relativePosition:r.relativePosition},t=r.iterations??(r.doubleTap?2:void 0),n=r.tapDelayMs??r.doubleTapDelayMs;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw new C("UserConfigurationError","iterations must be a positive integer");if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new C("UserConfigurationError","tapDelayMs must be >= 0");if(t&&t>1&&r.longPress)throw new C("UserConfigurationError","Cannot specify both more than one tap iteration and long press at the same time");if(n!==void 0&&(!t||t<2))throw new C("UserConfigurationError","tapDelayMs requires iterations >= 2");if(r.longPress){if(n!==void 0)throw new C("UserConfigurationError","tapDelayMs cannot be used with longPress");return{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}}return t!==void 0?{...e,iterations:t,tapDelayMs:n}:e}var Ju=class extends hr{async tapOnAbsoluteCoordinates(e,t){let n=t.x,o=t.y;if(e.info({x:n,y:o},"Tap at coordinates"),"longPress"in t&&t.longPress){let i=(t.longPressDurationMs??2e3)/1e3;await this.driver.executeInNativeContext(a=>a.executeScript("mobile: touchAndHold",[{x:n,y:o,duration:i}]));return}if(Qce(t)){let i=t.tapDelayMs??100;for(let a=0;a<t.iterations;a++)await this.driver.executeInNativeContext(s=>s.tap({x:n,y:o})),a<t.iterations-1&&await ee(i);return}await this.driver.executeInNativeContext(i=>i.tap({x:n,y:o}))}async tapOnTarget({logger:e,target:t,options:n}){return await X().startAsyncSpan("EMULATOR_INTERACTION",async i=>{i.attributes.options=n;let{x1:a,y1:s,x2:l,y2:c}=t.bounds,u=l-a,d=c-s,m=n?.relativePosition?.x??u/2,p=n?.relativePosition?.y??d/2;m=Math.max(0,Math.min(m,u)),p=Math.max(0,Math.min(p,d));let f=a+m,h=s+p;await this.tapOnAbsoluteCoordinates(e,{x:f,y:h,...n}),i.attributes.point={x:f,y:h}},{name:"Tap on target"})}async executeTap({logger:e,command:t}){let n=eue(t),o=X();if(t.target.type==="coordinates"){let s=await this.driver.executeInNativeContext(async u=>u.getWindowSize()),l=t.target.xPercent*s.width,c=t.target.yPercent*s.height;return await o.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates(e,{...n,x:l,y:c})},{name:`Tap at coordinates ${l}, ${c}`}),{success:!0,message:`Tapped at ${l}, ${c}`}}let i=t.target.description,{thoughts:a}=await this.wrapTargetingAction({logger:e,tracer:o,command:t,action:s=>this.tapOnTarget({logger:e,target:s,options:n}),description:i});return{success:!0,message:a}}};var Ol=25,nb=class extends hr{async doType(e,t){let n=X();if(!t.target){if(t.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForScreenshotStability({logger:e,timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(t),{success:!0,message:"Successfully executed type action"}}if(t.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:o}=await this.wrapTargetingAction({logger:e,tracer:n,command:t,action:async i=>{await this.doTypeHelper(e,t,i)},description:t.target.description});return{success:!0,message:o}}async doTypeHelper(e,t,n){let o=new Ju(this.constructPerformerParams());t.clearContent?(await o.tapOnTarget({logger:e,target:n,options:{longPress:!0}}),await this.clearContent(e)):await o.tapOnTarget({logger:e,target:n,options:{}}),await this.sendKeys(t)}async sendKeys(e){let t=X(),n=e.keyPressDelayMs??Ol;n<=0&&(n=Ol),await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){if(this.throwIfAborted(),await this.driver.executeInNativeContext(s=>s.isKeyboardShown()))return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.executeInNativeContext(async o=>{try{n!==Ol&&await o.updateSettings({maxTypingFrequency:1e3/n}),await o.performActions(tue(e.text)),await o.releaseActions()}finally{n!==Ol&&await o.updateSettings({maxTypingFrequency:1e3/Ol})}})},{name:`Typing "${e.text}"${n?` with a ${n}ms delay`:""}`})}async clearContent(e){let t=X();try{await t.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(n){e.warn({err:n},"Failed to find select all button, continuing...")}}async clearContentHelper(){await this.driver.executeInNativeContext(async e=>{let t=e.$('-ios predicate string:label == "Select All"');await t.waitForExist({timeout:750}),await t.click()}),await this.driver.executeInNativeContext(async e=>{await e.keys(["\uE003"])})}};function tue(r){let e={type:"key",id:"pressKeys",actions:[]};for(let t of[...r])e.actions.push({type:"keyDown",value:t},{type:"keyUp",value:t});return[e]}async function sG({command:r,abortSignal:e}){return await ee(r.timeoutSecs*1e3,e),{success:!0}}async function rue(r,e){try{await r.executeInNativeContext(t=>t.executeScript("mobile: pressButton",[{name:"home"}])),e.info("Navigated to home screen")}catch(t){e.warn({err:t},"Failed to press home button")}}var uR=["io.appium."],dR=["com.facebook.WebDriverAgentRunner.xctrunner"];async function nue(r,e){let t;try{t=await r.listApps()}catch(a){e.warn({err:a},"Failed to list installed apps");return}let n=t.filter(({bundleId:a})=>!dR.includes(a)&&!uR.some(s=>a.startsWith(s)));e.info({count:n.length},"Terminating all apps");let i=(await Promise.allSettled(n.map(async a=>{try{return await r.terminateApp(a.bundleId),a.bundleId}catch(s){return e.debug({err:s,bundleId:a.bundleId},"Failed to terminate app (may not be running)"),null}}))).filter(a=>a.status==="fulfilled"&&a.value!==null).length;i>0&&e.info({count:i},"Terminated apps")}async function oue(r,e){e.info("Resetting privacy settings for all apps");try{let t=await r.simctl(["privacy","booted","reset","all"]).wait();t.code!==0&&e.warn({stderr:t.stderr,exitCode:t.code},"simctl privacy reset returned non-zero exit code")}catch(t){e.warn({err:t},"Failed to reset privacy settings")}}async function lG(r){let{limbarClient:e,driver:t,logger:n}=r;await rue(t,n),await nue(e,n),await oue(e,n)}var Zu=class r extends hr{emulatorSettings;logger;splitInstalledApps(e){let t=[],n=[];for(let{bundleId:o}of e)if(!(dR.includes(o)||uR.some(i=>o.startsWith(i)))){if(o.startsWith("com.apple.")){n.push(o);continue}t.push(o)}return{installedApps:t,prunedApps:n}}constructor(e){super(e),this.logger=e.logger,this.emulatorSettings=e.emulatorSettings}static async init({driver:e,logger:t,fixtures:n,orgId:o,options:i,abortController:a,limbarClient:s,generator:l,aiSettings:c}){let u={controller:a},d=i?.emulator??{},m=await VS.init({driver:e,orgId:o,limbarClient:s,options:d,aborter:u}),p=new r({generator:l,aiSettings:c,limbarClient:s,driver:e,stateManager:m,logger:t,fixtures:n,aborter:u,orgId:o,emulatorSettings:d});return await p.initializeSettings(),p}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Iu({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Ou(e.command,n)}}async executeCommandHelper({command:e}){switch(e.type){case"TAP":return new Ju(this.constructPerformerParams()).executeTap({logger:this.logger,command:e});case"SWIPE":return new Xu(this.constructPerformerParams()).executeSwipe({logger:this.logger,command:e});case"DRAG_AND_DROP":return new YS(this.constructPerformerParams()).executeDragAndDrop({logger:this.logger,command:e});case"SCROLL_TO":return new rb(this.constructPerformerParams()).executeScrollTo({logger:this.logger,command:e});case"TYPE":return new nb(this.constructPerformerParams()).doType(this.logger,e);case"STATE":{let t=await this.stateManager.getDomState(this.logger),n=await this.stateManager.getContexts();return{output:{xml:t.graph.xml,contexts:n},success:!0}}case"OPEN_APP":{let t=[];if(e.intentExtras)try{let n=JSON.parse(e.intentExtras);t=iue.string().array().parse(n)}catch(n){throw new C("UserConfigurationError",`Invalid launch arguments: expected a JSON array of strings. ${n instanceof Error?n.message:`${n}`}`)}return await this.driver.executeInNativeContext(n=>n.execute("mobile: launchApp",{bundleId:e.packageName,arguments:t})),{success:!0}}case"KILL_APP":return new eb(this.constructPerformerParams()).execute();case"PRESS":{let t=new Yu(this.constructPerformerParams());switch(e.key){case"HOME":await t.doPress({name:"home"});break;case"POWER":await this.driver.executeInNativeContext(n=>n.isLocked())?await this.driver.executeInNativeContext(n=>n.unlock()):await this.driver.executeInNativeContext(n=>n.lock());break}return{success:!0}}case"PRESS_KEYBOARD":return tG({command:e,driver:this.driver});case"AI_CHECK":return Kj({command:e,logger:this.logger,generator:this.generator,aiSettings:this.aiSettings,getEmulatorDomState:()=>this.getEmulatorDomState(),getScreenshotBase64:()=>this.getScreenshotBase64(),throwIfAborted:()=>this.throwIfAborted(),abortSignal:this.abortSignal});case"AI_EXTRACT":return Yj({command:e,logger:this.logger,generator:this.generator,aiSettings:this.aiSettings,getEmulatorDomState:()=>this.getEmulatorDomState(),getScreenshotBase64:()=>this.getScreenshotBase64(),abortSignal:this.abortSignal});case"JAVASCRIPT":return eG({command:e,orgId:this.orgId,logger:this.logger,fixtures:this.fixtures,abortSignal:this.abortSignal});case"WAIT":return sG({command:e,abortSignal:this.aborter.controller?.signal});case"REQUEST":return nG({command:e,logger:this.logger});case"ROTATE_ORIENTATION":return oG({command:e,limbarClient:this.limbarClient,getViewportBounds:()=>this.getViewportBounds()});case"ADD_FILE":{let t=await rS(e.file);return await this.driver.executeInNativeContext(n=>n.pushFile(e.storageLocation,t)),{success:!0}}case"SCREEN_CHECK":return new tb(this.constructPerformerParams()).executeScreenCheck(this.logger,e);case"ELEMENT_CHECK":return new ZS(this.constructPerformerParams()).executeElementCheck({logger:this.logger,command:e});default:{let t=e;throw new Error(`Unsupported mobile command type: ${t}`)}}}async getMobileFailureRecoveryPlan(e){return{thoughts:"Failure recovery is not yet supported for iOS.",scenario:"INELIGIBLE",instructions:void 0}}async waitForPageSourceStability(e){return this.stateManager.waitForPageSourceStability({logger:this.logger,timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}async getInstalledApps(){let e=await this.limbarClient.listApps();return this.splitInstalledApps(e)}async initializeSettings(){let{latitude:e,longitude:t}=this.emulatorSettings?.geolocation??vc;await this.driver.executeInNativeContext(async n=>{await n.setGeoLocation({latitude:e,longitude:t}),await n.updateSettings({maxTypingFrequency:1e3/Ol})})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64(this.logger)}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString(this.logger)}async getEmulatorDomState(){return(await this.stateManager.getDomState(this.logger)).graph.xml}async getViewportBounds(){return this.stateManager.getViewportBounds()}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({logger:this.logger,timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async softReset(){await lG({limbarClient:this.limbarClient,driver:this.driver,logger:this.logger}),this.fixtures.testContext.resetToInitial()}async cleanup(){}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};import aue from"path";async function cG({socket:r,logger:e,orgId:t,testMetadata:n,globalOrgSettings:o,iosDriverFactory:i,mobileGeneratorFactory:a,browserGeneratorFactory:s,browserEnricherFactory:l,storageFactory:c,localToolsFactory:u,globalStateManager:d,getGitMetadata:m}){let p=r.id,f=await m(),h=r.handshake.query?.fileName,g=h?aue.basename(h,".test.yaml"):"",y=n.id,b=n.settings?.defaultChannel,E=n.settings?.defaultTag;e=e.child({sessionId:p,testId:y,orgId:t,branch:f.gitBranchName});let v=await c(t),w=n.settings?.defaultEnv,L={};w&&(L=(await v.fetchEnvironment(w,e))?.variables??{});let I={...o.emulator,...n.settings?.emulator},A=d.getSession(p);if(A){if(e.info("Reconnecting to existing iOS session"),A.local)return r.emit("session",A.metadata),A.softDeleted=!1,A.metadata;throw new Error("Restoring existing remote emulator sessions is not supported. Please reconnect to a new emulator.")}if(I.region==="local")throw new Error("Local region is not supported for iOS tests, as we do not support local iOS emulators.");let _={region:I.region,appToInstall:b?{channel:b,tag:E}:void 0},O=Date.now(),{driver:k,cleanup:D,emulatorName:j,limbarClient:$,limbarWebRtcUrl:xe,limbarToken:B,limbarRegion:Z}=await i({socket:r,logger:e,creationOpts:_});e.info({duration:Date.now()-O,emulatorName:j},"iOS emulator session initiated"),e=e.child({emulator:j});let ie=await a(t,e),se=await s(t,e),Pe=await l(t,e),we=u?await u(t):void 0,he=new io({variablesFromEnvironment:L,envName:w,testName:g}),Ie=await Zu.init({driver:k,generator:ie,logger:e,limbarClient:$,aiSettings:{...o.ai,useMemory:o.ai?.useMemory!==!1,...n.settings?.ai},options:{emulator:{...I,browserSettings:o.browser}},fixtures:{storage:v,browserEnricher:Pe,browserGenerator:se,localCodeEvalTools:we,testContext:he},orgId:t,abortController:new AbortController}),Ot=await Ie.getViewportBounds();if(!r.connected)throw await Ie.cleanup(),await D(),new Error("Socket not connected anymore, not proceeding with iOS session setup");let ke=sue({socket:r,testContext:he}),M=async()=>{clearInterval(ke);try{await Ie.cleanup()}catch(ye){e.warn({err:ye},"Failed to clean up controller in socket server")}try{await D()}catch(ye){e.warn({err:ye},"Failed to clean up emulator in socket server")}},me={sessionId:p,testId:y,orgId:t,emulatorName:j,testName:g,limbarUrl:xe,limbarToken:B,limbarRegion:Z,viewportBounds:Ot,envName:w};return d.registerSession(p,{platform:"IOS",controller:Ie,cleanup:M,emulatorName:j,local:!1,metadata:me}),r.emit("session",me),me}function sue({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}var ob=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async clearSoftDeletedLocalSessions(e){for(let t of this.sessions.values())t.softDeleted===!0&&t.local===!0&&await this.removeSession(t.metadata.sessionId,e)}hasActiveLocalSession(){for(let e of this.sessions.values())if(e.local===!0)return!0;return!1}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up by removeSession")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};function uG(r){let{logger:e,baseServer:t,globalStateManager:n,settingsFactory:o,getOrgId:i}=r,a=new lue(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0,connectionStateRecovery:{maxDisconnectionDuration:60*60*1e3,skipMiddlewares:!0}}),s=async()=>{await n.removeAllSessions(e)};a.on("connection",async c=>{let u=c.id,d=e.child({sessionId:u});d.info({event:"connection",transport:c.conn.transport.name},"Mobile websocket connection initiated"),c.on("disconnect",async f=>{if(e.info({reason:f},"Disconnect received"),f.includes("namespace disconnect")){await _j({socket:c,globalStateManager:n,logger:d,authorization:r.authorization});return}let h=n.getSession(u);h&&(h.softDeleted=!0)});let m,p;try{let f=c.handshake.query?.testMetadata,h=Ma.parse(JSON.parse(f??"")),g=h.id,y=await i({testId:g});switch(p=await o(y,e),h.platform){case"ANDROID":m=await xj({...r,orgId:y,socket:c,globalStateManager:n,logger:d,globalOrgSettings:p,testMetadata:h});break;case"IOS":m=await cG({...r,orgId:y,socket:c,globalStateManager:n,logger:d,globalOrgSettings:p,testMetadata:h});break;default:throw new Error("Unsupported platform")}}catch(f){d.error({err:f},"Failed to setup mobile connection"),c.emit("error",{message:f instanceof Error?f.message:JSON.stringify(f)}),c.disconnect(!0);return}Lj.forEach(f=>l(f,{...r,socket:c,metadata:m,globalOrgSettings:p,logger:d}))});let l=(c,u)=>{let d=c.createHandler(u),m=(...p)=>{c.event!=="keepalive"&&u.logger.debug({event:c.event},`Websocket event (${c.event})`);let f=h=>{u.logger.error({event:c.event,err:h instanceof Error?h:new Error(`${h}`)},"Unhandled exception in socket handler"),u.socket.emit("error",{message:h instanceof Error?h.message:typeof h=="string"?h:JSON.stringify(h)})};try{let h=d.apply(this,p);h&&typeof h.catch=="function"&&h.catch(f)}catch(h){f(h)}};u.socket.on(c.event,m)};return{server:a,dispose:s}}import cue from"adm-zip";import dG from"crypto";import uue from"fs";async function due(r,e){switch(r){case"ANDROID":return uue.promises.readFile(e);case"IOS":{let t=new cue;t.addLocalFolder(e,void 0,n=>n!==".DS_Store");for(let n of t.getEntries()){let o=n.isDirectory?16877:33188;n.attr=(o<<16|n.attr&65535)>>>0,n.header.made=768|n.header.made&255}return t.toBuffer()}}}async function ib({tag:r,channel:e,filePath:t,apiClient:n,logger:o,platform:i}){let a=await due(i,t),s=dG.createHash("md5").update(a).digest("base64"),l=dG.createHash("md5").update(a).digest("hex"),c=await n.generateAssetUploadUrl({channel:e,tag:r??"latest",md5:s,platform:i});if(c.md5&&(c.md5===s||c.md5===l)){o.info({channel:e,tag:r,md5:s,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:s,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let u=await fetch(c.uploadUrl,{headers:{"Content-Length":a.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:a});if(u.status!==200)throw new C("InternalPlatformError",`Got error response from emulator platform: ${u.status} ${await u.text()}`);o.info({channel:e,tag:r,md5:s},`Asset ${t} was uploaded successfully!`);return}catch(u){try{await n.deleteAsset(e,r??"latest",i)}catch(d){o.warn({err:d,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:u},"Failed to upload asset"),u}}throw new C("InternalPlatformError",`No upload URL was given for asset ${t}`)}import zK from"body-parser";import wbe from"cors";import Cbe from"dedent";import{Router as yue}from"express";import ab from"fs";import mue from"path";var pue=new my(30,60*1e3),hR="https://api.momentic.ai",pR,mG,lb=r=>{hR=r},Zp=()=>hR;var cb=r=>{mG=r},ed=()=>mG,nr=()=>pR;var Qu,fR,sb,ub=async r=>{if(pR&&Qu&&sb)return Qu;let e=new Or({baseUrl:hR,apiKey:r,logger:P});pR=e;try{let t=await e.getAuthInfo();return Qu=t.orgId,fR=t.userId,sb=r,Qu}catch(t){throw new Error(`Error checking API key against server: ${t}`,{cause:t})}},Xr=()=>{if(!Qu)throw new Error("Your organization ID is invalid.");return Qu},td=()=>{if(!fR)throw new Error("Your user ID is invalid.");return fR},pG=()=>{if(!sb)throw new Error("Your API key is invalid.");return sb},gR,mR,db=(r,e)=>{gR=r,mR?.abort(),mR=new AbortController;let t=mR.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=mue.resolve(r.rootDir,o.envFile);try{if(ab.lstatSync(i).isSymbolicLink())return;ab.existsSync(i)&&n.push(i)}catch(a){P.warn({err:a},`Failed to check if env file ${i} exists`)}});try{fue({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){P.error({err:o},"Failed to start config file watchers")}},st=()=>gR;function fue({filesToWatch:r,revalidator:e,signal:t,project:n}){P.debug("Starting watch on the following files:"),r.forEach(o=>{P.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,l)=>{s.mtime.getTime()!==l.mtime.getTime()&&(pue.increment("setLocalProject")&&P.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),gR=await Promise.resolve(e(n.configFilePath)))};ab.watchFile(o,{persistent:!1},i);let a=()=>{ab.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ye(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}import{hostname as hue}from"os";var gue="0.59.1",Nl=Zc({app:"desktop-server",hostname:hue(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:gue});(async()=>{try{let r=await Cp(Nl);r.gitBranchName&&Nl.addBinding("branch",r.gitBranchName)}catch{}})();var fG=yue();fG.get("/",async(r,e)=>{let t=st(),n=nr();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Wr(Nl,n,t),i=o?.gitProtectedBranches&&o?.gitBranchName&&o.gitProtectedBranches.includes(o.gitBranchName),{noCache:a,alwaysSaveCache:s}=ed(),l=!a&&(s||!i);e.status(200).json({saveCaches:l,checkedOutBranch:o?.gitBranchName})});var yR=fG;import{Router as Sue}from"express";import Jr from"fs";import{glob as bue}from"glob";import Rr from"path";var Eue=5e3;function SR(r={}){let e=Sue();function t(i){let a=st(),s=Rr.dirname(a.configFilePath);return Rr.join(s,...i)}function n(i){let a=st(),s=Rr.dirname(a.configFilePath),l=Rr.relative(s,i);return l?l.split(Rr.sep):[]}function o(i,a){let s=Jr.statSync(i),l=n(i);return kv.parse({name:a,absolutePath:i,relativePath:l.join(Rr.sep),pathSegments:l,isDirectory:s.isDirectory(),size:s.size,createdAt:s.birthtime,modifiedAt:s.mtime,accessedAt:s.atime})}return e.post("/",Ye(async(i,a,s)=>{let l;try{l=GN.parse(i.body).pathSegments}catch(y){a.status(400).json({error:`Failed to parse folder read body: ${y}`});return}let c=t(l);if(!Jr.existsSync(c)){a.status(404).json({error:`Path not found: ${l.join(Rr.sep)}`});return}if(!Jr.statSync(c).isDirectory()){a.status(400).json({error:`Path is not a directory: ${l.join(Rr.sep)}`});return}let d=st(),m=Array.from(d.config.exclude??[]).concat(Yh),p=AbortSignal.timeout(Eue),f;try{f=await bue("*",{absolute:!1,cwd:c,ignore:m,dotRelative:!1,maxDepth:1,nodir:!1,signal:p})}catch(y){if(y instanceof Error&&y.name==="TimeoutError"){a.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw y}let h=f.map(y=>{let b=Rr.join(c,y);return o(b,y)});if(r.allowedFileTypes){let y=new Set(r.allowedFileTypes);h=(await Promise.all(h.map(async b=>{if(b.isDirectory||!(b.name.endsWith(".test.yaml")||b.name.endsWith(".module.yaml")))return b;let v=await Tue(b.absolutePath);return v!==void 0&&y.has(v)?b:null}))).filter(b=>b!==null)}let g={absolutePath:c,pathSegments:l,contents:h};a.status(200).json(g)})),e.put("/",Ye(async(i,a,s)=>{let l;try{l=WN.parse(i.body).pathSegments}catch(d){a.status(400).json({error:`Failed to parse folder create body: ${d}`});return}let c=t(l);if(Jr.existsSync(c)){a.status(200).json({success:!0,message:`Folder already exists: ${l.join(Rr.sep)}`,pathSegments:l});return}Jr.mkdirSync(c,{recursive:!0});let u={success:!0,message:`Folder created: ${l.join(Rr.sep)}`,pathSegments:l};a.status(201).json(u)})),e.patch("/",Ye(async(i,a,s)=>{let l,c;try{let f=VN.parse(i.body);l=f.pathSegments,c=f.newPathSegments}catch(f){a.status(400).json({error:`Failed to parse folder update body: ${f}`});return}let u=t(l),d=t(c);if(!Jr.existsSync(u)){a.status(400).json({error:`Folder not found: ${l.join(Rr.sep)}`});return}if(Jr.existsSync(d)){a.status(400).json({error:`Destination already exists: ${c.join(Rr.sep)}`});return}let m=Rr.dirname(d);Jr.existsSync(m)||Jr.mkdirSync(m,{recursive:!0}),Jr.renameSync(u,d);let p={success:!0,message:`Folder moved from ${l.join(Rr.sep)} to ${c.join(Rr.sep)}`,pathSegments:c};a.status(200).json(p)})),e.delete("/",Ye(async(i,a,s)=>{let l,c=!0;try{let p=qN.parse(i.body);l=p.pathSegments,c=p.recursive??!0}catch(p){a.status(400).json({error:`Failed to parse folder delete body: ${p}`});return}let u=t(l);if(!Jr.existsSync(u)){a.status(200).json({success:!0,message:`Folder not found: ${l.join(Rr.sep)}`,pathSegments:l});return}if(!Jr.statSync(u).isDirectory()){a.status(400).json({error:`Path is not a directory: ${l.join(Rr.sep)}`});return}if(c)Jr.rmSync(u,{recursive:!0,force:!0});else{if(Jr.readdirSync(u).length>0){a.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${l.join("/")}`});return}Jr.rmdirSync(u)}let m={success:!0,message:`Folder deleted: ${l.join("/")}`,pathSegments:l};a.status(200).json(m)})),e}async function Tue(r){try{let e=await Jr.promises.open(r,"r");try{let t=Buffer.alloc(4096),{bytesRead:n}=await e.read(t,0,t.length,0);return t.toString("utf-8",0,n).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await e.close()}}catch{}}import{Router as vue}from"express";var hG=vue();hG.get("/",async(r,e)=>{let t=st(),n=nr();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Wr(Nl,n,t);e.status(200).json(o)});var bR=hG;import Rbe from"events";import $K,{Router as xbe}from"express";import _be from"http";import Mbe from"path";var mb=new ob;import{Router as wue}from"express";import{existsSync as Cue,statSync as Rue}from"fs";import xue from"path";import{hostname as Aue}from"os";var ER="0.59.1",Tt=Zc({app:"mobile-desktop-server",hostname:Aue(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:ER});(async()=>{try{let r=await Cp(Tt);r.gitBranchName&&Tt.addBinding("branch",r.gitBranchName)}catch{}})();var TR=wue();TR.get("/",Ye(async(r,e)=>{let t=nr();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getMobileAssets();e.status(200).json(n)}));TR.post("/upload-url",Ye(async(r,e)=>{let t;try{t=nL.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}let n=nr();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=xue.resolve(t.filePath);if(!Cue(o)){e.status(400).json({error:`File not found: ${o}`});return}let i=/\.apk$/i.test(o),a=o.endsWith(".app")&&Rue(o).isDirectory();if(!i&&!a){e.status(400).json({error:"Unsupported file type. Only .apk files and .app directories are supported."});return}await ib({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Tt,platform:i?"ANDROID":"IOS"}),e.sendStatus(204)}));var gG=TR;import{Router as Pue}from"express";import{Router as _ue}from"express";import yG from"fs";import Mue from"path";var rd=_ue();async function pb(r){return(await QU(r,Tt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){P.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}rd.get("/",Ye(async(r,e)=>{let t=st(),n=await xt(t),o=await pb(n);e.status(200).json(o)}));rd.get("/tests-join",Ye(async(r,e)=>{let t=st(),n=await xt(t),o=await pb(n),i={};for(let s of o)i[s.id]={...s,tests:[]};let a=await Promise.all(Object.values(n.mobileTests).map(async s=>({id:s.id,name:s.name,relativePath:s.relativePath,test:await Er(s.fullFilePath,Tt,n)})));for(let{id:s,name:l,relativePath:c,test:u}of a){let d=new Set;Ga({steps:u.steps,onPreset:()=>!1,onModule:m=>(d.add(m.moduleId),!1)});for(let m of d){let p=i[m];p&&p.tests.push({id:s,name:l,relativePath:c})}}e.status(200).json(i)}));rd.get("/:moduleId",Ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await xt(st()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await hl(n,t,P);e.json(o)}catch(o){e.status(400).json({err:o})}}));rd.patch("/:moduleId/metadata",Ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=iL.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=st(),o=await xt(n);ZU({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:P,project:n}),e.status(201).json({message:"ok"})}));rd.post("/",Ye(async(r,e)=>{let t;try{t=sL.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{eo(t.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=st(),i=(await xt(n)).mobileModules;if(Object.values(i).find(s=>s.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=Mue.join(n.rootDir,t.folderPath??"");if(!yG.existsSync(a)||!yG.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}switch(t.platform){case"ANDROID":{let s=await _p({...t,folder:a,project:n});e.status(201).json(s);return}case"IOS":{let s=await _p({...t,folder:a,project:n});e.status(201).json(s);return}}}));var SG=rd;var bG=Pue();bG.get("/",Ye(async(r,e)=>{let t=st(),n=await xt(t),o=await pb(n),i=new Set;n?.mobileTests&&Object.values(n.mobileTests).forEach(c=>{c.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),l={labels:a,modules:o,tests:s};e.status(200).json(l)}));var EG=bG;import{Router as Iue}from"express";var fb=Iue();fb.get("/",Ye((r,e)=>{let t=Ry(st(),Tt);e.status(200).json(t)}));fb.get("/names",Ye((r,e)=>{let n=st().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));fb.post("/",Ye((r,e)=>{let t;try{t=oL.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{eo(t.name)}catch(s){e.status(400).json({error:`Invalid environment name: ${s}`});return}let n=st();if(n.config.environments?.find(s=>s.name===t.name)){e.status(400).json({error:`An environment with the name "${t.name}" already exists. Please choose a different name.`});return}let i={...n.config,environments:[...n.config.environments??[],{name:t.name}]};n.config=i,My(i,n.configFilePath);let a=pl(t.name,n,Tt);e.status(201).json(a)}));var TG=fb;import{Router as Oue}from"express";var vG=Oue();vG.get("/",(r,e)=>{e.status(200).json({userId:td(),orgId:Xr(),cliVersion:ER??"0.0.0"})});var AG=vG;import{Router as Nue}from"express";var wG=Nue();wG.get("/",Ye(async(r,e)=>{let t=r.query.sessionId;if(!t){e.status(400).json({packages:[]});return}let n=mb.getSession(t);if(!n?.controller){e.status(200).json({packages:[]});return}try{let o=n.controller,{installedApps:i}=await o.getInstalledApps();e.status(200).json({packages:i})}catch(o){Tt.error({err:o},"Error fetching installed packages from the session controller"),e.status(200).json({packages:[]})}}));var CG=wG;import{Router as Lue}from"express";var vR=Lue(),Due=async({platform:r,steps:e,cacheStorage:t,stepId:n,parentStepIdChain:o,testId:i,environment:a})=>{let{result:s}=Su(e,n,o);if(s)return await t.getCacheKeyForStep({platform:r,logger:Tt,testId:i,environment:a,parentStepIdChain:o,step:s})};vR.patch("/",Ye(async(r,e)=>{let t=st(),n=Xr(),o=nr();if(!o){e.status(500).json({error:"API client not initialized"});return}let i;try{i=uL.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let a=await Wr(Tt,o,t),s=yo({logger:Tt,orgId:n,client:o,gitMetadata:a,regenerateCache:!1,noCache:!1,alwaysSaveCache:!1,isolateCachesByEnvironment:t.config?.advanced?.isolateCachesByEnvironment}),l=await Due({cacheStorage:s,platform:i.platform,steps:i.steps,stepId:i.stepId,parentStepIdChain:i.parentStepIdChain,testId:i.testId,environment:i.environment});if(!l){e.status(400).json({error:"Cache-supporting step not found"});return}await o.updateMobileStepCaches({platform:i.platform,body:{entries:[{key:l,organizationId:n,value:i.value,testId:i.testId,environment:i.environment}]},headers:$m(a)}),e.status(204).send()}));vR.post("/traces",Ye(async(r,e)=>{let t=nr();if(!t){e.status(500).json({error:"API client not initialized"});return}let n;try{n=dL.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o=await t.getMobileStepCacheMemoryTraces(n.platform,n);e.status(200).json(o)}));var RG=vR;import{Router as kue}from"express";import AR from"fs";import ls from"path";import{v4 as Fue}from"uuid";import Uue from"yaml";var nd=kue();nd.patch("/:testPath",Ye(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=tL.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}if(n.steps===void 0&&n.settings===void 0&&n.labels===void 0){e.status(400).json({error:"At least one of steps, settings, or labels is required"});return}let o=st(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await xt(o);await wu({platform:n.platform,filePath:i,steps:n.steps,settings:n.settings,labels:n.labels,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:vn});let s={message:"ok"};e.status(200).json(s)}));nd.post("/",Ye((r,e)=>{let t;try{t=QN.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}let{name:n,description:o,settings:i,pathSegments:a,platform:s}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{eo(n)}catch(h){e.status(400).json({error:h.message});return}let l=st(),c=ls.join(l.rootDir,...a??[]),{fullPath:u,testId:d}=Ny({name:n,description:o,settings:i,folder:c,platform:s}),m=ls.basename(u),p=ls.relative(l.rootDir,u),f={id:d,fileName:m,fullPath:u,relativeFilePath:p};e.status(201).json(f)}));nd.get("/:fileName",Ye(async(r,e)=>{let t=nr(),n=Xr(),o=r.params.fileName;if(!o){e.status(400).json({error:"Missing fileName in path"});return}if(!t){e.status(500).json({error:"API client not initialized"});return}let i=o.endsWith(".test.yaml")?o:`${o}.test.yaml`,a=ls.basename(i).replace(".test.yaml",""),s=st(),l=await xt(s),[c,u]=await Promise.all([Er(i,Tt,l),Wr(Tt,t,s,{includeHostingUsername:!1})]);await yo({logger:Tt,orgId:n,client:t,gitMetadata:u,regenerateCache:!1,noCache:!1,alwaysSaveCache:!1,isolateCachesByEnvironment:s.config?.advanced?.isolateCachesByEnvironment}).resolveEntries({logger:Tt,platform:c.platform,testId:c.id,environment:c.settings?.defaultEnv,stepLists:{steps:c.steps}});let m={...c,name:a};e.status(200).json(m)}));nd.patch("/:testPath/metadata",Ye(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=rL.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}let o=st(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,s={message:"ok",newRelativeTestPath:eB(i,n,o).newRelativeTestPath};e.status(200).json(s)}));nd.post("/:testPath/duplicate",Ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=lL.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{eo(n.name)}catch(h){e.status(400).json({error:h.message});return}let o=st(),i=ls.join(o.rootDir,t);if(!AR.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=await xt(o),s;try{s=await Er(i,Tt,a)}catch(h){e.status(400).json({error:h.message});return}let l=Fue(),{stepsToSave:c}=await _n({...s,createNewCacheIds:!0}),u=ra({fileType:pt.MOBILE_TEST,id:l,schemaVersion:vn,description:s.description,platform:s.platform,settings:s.settings,labels:s.labels,steps:c});RN.parse(u);let d=ls.dirname(i),m=ls.join(d,`${n.name}.test.yaml`);if(AR.existsSync(m)){e.status(409).send("A test with this name already exists");return}let p=Uue.stringify(u);AR.writeFileSync(m,p,"utf-8");let f={relativeFilePath:ls.relative(o.rootDir,m)};e.status(201).json(f)}));var xG=nd;import{Router as Bue}from"express";var _G=Bue();_G.get("/",Ye((r,e)=>{let t=st(),n={ai:t.config.ai,displayRoot:t.config.displayRoot};e.status(200).json(n)}));var MG=_G;import{Router as zue}from"express";var PG=zue();PG.post("/traces",Ye(async(r,e)=>{let t=nr();if(!t){e.status(500).json({error:"API client not initialized"});return}let n;try{n=mL.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o=await t.getWebStepCacheMemoryTraces(n);e.status(200).json(o)}));var IG=PG;var od=class extends xu{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=st();return pl(t,o,P)}};import{randomUUID as vbe}from"crypto";import{existsSync as DG,mkdirSync as $ue}from"fs";import{readdir as Hue,stat as jue,unlink as Gue,writeFile as Wue}from"fs/promises";import Qp from"path";import wR from"path";function vt({text:r,section:e}){if(!e)return[{type:"text",text:r}];let t=`### ${e}`;return r.length===0?[{type:"text",text:t}]:[{type:"text",text:`${t}
4894
4894
  ${r}`}]}function CR({imageDataUri:r,mediaType:e,section:t}){return t?[{type:"text",text:`### ${t}`},{type:"media",data:r,mediaType:e}]:[{type:"media",data:r,mediaType:e}]}function id(r){if(r.length===0)throw new ln("No content parts provided to construct the tool response content.");return{type:"content",value:r}}function OG({projectRoot:r,filePath:e,pathLabel:t="path"}){if(!e||!wR.isAbsolute(e))return e;let n=wR.relative(r,e);if(n.startsWith("..")||wR.isAbsolute(n))throw new Error(`Error: ${t} "${e}" must be inside project root "${r}".`);return n}function NG(r){return r.map(e=>{switch(e.type){case"text":return e;case"media":return{type:"image",data:e.data,mimeType:e.mediaType};default:return(n=>{throw new Error("Unhandled content part")})(e)}})}var LG=".momentic-mcp",Vue=30*24*60*60*1e3;function RR(r){return r?Qp.join(r,LG):Qp.resolve(LG)}function Ll(r){let e=RR(r);DG(e)||$ue(e,{recursive:!0})}function que(){return`${Date.now()}`}function Dl({rootDir:r,entity:e,ext:t}){return Qp.join(RR(r),`${e}-${que()}.${t}`)}function Kue(r){let e=Qp.relative(process.cwd(),r);return e.startsWith(".")?e:`./${e}`}function kl({filePath:r,title:e}){return`- [${e}](${Kue(r)})`}async function kG({artifacts:r,rootDir:e,supportsFileOutput:t}){let n=Object.assign({},...r.map(i=>i.payload)),o=JSON.stringify(n,null,2);if(t){Ll(e);let i=await Promise.all(r.map(async({title:a,entity:s,payload:l})=>{let c=Dl({rootDir:e,entity:s,ext:"json"});return await Wue(c,JSON.stringify(l,null,2),"utf8"),{title:a,filePath:c}}));return vt({text:i.map(({title:a,filePath:s})=>kl({filePath:s,title:a})).join(`
4895
4895
  `),section:"Artifacts Lists"})}return[{type:"text",text:`### Artifacts Lists Json:
4896
- ${o}`}]}async function FG({rootDir:r,cutoffTime:e}){let t=await Hue(r,{withFileTypes:!0});for(let n of t){let o=Qp.join(r,n.name);if(n.isDirectory()){await FG({rootDir:o,cutoffTime:e});continue}if(!n.isFile())continue;(await jue(o)).mtimeMs<e&&await Gue(o)}}async function UG(r){let e=RR(r);DG(e)&&await FG({rootDir:e,cutoffTime:Date.now()-Vue})}import{z as Yue}from"zod";var hb=class{isError;content=[];addPartFromText(e){this.addContent({type:"text",text:e})}addError(e){this.addPartFromText(`Error: ${e}`),this.isError=!0}addContent(e){this.content.push(e)}addContentParts(e){this.content.push(...NG(e))}async serialize(){return{content:this.content,isError:this.isError}}};function BG(r,e){let t=JSON.stringify(r);return t?t.length<=e?t:`${t.slice(0,e)}...`:""}function Lr(r){return{addToolToMcpServer:(t,n)=>{let o=Yue.object(r.schema.inputSchema),i=async(a,s)=>{let l=s.sessionId??t.sessionId??t.serverId,c=t.logger.child({sessionId:l,toolName:r.schema.name}),u=Date.now();c.debug({params:BG(a,500),sessionId:l,toolName:r.schema.name},`MCP tool invoked: ${r.schema.name}`);let d=new hb,m;try{await r.handle({...t,sessionId:l},a,d,s)}catch(h){m=h instanceof Error?h:new Error(Le(h)),d.addError(Le(h))}let p=Date.now()-u,f=await d.serialize();if(m)c.error({duration:p,err:m,sessionId:l,toolName:r.schema.name},`MCP tool failed: ${r.schema.name}`);else{let h=f.content.filter(g=>g.type==="text");c.debug({duration:p,response:BG(h,500),responseIsError:f.isError,sessionId:l,toolName:r.schema.name},`MCP tool completed: ${r.schema.name}`)}return f};n.registerTool(r.schema.name,{title:r.schema.name,description:r.schema.description,inputSchema:o},i)},name:r.schema.name,tool:r}}function xR(r){return r?._meta?.progressToken!==void 0}async function zG(r,e,t,n,o,i){if(!xR(r))return!1;try{await r.sendNotification({method:"notifications/progress",params:{progressToken:r._meta.progressToken,progress:e.completed,total:e.total,...t?{message:t}:{}}})}catch(a){n.error({err:a},"Failed to send progress notification"),o.abort(a),i.addError(`Failed to send progress notification: ${Le(a)}`)}return!0}function _R(r,e,t,n){if(r!==t||e.length!==n.length)return!1;for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}import*as $G from"zod/v3";import*as Fl from"zod/v4-mini";function Ao(r){return!!r._zod}function Ul(r){let e=Object.values(r);if(e.length===0)return Fl.object({});let t=e.every(Ao),n=e.every(o=>!Ao(o));if(t)return Fl.object(r);if(n)return $G.object(r);throw new Error("Mixed Zod versions detected in object shape.")}function cs(r,e){return Ao(r)?Fl.safeParse(r,e):r.safeParse(e)}async function gb(r,e){return Ao(r)?await Fl.safeParseAsync(r,e):await r.safeParseAsync(e)}function us(r){if(!r)return;let e;if(Ao(r)?e=r._zod?.def?.shape:e=r.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function ad(r){if(r){if(typeof r=="object"){let e=r,t=r;if(!e._def&&!t._zod){let n=Object.values(r);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Ul(r)}}if(Ao(r)){let t=r._zod?.def;if(t&&(t.type==="object"||t.shape!==void 0))return r}else if(r.shape!==void 0)return r}}function yb(r){if(r&&typeof r=="object"){if("message"in r&&typeof r.message=="string")return r.message;if("issues"in r&&Array.isArray(r.issues)&&r.issues.length>0){let e=r.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(r)}catch{return String(r)}}return String(r)}function HG(r){return r.description}function jG(r){if(Ao(r))return r._zod?.def?.type==="optional";let e=r;return typeof r.isOptional=="function"?r.isOptional():e._def?.typeName==="ZodOptional"}function Sb(r){if(Ao(r)){let i=r._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let t=r._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=r.value;if(n!==void 0)return n}import*as S from"zod/v4";var PR="2025-11-25";var GG=[PR,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ds="io.modelcontextprotocol/related-task",Eb="2.0",Dr=S.custom(r=>r!==null&&(typeof r=="object"||typeof r=="function")),WG=S.union([S.string(),S.number().int()]),VG=S.string(),eBt=S.looseObject({ttl:S.union([S.number(),S.null()]).optional(),pollInterval:S.number().optional()}),Xue=S.object({ttl:S.number().optional()}),Jue=S.object({taskId:S.string()}),IR=S.looseObject({progressToken:WG.optional(),[ds]:Jue.optional()}),Vn=S.object({_meta:IR.optional()}),ef=Vn.extend({task:Xue.optional()}),qG=r=>ef.safeParse(r).success,kr=S.object({method:S.string(),params:Vn.loose().optional()}),wo=S.object({_meta:IR.optional()}),Co=S.object({method:S.string(),params:wo.loose().optional()}),Fr=S.looseObject({_meta:IR.optional()}),Tb=S.union([S.string(),S.number().int()]),KG=S.object({jsonrpc:S.literal(Eb),id:Tb,...kr.shape}).strict(),OR=r=>KG.safeParse(r).success,YG=S.object({jsonrpc:S.literal(Eb),...Co.shape}).strict(),XG=r=>YG.safeParse(r).success,NR=S.object({jsonrpc:S.literal(Eb),id:Tb,result:Fr}).strict(),tf=r=>NR.safeParse(r).success;var pe;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(pe||(pe={}));var LR=S.object({jsonrpc:S.literal(Eb),id:Tb.optional(),error:S.object({code:S.number().int(),message:S.string(),data:S.unknown().optional()})}).strict();var JG=r=>LR.safeParse(r).success;var ZG=S.union([KG,YG,NR,LR]),tBt=S.union([NR,LR]),vb=Fr.strict(),Zue=wo.extend({requestId:Tb.optional(),reason:S.string().optional()}),Ab=Co.extend({method:S.literal("notifications/cancelled"),params:Zue}),Que=S.object({src:S.string(),mimeType:S.string().optional(),sizes:S.array(S.string()).optional(),theme:S.enum(["light","dark"]).optional()}),rf=S.object({icons:S.array(Que).optional()}),sd=S.object({name:S.string(),title:S.string().optional()}),QG=sd.extend({...sd.shape,...rf.shape,version:S.string(),websiteUrl:S.string().optional(),description:S.string().optional()}),ede=S.intersection(S.object({applyDefaults:S.boolean().optional()}),S.record(S.string(),S.unknown())),tde=S.preprocess(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,S.intersection(S.object({form:ede.optional(),url:Dr.optional()}),S.record(S.string(),S.unknown()).optional())),rde=S.looseObject({list:Dr.optional(),cancel:Dr.optional(),requests:S.looseObject({sampling:S.looseObject({createMessage:Dr.optional()}).optional(),elicitation:S.looseObject({create:Dr.optional()}).optional()}).optional()}),nde=S.looseObject({list:Dr.optional(),cancel:Dr.optional(),requests:S.looseObject({tools:S.looseObject({call:Dr.optional()}).optional()}).optional()}),ode=S.object({experimental:S.record(S.string(),Dr).optional(),sampling:S.object({context:Dr.optional(),tools:Dr.optional()}).optional(),elicitation:tde.optional(),roots:S.object({listChanged:S.boolean().optional()}).optional(),tasks:rde.optional()}),ide=Vn.extend({protocolVersion:S.string(),capabilities:ode,clientInfo:QG}),DR=kr.extend({method:S.literal("initialize"),params:ide});var ade=S.object({experimental:S.record(S.string(),Dr).optional(),logging:Dr.optional(),completions:Dr.optional(),prompts:S.object({listChanged:S.boolean().optional()}).optional(),resources:S.object({subscribe:S.boolean().optional(),listChanged:S.boolean().optional()}).optional(),tools:S.object({listChanged:S.boolean().optional()}).optional(),tasks:nde.optional()}),sde=Fr.extend({protocolVersion:S.string(),capabilities:ade,serverInfo:QG,instructions:S.string().optional()}),kR=Co.extend({method:S.literal("notifications/initialized"),params:wo.optional()});var wb=kr.extend({method:S.literal("ping"),params:Vn.optional()}),lde=S.object({progress:S.number(),total:S.optional(S.number()),message:S.optional(S.string())}),cde=S.object({...wo.shape,...lde.shape,progressToken:WG}),Cb=Co.extend({method:S.literal("notifications/progress"),params:cde}),ude=Vn.extend({cursor:VG.optional()}),nf=kr.extend({params:ude.optional()}),of=Fr.extend({nextCursor:VG.optional()}),dde=S.enum(["working","input_required","completed","failed","cancelled"]),af=S.object({taskId:S.string(),status:dde,ttl:S.union([S.number(),S.null()]),createdAt:S.string(),lastUpdatedAt:S.string(),pollInterval:S.optional(S.number()),statusMessage:S.optional(S.string())}),ld=Fr.extend({task:af}),mde=wo.merge(af),sf=Co.extend({method:S.literal("notifications/tasks/status"),params:mde}),Rb=kr.extend({method:S.literal("tasks/get"),params:Vn.extend({taskId:S.string()})}),xb=Fr.merge(af),_b=kr.extend({method:S.literal("tasks/result"),params:Vn.extend({taskId:S.string()})}),rBt=Fr.loose(),Mb=nf.extend({method:S.literal("tasks/list")}),Pb=of.extend({tasks:S.array(af)}),Ib=kr.extend({method:S.literal("tasks/cancel"),params:Vn.extend({taskId:S.string()})}),eW=Fr.merge(af),tW=S.object({uri:S.string(),mimeType:S.optional(S.string()),_meta:S.record(S.string(),S.unknown()).optional()}),rW=tW.extend({text:S.string()}),FR=S.string().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),nW=tW.extend({blob:FR}),lf=S.enum(["user","assistant"]),cd=S.object({audience:S.array(lf).optional(),priority:S.number().min(0).max(1).optional(),lastModified:S.iso.datetime({offset:!0}).optional()}),oW=S.object({...sd.shape,...rf.shape,uri:S.string(),description:S.optional(S.string()),mimeType:S.optional(S.string()),annotations:cd.optional(),_meta:S.optional(S.looseObject({}))}),pde=S.object({...sd.shape,...rf.shape,uriTemplate:S.string(),description:S.optional(S.string()),mimeType:S.optional(S.string()),annotations:cd.optional(),_meta:S.optional(S.looseObject({}))}),Ob=nf.extend({method:S.literal("resources/list")}),fde=of.extend({resources:S.array(oW)}),Nb=nf.extend({method:S.literal("resources/templates/list")}),hde=of.extend({resourceTemplates:S.array(pde)}),UR=Vn.extend({uri:S.string()}),gde=UR,Lb=kr.extend({method:S.literal("resources/read"),params:gde}),yde=Fr.extend({contents:S.array(S.union([rW,nW]))}),Sde=Co.extend({method:S.literal("notifications/resources/list_changed"),params:wo.optional()}),bde=UR,Ede=kr.extend({method:S.literal("resources/subscribe"),params:bde}),Tde=UR,vde=kr.extend({method:S.literal("resources/unsubscribe"),params:Tde}),Ade=wo.extend({uri:S.string()}),wde=Co.extend({method:S.literal("notifications/resources/updated"),params:Ade}),Cde=S.object({name:S.string(),description:S.optional(S.string()),required:S.optional(S.boolean())}),Rde=S.object({...sd.shape,...rf.shape,description:S.optional(S.string()),arguments:S.optional(S.array(Cde)),_meta:S.optional(S.looseObject({}))}),Db=nf.extend({method:S.literal("prompts/list")}),xde=of.extend({prompts:S.array(Rde)}),_de=Vn.extend({name:S.string(),arguments:S.record(S.string(),S.string()).optional()}),kb=kr.extend({method:S.literal("prompts/get"),params:_de}),BR=S.object({type:S.literal("text"),text:S.string(),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),zR=S.object({type:S.literal("image"),data:FR,mimeType:S.string(),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),$R=S.object({type:S.literal("audio"),data:FR,mimeType:S.string(),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Mde=S.object({type:S.literal("tool_use"),name:S.string(),id:S.string(),input:S.record(S.string(),S.unknown()),_meta:S.record(S.string(),S.unknown()).optional()}),Pde=S.object({type:S.literal("resource"),resource:S.union([rW,nW]),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Ide=oW.extend({type:S.literal("resource_link")}),HR=S.union([BR,zR,$R,Ide,Pde]),Ode=S.object({role:lf,content:HR}),Nde=Fr.extend({description:S.string().optional(),messages:S.array(Ode)}),Lde=Co.extend({method:S.literal("notifications/prompts/list_changed"),params:wo.optional()}),Dde=S.object({title:S.string().optional(),readOnlyHint:S.boolean().optional(),destructiveHint:S.boolean().optional(),idempotentHint:S.boolean().optional(),openWorldHint:S.boolean().optional()}),kde=S.object({taskSupport:S.enum(["required","optional","forbidden"]).optional()}),iW=S.object({...sd.shape,...rf.shape,description:S.string().optional(),inputSchema:S.object({type:S.literal("object"),properties:S.record(S.string(),Dr).optional(),required:S.array(S.string()).optional()}).catchall(S.unknown()),outputSchema:S.object({type:S.literal("object"),properties:S.record(S.string(),Dr).optional(),required:S.array(S.string()).optional()}).catchall(S.unknown()).optional(),annotations:Dde.optional(),execution:kde.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Fb=nf.extend({method:S.literal("tools/list")}),Fde=of.extend({tools:S.array(iW)}),Ub=Fr.extend({content:S.array(HR).default([]),structuredContent:S.record(S.string(),S.unknown()).optional(),isError:S.boolean().optional()}),nBt=Ub.or(Fr.extend({toolResult:S.unknown()})),Ude=ef.extend({name:S.string(),arguments:S.record(S.string(),S.unknown()).optional()}),ud=kr.extend({method:S.literal("tools/call"),params:Ude}),Bde=Co.extend({method:S.literal("notifications/tools/list_changed"),params:wo.optional()}),oBt=S.object({autoRefresh:S.boolean().default(!0),debounceMs:S.number().int().nonnegative().default(300)}),cf=S.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),zde=Vn.extend({level:cf}),jR=kr.extend({method:S.literal("logging/setLevel"),params:zde}),$de=wo.extend({level:cf,logger:S.string().optional(),data:S.unknown()}),Hde=Co.extend({method:S.literal("notifications/message"),params:$de}),jde=S.object({name:S.string().optional()}),Gde=S.object({hints:S.array(jde).optional(),costPriority:S.number().min(0).max(1).optional(),speedPriority:S.number().min(0).max(1).optional(),intelligencePriority:S.number().min(0).max(1).optional()}),Wde=S.object({mode:S.enum(["auto","required","none"]).optional()}),Vde=S.object({type:S.literal("tool_result"),toolUseId:S.string().describe("The unique identifier for the corresponding tool call."),content:S.array(HR).default([]),structuredContent:S.object({}).loose().optional(),isError:S.boolean().optional(),_meta:S.record(S.string(),S.unknown()).optional()}),qde=S.discriminatedUnion("type",[BR,zR,$R]),bb=S.discriminatedUnion("type",[BR,zR,$R,Mde,Vde]),Kde=S.object({role:lf,content:S.union([bb,S.array(bb)]),_meta:S.record(S.string(),S.unknown()).optional()}),Yde=ef.extend({messages:S.array(Kde),modelPreferences:Gde.optional(),systemPrompt:S.string().optional(),includeContext:S.enum(["none","thisServer","allServers"]).optional(),temperature:S.number().optional(),maxTokens:S.number().int(),stopSequences:S.array(S.string()).optional(),metadata:Dr.optional(),tools:S.array(iW).optional(),toolChoice:Wde.optional()}),Xde=kr.extend({method:S.literal("sampling/createMessage"),params:Yde}),GR=Fr.extend({model:S.string(),stopReason:S.optional(S.enum(["endTurn","stopSequence","maxTokens"]).or(S.string())),role:lf,content:qde}),WR=Fr.extend({model:S.string(),stopReason:S.optional(S.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(S.string())),role:lf,content:S.union([bb,S.array(bb)])}),Jde=S.object({type:S.literal("boolean"),title:S.string().optional(),description:S.string().optional(),default:S.boolean().optional()}),Zde=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),minLength:S.number().optional(),maxLength:S.number().optional(),format:S.enum(["email","uri","date","date-time"]).optional(),default:S.string().optional()}),Qde=S.object({type:S.enum(["number","integer"]),title:S.string().optional(),description:S.string().optional(),minimum:S.number().optional(),maximum:S.number().optional(),default:S.number().optional()}),eme=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),enum:S.array(S.string()),default:S.string().optional()}),tme=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),oneOf:S.array(S.object({const:S.string(),title:S.string()})),default:S.string().optional()}),rme=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),enum:S.array(S.string()),enumNames:S.array(S.string()).optional(),default:S.string().optional()}),nme=S.union([eme,tme]),ome=S.object({type:S.literal("array"),title:S.string().optional(),description:S.string().optional(),minItems:S.number().optional(),maxItems:S.number().optional(),items:S.object({type:S.literal("string"),enum:S.array(S.string())}),default:S.array(S.string()).optional()}),ime=S.object({type:S.literal("array"),title:S.string().optional(),description:S.string().optional(),minItems:S.number().optional(),maxItems:S.number().optional(),items:S.object({anyOf:S.array(S.object({const:S.string(),title:S.string()}))}),default:S.array(S.string()).optional()}),ame=S.union([ome,ime]),sme=S.union([rme,nme,ame]),lme=S.union([sme,Jde,Zde,Qde]),cme=ef.extend({mode:S.literal("form").optional(),message:S.string(),requestedSchema:S.object({type:S.literal("object"),properties:S.record(S.string(),lme),required:S.array(S.string()).optional()})}),ume=ef.extend({mode:S.literal("url"),message:S.string(),elicitationId:S.string(),url:S.string().url()}),dme=S.union([cme,ume]),mme=kr.extend({method:S.literal("elicitation/create"),params:dme}),pme=wo.extend({elicitationId:S.string()}),fme=Co.extend({method:S.literal("notifications/elicitation/complete"),params:pme}),Bb=Fr.extend({action:S.enum(["accept","decline","cancel"]),content:S.preprocess(r=>r===null?void 0:r,S.record(S.string(),S.union([S.string(),S.number(),S.boolean(),S.array(S.string())])).optional())}),hme=S.object({type:S.literal("ref/resource"),uri:S.string()});var gme=S.object({type:S.literal("ref/prompt"),name:S.string()}),yme=Vn.extend({ref:S.union([gme,hme]),argument:S.object({name:S.string(),value:S.string()}),context:S.object({arguments:S.record(S.string(),S.string()).optional()}).optional()}),zb=kr.extend({method:S.literal("completion/complete"),params:yme});function aW(r){if(r.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${r.params.ref.type}`)}function sW(r){if(r.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${r.params.ref.type}`)}var Sme=Fr.extend({completion:S.looseObject({values:S.array(S.string()).max(100),total:S.optional(S.number().int()),hasMore:S.optional(S.boolean())})}),bme=S.object({uri:S.string().startsWith("file://"),name:S.string().optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Eme=kr.extend({method:S.literal("roots/list"),params:Vn.optional()}),VR=Fr.extend({roots:S.array(bme)}),Tme=Co.extend({method:S.literal("notifications/roots/list_changed"),params:wo.optional()}),iBt=S.union([wb,DR,zb,jR,kb,Db,Ob,Nb,Lb,Ede,vde,ud,Fb,Rb,_b,Mb,Ib]),aBt=S.union([Ab,Cb,kR,Tme,sf]),sBt=S.union([vb,GR,WR,Bb,VR,xb,Pb,ld]),lBt=S.union([wb,Xde,mme,Eme,Rb,_b,Mb,Ib]),cBt=S.union([Ab,Cb,Hde,wde,Sde,Bde,Lde,sf,fme]),uBt=S.union([vb,sde,Sme,Nde,xde,fde,hde,yde,Ub,Fde,xb,Pb,ld]),ce=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===pe.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new MR(o.elicitations,t)}return new r(e,t,n)}},MR=class extends ce{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(pe.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ms(r){return r==="completed"||r==="failed"||r==="cancelled"}import*as zW from"zod/v4-mini";var cW=Symbol("Let zodToJsonSchema decide on which parser to use");var lW={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},uW=r=>typeof r=="string"?{...lW,name:r}:{...lW,...r};var dW=r=>{let e=uW(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function qR(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function nt(r,e,t,n,o){r[e]=t,qR(r,e,n,o)}var $b=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as Xe}from"zod/v3";function Wt(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?$b(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as vme}from"zod/v3";function mW(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==vme.ZodAny&&(t.items=Ae(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&nt(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&nt(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(nt(t,"minItems",r.exactLength.value,r.exactLength.message,e),nt(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function pW(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?nt(t,"minimum",n.value,n.message,e):nt(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),nt(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?nt(t,"maximum",n.value,n.message,e):nt(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),nt(t,"maximum",n.value,n.message,e));break;case"multipleOf":nt(t,"multipleOf",n.value,n.message,e);break}return t}function fW(){return{type:"boolean"}}function Hb(r,e){return Ae(r.type._def,e)}var hW=(r,e)=>Ae(r.innerType._def,e);function KR(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>KR(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ame(r,e)}}var Ame=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":nt(t,"minimum",n.value,n.message,e);break;case"max":nt(t,"maximum",n.value,n.message,e);break}return t};function gW(r,e){return{...Ae(r.innerType._def,e),default:r.defaultValue()}}function yW(r,e){return e.effectStrategy==="input"?Ae(r.schema._def,e):Wt(e)}function SW(r){return{type:"string",enum:Array.from(r.values)}}var wme=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function bW(r,e){let t=[Ae(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ae(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(wme(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...l}=i;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function EW(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as uf}from"zod/v3";var YR,Wo={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(YR===void 0&&(YR=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),YR),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function jb(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":nt(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":nt(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Vo(t,"email",n.message,e);break;case"format:idn-email":Vo(t,"idn-email",n.message,e);break;case"pattern:zod":Sn(t,Wo.email,n.message,e);break}break;case"url":Vo(t,"uri",n.message,e);break;case"uuid":Vo(t,"uuid",n.message,e);break;case"regex":Sn(t,n.regex,n.message,e);break;case"cuid":Sn(t,Wo.cuid,n.message,e);break;case"cuid2":Sn(t,Wo.cuid2,n.message,e);break;case"startsWith":Sn(t,RegExp(`^${XR(n.value,e)}`),n.message,e);break;case"endsWith":Sn(t,RegExp(`${XR(n.value,e)}$`),n.message,e);break;case"datetime":Vo(t,"date-time",n.message,e);break;case"date":Vo(t,"date",n.message,e);break;case"time":Vo(t,"time",n.message,e);break;case"duration":Vo(t,"duration",n.message,e);break;case"length":nt(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),nt(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Sn(t,RegExp(XR(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Vo(t,"ipv4",n.message,e),n.version!=="v4"&&Vo(t,"ipv6",n.message,e);break}case"base64url":Sn(t,Wo.base64url,n.message,e);break;case"jwt":Sn(t,Wo.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Sn(t,Wo.ipv4Cidr,n.message,e),n.version!=="v4"&&Sn(t,Wo.ipv6Cidr,n.message,e);break}case"emoji":Sn(t,Wo.emoji(),n.message,e);break;case"ulid":{Sn(t,Wo.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Vo(t,"binary",n.message,e);break}case"contentEncoding:base64":{nt(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Sn(t,Wo.base64,n.message,e);break}}break}case"nanoid":Sn(t,Wo.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function XR(r,e){return e.patternStrategy==="escape"?Rme(r):r}var Cme=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Rme(r){let e="";for(let t=0;t<r.length;t++)Cme.has(r[t])||(e+="\\"),e+=r[t];return e}function Vo(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):nt(r,"format",e,t,n)}function Sn(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:TW(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):nt(r,"pattern",TW(e,n),t,n)}function TW(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let l=0;l<n.length;l++){if(i){o+=n[l],i=!1;continue}if(t.i){if(a){if(n[l].match(/[a-z]/)){s?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),s=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],s=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(t.m){if(n[l]==="^"){o+=`(^|(?<=[\r
4896
+ ${o}`}]}async function FG({rootDir:r,cutoffTime:e}){let t=await Hue(r,{withFileTypes:!0});for(let n of t){let o=Qp.join(r,n.name);if(n.isDirectory()){await FG({rootDir:o,cutoffTime:e});continue}if(!n.isFile())continue;(await jue(o)).mtimeMs<e&&await Gue(o)}}async function UG(r){let e=RR(r);DG(e)&&await FG({rootDir:e,cutoffTime:Date.now()-Vue})}import{z as Yue}from"zod";var hb=class{isError;content=[];addPartFromText(e){this.addContent({type:"text",text:e})}addError(e){this.addPartFromText(`Error: ${e}`),this.isError=!0}addContent(e){this.content.push(e)}addContentParts(e){this.content.push(...NG(e))}async serialize(){return{content:this.content,isError:this.isError}}};function BG(r,e){let t=JSON.stringify(r);return t?t.length<=e?t:`${t.slice(0,e)}...`:""}function Lr(r){return{addToolToMcpServer:(t,n)=>{let o=Yue.object(r.schema.inputSchema),i=async(a,s)=>{let l=s.sessionId??t.sessionId??t.serverId,c=t.logger.child({sessionId:l,toolName:r.schema.name}),u=Date.now();c.debug({params:BG(a,500),sessionId:l,toolName:r.schema.name},`MCP tool invoked: ${r.schema.name}`);let d=new hb,m;try{await r.handle({...t,sessionId:l},a,d,s)}catch(h){m=h instanceof Error?h:new Error(Le(h)),d.addError(Le(h))}let p=Date.now()-u,f=await d.serialize();if(m)c.error({duration:p,err:m,sessionId:l,toolName:r.schema.name},`MCP tool failed: ${r.schema.name}`);else{let h=f.content.filter(g=>g.type==="text");c.debug({duration:p,response:BG(h,500),responseIsError:f.isError,sessionId:l,toolName:r.schema.name},`MCP tool completed: ${r.schema.name}`)}return f};n.registerTool(r.schema.name,{title:r.schema.name,description:r.schema.description,inputSchema:o},i)},name:r.schema.name,tool:r}}function xR(r){return r?._meta?.progressToken!==void 0}async function zG(r,e,t,n,o,i){if(!xR(r))return!1;try{await r.sendNotification({method:"notifications/progress",params:{progressToken:r._meta.progressToken,progress:e.completed,total:e.total,...t?{message:t}:{}}})}catch(a){n.error({err:a},"Failed to send progress notification"),o.abort(a),i.addError(`Failed to send progress notification: ${Le(a)}`)}return!0}function _R(r,e,t,n){if(r!==t||e.length!==n.length)return!1;for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}import*as $G from"zod/v3";import*as Fl from"zod/v4-mini";function Ao(r){return!!r._zod}function Ul(r){let e=Object.values(r);if(e.length===0)return Fl.object({});let t=e.every(Ao),n=e.every(o=>!Ao(o));if(t)return Fl.object(r);if(n)return $G.object(r);throw new Error("Mixed Zod versions detected in object shape.")}function cs(r,e){return Ao(r)?Fl.safeParse(r,e):r.safeParse(e)}async function gb(r,e){return Ao(r)?await Fl.safeParseAsync(r,e):await r.safeParseAsync(e)}function us(r){if(!r)return;let e;if(Ao(r)?e=r._zod?.def?.shape:e=r.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function ad(r){if(r){if(typeof r=="object"){let e=r,t=r;if(!e._def&&!t._zod){let n=Object.values(r);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Ul(r)}}if(Ao(r)){let t=r._zod?.def;if(t&&(t.type==="object"||t.shape!==void 0))return r}else if(r.shape!==void 0)return r}}function yb(r){if(r&&typeof r=="object"){if("message"in r&&typeof r.message=="string")return r.message;if("issues"in r&&Array.isArray(r.issues)&&r.issues.length>0){let e=r.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(r)}catch{return String(r)}}return String(r)}function HG(r){return r.description}function jG(r){if(Ao(r))return r._zod?.def?.type==="optional";let e=r;return typeof r.isOptional=="function"?r.isOptional():e._def?.typeName==="ZodOptional"}function Sb(r){if(Ao(r)){let i=r._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let t=r._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=r.value;if(n!==void 0)return n}import*as S from"zod/v4";var PR="2025-11-25";var GG=[PR,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ds="io.modelcontextprotocol/related-task",Eb="2.0",Dr=S.custom(r=>r!==null&&(typeof r=="object"||typeof r=="function")),WG=S.union([S.string(),S.number().int()]),VG=S.string(),rBt=S.looseObject({ttl:S.union([S.number(),S.null()]).optional(),pollInterval:S.number().optional()}),Xue=S.object({ttl:S.number().optional()}),Jue=S.object({taskId:S.string()}),IR=S.looseObject({progressToken:WG.optional(),[ds]:Jue.optional()}),Vn=S.object({_meta:IR.optional()}),ef=Vn.extend({task:Xue.optional()}),qG=r=>ef.safeParse(r).success,kr=S.object({method:S.string(),params:Vn.loose().optional()}),wo=S.object({_meta:IR.optional()}),Co=S.object({method:S.string(),params:wo.loose().optional()}),Fr=S.looseObject({_meta:IR.optional()}),Tb=S.union([S.string(),S.number().int()]),KG=S.object({jsonrpc:S.literal(Eb),id:Tb,...kr.shape}).strict(),OR=r=>KG.safeParse(r).success,YG=S.object({jsonrpc:S.literal(Eb),...Co.shape}).strict(),XG=r=>YG.safeParse(r).success,NR=S.object({jsonrpc:S.literal(Eb),id:Tb,result:Fr}).strict(),tf=r=>NR.safeParse(r).success;var pe;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(pe||(pe={}));var LR=S.object({jsonrpc:S.literal(Eb),id:Tb.optional(),error:S.object({code:S.number().int(),message:S.string(),data:S.unknown().optional()})}).strict();var JG=r=>LR.safeParse(r).success;var ZG=S.union([KG,YG,NR,LR]),nBt=S.union([NR,LR]),vb=Fr.strict(),Zue=wo.extend({requestId:Tb.optional(),reason:S.string().optional()}),Ab=Co.extend({method:S.literal("notifications/cancelled"),params:Zue}),Que=S.object({src:S.string(),mimeType:S.string().optional(),sizes:S.array(S.string()).optional(),theme:S.enum(["light","dark"]).optional()}),rf=S.object({icons:S.array(Que).optional()}),sd=S.object({name:S.string(),title:S.string().optional()}),QG=sd.extend({...sd.shape,...rf.shape,version:S.string(),websiteUrl:S.string().optional(),description:S.string().optional()}),ede=S.intersection(S.object({applyDefaults:S.boolean().optional()}),S.record(S.string(),S.unknown())),tde=S.preprocess(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,S.intersection(S.object({form:ede.optional(),url:Dr.optional()}),S.record(S.string(),S.unknown()).optional())),rde=S.looseObject({list:Dr.optional(),cancel:Dr.optional(),requests:S.looseObject({sampling:S.looseObject({createMessage:Dr.optional()}).optional(),elicitation:S.looseObject({create:Dr.optional()}).optional()}).optional()}),nde=S.looseObject({list:Dr.optional(),cancel:Dr.optional(),requests:S.looseObject({tools:S.looseObject({call:Dr.optional()}).optional()}).optional()}),ode=S.object({experimental:S.record(S.string(),Dr).optional(),sampling:S.object({context:Dr.optional(),tools:Dr.optional()}).optional(),elicitation:tde.optional(),roots:S.object({listChanged:S.boolean().optional()}).optional(),tasks:rde.optional()}),ide=Vn.extend({protocolVersion:S.string(),capabilities:ode,clientInfo:QG}),DR=kr.extend({method:S.literal("initialize"),params:ide});var ade=S.object({experimental:S.record(S.string(),Dr).optional(),logging:Dr.optional(),completions:Dr.optional(),prompts:S.object({listChanged:S.boolean().optional()}).optional(),resources:S.object({subscribe:S.boolean().optional(),listChanged:S.boolean().optional()}).optional(),tools:S.object({listChanged:S.boolean().optional()}).optional(),tasks:nde.optional()}),sde=Fr.extend({protocolVersion:S.string(),capabilities:ade,serverInfo:QG,instructions:S.string().optional()}),kR=Co.extend({method:S.literal("notifications/initialized"),params:wo.optional()});var wb=kr.extend({method:S.literal("ping"),params:Vn.optional()}),lde=S.object({progress:S.number(),total:S.optional(S.number()),message:S.optional(S.string())}),cde=S.object({...wo.shape,...lde.shape,progressToken:WG}),Cb=Co.extend({method:S.literal("notifications/progress"),params:cde}),ude=Vn.extend({cursor:VG.optional()}),nf=kr.extend({params:ude.optional()}),of=Fr.extend({nextCursor:VG.optional()}),dde=S.enum(["working","input_required","completed","failed","cancelled"]),af=S.object({taskId:S.string(),status:dde,ttl:S.union([S.number(),S.null()]),createdAt:S.string(),lastUpdatedAt:S.string(),pollInterval:S.optional(S.number()),statusMessage:S.optional(S.string())}),ld=Fr.extend({task:af}),mde=wo.merge(af),sf=Co.extend({method:S.literal("notifications/tasks/status"),params:mde}),Rb=kr.extend({method:S.literal("tasks/get"),params:Vn.extend({taskId:S.string()})}),xb=Fr.merge(af),_b=kr.extend({method:S.literal("tasks/result"),params:Vn.extend({taskId:S.string()})}),oBt=Fr.loose(),Mb=nf.extend({method:S.literal("tasks/list")}),Pb=of.extend({tasks:S.array(af)}),Ib=kr.extend({method:S.literal("tasks/cancel"),params:Vn.extend({taskId:S.string()})}),eW=Fr.merge(af),tW=S.object({uri:S.string(),mimeType:S.optional(S.string()),_meta:S.record(S.string(),S.unknown()).optional()}),rW=tW.extend({text:S.string()}),FR=S.string().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),nW=tW.extend({blob:FR}),lf=S.enum(["user","assistant"]),cd=S.object({audience:S.array(lf).optional(),priority:S.number().min(0).max(1).optional(),lastModified:S.iso.datetime({offset:!0}).optional()}),oW=S.object({...sd.shape,...rf.shape,uri:S.string(),description:S.optional(S.string()),mimeType:S.optional(S.string()),annotations:cd.optional(),_meta:S.optional(S.looseObject({}))}),pde=S.object({...sd.shape,...rf.shape,uriTemplate:S.string(),description:S.optional(S.string()),mimeType:S.optional(S.string()),annotations:cd.optional(),_meta:S.optional(S.looseObject({}))}),Ob=nf.extend({method:S.literal("resources/list")}),fde=of.extend({resources:S.array(oW)}),Nb=nf.extend({method:S.literal("resources/templates/list")}),hde=of.extend({resourceTemplates:S.array(pde)}),UR=Vn.extend({uri:S.string()}),gde=UR,Lb=kr.extend({method:S.literal("resources/read"),params:gde}),yde=Fr.extend({contents:S.array(S.union([rW,nW]))}),Sde=Co.extend({method:S.literal("notifications/resources/list_changed"),params:wo.optional()}),bde=UR,Ede=kr.extend({method:S.literal("resources/subscribe"),params:bde}),Tde=UR,vde=kr.extend({method:S.literal("resources/unsubscribe"),params:Tde}),Ade=wo.extend({uri:S.string()}),wde=Co.extend({method:S.literal("notifications/resources/updated"),params:Ade}),Cde=S.object({name:S.string(),description:S.optional(S.string()),required:S.optional(S.boolean())}),Rde=S.object({...sd.shape,...rf.shape,description:S.optional(S.string()),arguments:S.optional(S.array(Cde)),_meta:S.optional(S.looseObject({}))}),Db=nf.extend({method:S.literal("prompts/list")}),xde=of.extend({prompts:S.array(Rde)}),_de=Vn.extend({name:S.string(),arguments:S.record(S.string(),S.string()).optional()}),kb=kr.extend({method:S.literal("prompts/get"),params:_de}),BR=S.object({type:S.literal("text"),text:S.string(),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),zR=S.object({type:S.literal("image"),data:FR,mimeType:S.string(),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),$R=S.object({type:S.literal("audio"),data:FR,mimeType:S.string(),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Mde=S.object({type:S.literal("tool_use"),name:S.string(),id:S.string(),input:S.record(S.string(),S.unknown()),_meta:S.record(S.string(),S.unknown()).optional()}),Pde=S.object({type:S.literal("resource"),resource:S.union([rW,nW]),annotations:cd.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Ide=oW.extend({type:S.literal("resource_link")}),HR=S.union([BR,zR,$R,Ide,Pde]),Ode=S.object({role:lf,content:HR}),Nde=Fr.extend({description:S.string().optional(),messages:S.array(Ode)}),Lde=Co.extend({method:S.literal("notifications/prompts/list_changed"),params:wo.optional()}),Dde=S.object({title:S.string().optional(),readOnlyHint:S.boolean().optional(),destructiveHint:S.boolean().optional(),idempotentHint:S.boolean().optional(),openWorldHint:S.boolean().optional()}),kde=S.object({taskSupport:S.enum(["required","optional","forbidden"]).optional()}),iW=S.object({...sd.shape,...rf.shape,description:S.string().optional(),inputSchema:S.object({type:S.literal("object"),properties:S.record(S.string(),Dr).optional(),required:S.array(S.string()).optional()}).catchall(S.unknown()),outputSchema:S.object({type:S.literal("object"),properties:S.record(S.string(),Dr).optional(),required:S.array(S.string()).optional()}).catchall(S.unknown()).optional(),annotations:Dde.optional(),execution:kde.optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Fb=nf.extend({method:S.literal("tools/list")}),Fde=of.extend({tools:S.array(iW)}),Ub=Fr.extend({content:S.array(HR).default([]),structuredContent:S.record(S.string(),S.unknown()).optional(),isError:S.boolean().optional()}),iBt=Ub.or(Fr.extend({toolResult:S.unknown()})),Ude=ef.extend({name:S.string(),arguments:S.record(S.string(),S.unknown()).optional()}),ud=kr.extend({method:S.literal("tools/call"),params:Ude}),Bde=Co.extend({method:S.literal("notifications/tools/list_changed"),params:wo.optional()}),aBt=S.object({autoRefresh:S.boolean().default(!0),debounceMs:S.number().int().nonnegative().default(300)}),cf=S.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),zde=Vn.extend({level:cf}),jR=kr.extend({method:S.literal("logging/setLevel"),params:zde}),$de=wo.extend({level:cf,logger:S.string().optional(),data:S.unknown()}),Hde=Co.extend({method:S.literal("notifications/message"),params:$de}),jde=S.object({name:S.string().optional()}),Gde=S.object({hints:S.array(jde).optional(),costPriority:S.number().min(0).max(1).optional(),speedPriority:S.number().min(0).max(1).optional(),intelligencePriority:S.number().min(0).max(1).optional()}),Wde=S.object({mode:S.enum(["auto","required","none"]).optional()}),Vde=S.object({type:S.literal("tool_result"),toolUseId:S.string().describe("The unique identifier for the corresponding tool call."),content:S.array(HR).default([]),structuredContent:S.object({}).loose().optional(),isError:S.boolean().optional(),_meta:S.record(S.string(),S.unknown()).optional()}),qde=S.discriminatedUnion("type",[BR,zR,$R]),bb=S.discriminatedUnion("type",[BR,zR,$R,Mde,Vde]),Kde=S.object({role:lf,content:S.union([bb,S.array(bb)]),_meta:S.record(S.string(),S.unknown()).optional()}),Yde=ef.extend({messages:S.array(Kde),modelPreferences:Gde.optional(),systemPrompt:S.string().optional(),includeContext:S.enum(["none","thisServer","allServers"]).optional(),temperature:S.number().optional(),maxTokens:S.number().int(),stopSequences:S.array(S.string()).optional(),metadata:Dr.optional(),tools:S.array(iW).optional(),toolChoice:Wde.optional()}),Xde=kr.extend({method:S.literal("sampling/createMessage"),params:Yde}),GR=Fr.extend({model:S.string(),stopReason:S.optional(S.enum(["endTurn","stopSequence","maxTokens"]).or(S.string())),role:lf,content:qde}),WR=Fr.extend({model:S.string(),stopReason:S.optional(S.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(S.string())),role:lf,content:S.union([bb,S.array(bb)])}),Jde=S.object({type:S.literal("boolean"),title:S.string().optional(),description:S.string().optional(),default:S.boolean().optional()}),Zde=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),minLength:S.number().optional(),maxLength:S.number().optional(),format:S.enum(["email","uri","date","date-time"]).optional(),default:S.string().optional()}),Qde=S.object({type:S.enum(["number","integer"]),title:S.string().optional(),description:S.string().optional(),minimum:S.number().optional(),maximum:S.number().optional(),default:S.number().optional()}),eme=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),enum:S.array(S.string()),default:S.string().optional()}),tme=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),oneOf:S.array(S.object({const:S.string(),title:S.string()})),default:S.string().optional()}),rme=S.object({type:S.literal("string"),title:S.string().optional(),description:S.string().optional(),enum:S.array(S.string()),enumNames:S.array(S.string()).optional(),default:S.string().optional()}),nme=S.union([eme,tme]),ome=S.object({type:S.literal("array"),title:S.string().optional(),description:S.string().optional(),minItems:S.number().optional(),maxItems:S.number().optional(),items:S.object({type:S.literal("string"),enum:S.array(S.string())}),default:S.array(S.string()).optional()}),ime=S.object({type:S.literal("array"),title:S.string().optional(),description:S.string().optional(),minItems:S.number().optional(),maxItems:S.number().optional(),items:S.object({anyOf:S.array(S.object({const:S.string(),title:S.string()}))}),default:S.array(S.string()).optional()}),ame=S.union([ome,ime]),sme=S.union([rme,nme,ame]),lme=S.union([sme,Jde,Zde,Qde]),cme=ef.extend({mode:S.literal("form").optional(),message:S.string(),requestedSchema:S.object({type:S.literal("object"),properties:S.record(S.string(),lme),required:S.array(S.string()).optional()})}),ume=ef.extend({mode:S.literal("url"),message:S.string(),elicitationId:S.string(),url:S.string().url()}),dme=S.union([cme,ume]),mme=kr.extend({method:S.literal("elicitation/create"),params:dme}),pme=wo.extend({elicitationId:S.string()}),fme=Co.extend({method:S.literal("notifications/elicitation/complete"),params:pme}),Bb=Fr.extend({action:S.enum(["accept","decline","cancel"]),content:S.preprocess(r=>r===null?void 0:r,S.record(S.string(),S.union([S.string(),S.number(),S.boolean(),S.array(S.string())])).optional())}),hme=S.object({type:S.literal("ref/resource"),uri:S.string()});var gme=S.object({type:S.literal("ref/prompt"),name:S.string()}),yme=Vn.extend({ref:S.union([gme,hme]),argument:S.object({name:S.string(),value:S.string()}),context:S.object({arguments:S.record(S.string(),S.string()).optional()}).optional()}),zb=kr.extend({method:S.literal("completion/complete"),params:yme});function aW(r){if(r.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${r.params.ref.type}`)}function sW(r){if(r.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${r.params.ref.type}`)}var Sme=Fr.extend({completion:S.looseObject({values:S.array(S.string()).max(100),total:S.optional(S.number().int()),hasMore:S.optional(S.boolean())})}),bme=S.object({uri:S.string().startsWith("file://"),name:S.string().optional(),_meta:S.record(S.string(),S.unknown()).optional()}),Eme=kr.extend({method:S.literal("roots/list"),params:Vn.optional()}),VR=Fr.extend({roots:S.array(bme)}),Tme=Co.extend({method:S.literal("notifications/roots/list_changed"),params:wo.optional()}),sBt=S.union([wb,DR,zb,jR,kb,Db,Ob,Nb,Lb,Ede,vde,ud,Fb,Rb,_b,Mb,Ib]),lBt=S.union([Ab,Cb,kR,Tme,sf]),cBt=S.union([vb,GR,WR,Bb,VR,xb,Pb,ld]),uBt=S.union([wb,Xde,mme,Eme,Rb,_b,Mb,Ib]),dBt=S.union([Ab,Cb,Hde,wde,Sde,Bde,Lde,sf,fme]),mBt=S.union([vb,sde,Sme,Nde,xde,fde,hde,yde,Ub,Fde,xb,Pb,ld]),ce=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===pe.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new MR(o.elicitations,t)}return new r(e,t,n)}},MR=class extends ce{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(pe.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ms(r){return r==="completed"||r==="failed"||r==="cancelled"}import*as zW from"zod/v4-mini";var cW=Symbol("Let zodToJsonSchema decide on which parser to use");var lW={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},uW=r=>typeof r=="string"?{...lW,name:r}:{...lW,...r};var dW=r=>{let e=uW(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function qR(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function nt(r,e,t,n,o){r[e]=t,qR(r,e,n,o)}var $b=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as Xe}from"zod/v3";function Wt(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?$b(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as vme}from"zod/v3";function mW(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==vme.ZodAny&&(t.items=Ae(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&nt(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&nt(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(nt(t,"minItems",r.exactLength.value,r.exactLength.message,e),nt(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function pW(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?nt(t,"minimum",n.value,n.message,e):nt(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),nt(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?nt(t,"maximum",n.value,n.message,e):nt(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),nt(t,"maximum",n.value,n.message,e));break;case"multipleOf":nt(t,"multipleOf",n.value,n.message,e);break}return t}function fW(){return{type:"boolean"}}function Hb(r,e){return Ae(r.type._def,e)}var hW=(r,e)=>Ae(r.innerType._def,e);function KR(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>KR(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ame(r,e)}}var Ame=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":nt(t,"minimum",n.value,n.message,e);break;case"max":nt(t,"maximum",n.value,n.message,e);break}return t};function gW(r,e){return{...Ae(r.innerType._def,e),default:r.defaultValue()}}function yW(r,e){return e.effectStrategy==="input"?Ae(r.schema._def,e):Wt(e)}function SW(r){return{type:"string",enum:Array.from(r.values)}}var wme=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function bW(r,e){let t=[Ae(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ae(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(wme(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...l}=i;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function EW(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as uf}from"zod/v3";var YR,Wo={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(YR===void 0&&(YR=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),YR),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function jb(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":nt(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":nt(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Vo(t,"email",n.message,e);break;case"format:idn-email":Vo(t,"idn-email",n.message,e);break;case"pattern:zod":Sn(t,Wo.email,n.message,e);break}break;case"url":Vo(t,"uri",n.message,e);break;case"uuid":Vo(t,"uuid",n.message,e);break;case"regex":Sn(t,n.regex,n.message,e);break;case"cuid":Sn(t,Wo.cuid,n.message,e);break;case"cuid2":Sn(t,Wo.cuid2,n.message,e);break;case"startsWith":Sn(t,RegExp(`^${XR(n.value,e)}`),n.message,e);break;case"endsWith":Sn(t,RegExp(`${XR(n.value,e)}$`),n.message,e);break;case"datetime":Vo(t,"date-time",n.message,e);break;case"date":Vo(t,"date",n.message,e);break;case"time":Vo(t,"time",n.message,e);break;case"duration":Vo(t,"duration",n.message,e);break;case"length":nt(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),nt(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Sn(t,RegExp(XR(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Vo(t,"ipv4",n.message,e),n.version!=="v4"&&Vo(t,"ipv6",n.message,e);break}case"base64url":Sn(t,Wo.base64url,n.message,e);break;case"jwt":Sn(t,Wo.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Sn(t,Wo.ipv4Cidr,n.message,e),n.version!=="v4"&&Sn(t,Wo.ipv6Cidr,n.message,e);break}case"emoji":Sn(t,Wo.emoji(),n.message,e);break;case"ulid":{Sn(t,Wo.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Vo(t,"binary",n.message,e);break}case"contentEncoding:base64":{nt(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Sn(t,Wo.base64,n.message,e);break}}break}case"nanoid":Sn(t,Wo.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function XR(r,e){return e.patternStrategy==="escape"?Rme(r):r}var Cme=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Rme(r){let e="";for(let t=0;t<r.length;t++)Cme.has(r[t])||(e+="\\"),e+=r[t];return e}function Vo(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):nt(r,"format",e,t,n)}function Sn(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:TW(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):nt(r,"pattern",TW(e,n),t,n)}function TW(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let l=0;l<n.length;l++){if(i){o+=n[l],i=!1;continue}if(t.i){if(a){if(n[l].match(/[a-z]/)){s?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),s=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],s=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(t.m){if(n[l]==="^"){o+=`(^|(?<=[\r
4897
4897
  ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
4898
4898
  ]))`;continue}}if(t.s&&n[l]==="."){o+=a?`${n[l]}\r
4899
4899
  `:`[${n[l]}\r
4900
4900
  ]`;continue}o+=n[l],n[l]==="\\"?i=!0:a&&n[l]==="]"?a=!1:!a&&n[l]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function Gb(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===uf.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:Ae(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Wt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:Ae(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===uf.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=jb(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===uf.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===uf.ZodBranded&&r.keyType._def.type._def.typeName===uf.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=Hb(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function vW(r,e){if(e.mapStrategy==="record")return Gb(r,e);let t=Ae(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Wt(e),n=Ae(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Wt(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function AW(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function wW(r){return r.target==="openAi"?void 0:{not:Wt({...r,currentPath:[...r.currentPath,"not"]})}}function CW(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var df={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function xW(r,e){if(e.target==="openApi3")return RW(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in df&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=df[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return RW(r,e)}var RW=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>Ae(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function _W(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:df[r.innerType._def.typeName],nullable:!0}:{type:[df[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Ae(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=Ae(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function MW(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",qR(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?nt(t,"minimum",n.value,n.message,e):nt(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),nt(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?nt(t,"maximum",n.value,n.message,e):nt(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),nt(t,"maximum",n.value,n.message,e));break;case"multipleOf":nt(t,"multipleOf",n.value,n.message,e);break}return t}function PW(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let s in i){let l=i[s];if(l===void 0||l._def===void 0)continue;let c=_me(l);c&&t&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);let u=Ae(l._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,c||o.push(s))}o.length&&(n.required=o);let a=xme(r,e);return a!==void 0&&(n.additionalProperties=a),n}function xme(r,e){if(r.catchall._def.typeName!=="ZodNever")return Ae(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function _me(r){try{return r.isOptional()}catch{return!0}}var IW=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Ae(r.innerType._def,e);let t=Ae(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Wt(e)},t]}:Wt(e)};var OW=(r,e)=>{if(e.pipeStrategy==="input")return Ae(r.in._def,e);if(e.pipeStrategy==="output")return Ae(r.out._def,e);let t=Ae(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ae(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function NW(r,e){return Ae(r.type._def,e)}function LW(r,e){let n={type:"array",uniqueItems:!0,items:Ae(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&nt(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&nt(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function DW(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>Ae(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:Ae(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>Ae(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function kW(r){return{not:Wt(r)}}function FW(r){return Wt(r)}var UW=(r,e)=>Ae(r.innerType._def,e);var BW=(r,e,t)=>{switch(e){case Xe.ZodString:return jb(r,t);case Xe.ZodNumber:return MW(r,t);case Xe.ZodObject:return PW(r,t);case Xe.ZodBigInt:return pW(r,t);case Xe.ZodBoolean:return fW();case Xe.ZodDate:return KR(r,t);case Xe.ZodUndefined:return kW(t);case Xe.ZodNull:return CW(t);case Xe.ZodArray:return mW(r,t);case Xe.ZodUnion:case Xe.ZodDiscriminatedUnion:return xW(r,t);case Xe.ZodIntersection:return bW(r,t);case Xe.ZodTuple:return DW(r,t);case Xe.ZodRecord:return Gb(r,t);case Xe.ZodLiteral:return EW(r,t);case Xe.ZodEnum:return SW(r);case Xe.ZodNativeEnum:return AW(r);case Xe.ZodNullable:return _W(r,t);case Xe.ZodOptional:return IW(r,t);case Xe.ZodMap:return vW(r,t);case Xe.ZodSet:return LW(r,t);case Xe.ZodLazy:return()=>r.getter()._def;case Xe.ZodPromise:return NW(r,t);case Xe.ZodNaN:case Xe.ZodNever:return wW(t);case Xe.ZodEffects:return yW(r,t);case Xe.ZodAny:return Wt(t);case Xe.ZodUnknown:return FW(t);case Xe.ZodDefault:return gW(r,t);case Xe.ZodBranded:return Hb(r,t);case Xe.ZodReadonly:return UW(r,t);case Xe.ZodCatch:return hW(r,t);case Xe.ZodPipeline:return OW(r,t);case Xe.ZodFunction:case Xe.ZodVoid:case Xe.ZodSymbol:return;default:return(n=>{})(e)}};function Ae(r,e,t=!1){let n=e.seen.get(r);if(e.override){let s=e.override?.(r,e,n,t);if(s!==cW)return s}if(n&&!t){let s=Mme(n,e);if(s!==void 0)return s}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=BW(r,r.typeName,e),a=typeof i=="function"?Ae(i(),e):i;if(a&&Pme(r,e,a),e.postProcess){let s=e.postProcess(a,r,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var Mme=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:$b(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Wt(e)):e.$refStrategy==="seen"?Wt(e):void 0}},Pme=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var JR=(r,e)=>{let t=dW(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Ae(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,c]},!0)??Wt(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Ae(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??Wt(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function Ime(r){return!r||r==="jsonSchema7"||r==="draft-7"?"draft-7":r==="jsonSchema2019-09"||r==="draft-2020-12"?"draft-2020-12":"draft-7"}function ZR(r,e){return Ao(r)?zW.toJSONSchema(r,{target:Ime(e?.target),io:e?.pipeStrategy??"input"}):JR(r,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function QR(r){let t=us(r)?.method;if(!t)throw new Error("Schema is missing a method literal");let n=Sb(t);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ex(r,e){let t=cs(r,e);if(!t.success)throw t.error;return t.data}var Ome=6e4,Wb=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ab,t=>{this._oncancel(t)}),this.setNotificationHandler(Cb,t=>{this._onprogress(t)}),this.setRequestHandler(wb,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Rb,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new ce(pe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(_b,async(t,n)=>{let o=async()=>{let i=t.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(s.type==="response"||s.type==="error"){let l=s.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),s.type==="response")u(l);else{let d=l,m=new ce(d.error.code,d.error.message,d.error.data);u(m)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new ce(pe.InvalidParams,`Task not found: ${i}`);if(!ms(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ms(a.status)){let s=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[ds]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Mb,async(t,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new ce(pe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ib,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new ce(pe.InvalidParams,`Task not found: ${t.params.taskId}`);if(ms(o.status))throw new ce(pe.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);let i=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!i)throw new ce(pe.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof ce?o:new ce(pe.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),ce.fromError(pe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),tf(i)||JG(i)?this._onresponse(i):OR(i)?this._onrequest(i,a):XG(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let t=ce.fromError(pe.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[ds]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:pe.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=qG(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,m)=>{if(a.signal.aborted)throw new ce(pe.ConnectionClosed,"Request was cancelled");let p={...m,relatedRequestId:e.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let f=p.relatedTask?.taskId??i;return f&&l&&await l.updateTaskStatus(f,"input_required"),await this.request(u,d,p)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:l,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async u=>{if(a.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:pe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),tf(e))n(e);else{let a=new ce(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(t);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(tf(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,t))}}if(i||this._progressHandlers.delete(t),tf(e))o(e);else{let a=ce.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,t,n)}}catch(a){yield{type:"error",error:a instanceof ce?a:new ce(pe.InternalError,String(a))}}return}let i;try{let a=await this.request(e,ld,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ce(pe.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:s},ms(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},t,n)}:s.status==="failed"?yield{type:"error",error:new ce(pe.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new ce(pe.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},t,n)};return}let l=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof ce?a:new ce(pe.InternalError,String(a))}}}request(e,t,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:l}=n??{};return new Promise((c,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),s&&(p.params={...p.params,task:s}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[ds]:l}});let f=b=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));let E=b instanceof ce?b:new ce(pe.RequestTimeout,String(b));u(E)};this._responseHandlers.set(m,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let E=cs(t,b.result);E.success?c(E.data):u(E.error)}catch(E){u(E)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??Ome,g=()=>f(ce.fromError(pe.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=l?.taskId;if(y){let b=E=>{let v=this._responseHandlers.get(m);v?v(E):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,b),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(E=>{this._cleanupTimeout(m),u(E)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(b=>{this._cleanupTimeout(m),u(b)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},xb,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Pb,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},eW,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ds]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ds]:t.relatedTask}}}),this._transport?.send(s,t).catch(l=>this._onerror(l))});return}let a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ds]:t.relatedTask}}}),await this._transport.send(a,t)}setRequestHandler(e,t){let n=QR(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=ex(e,o);return Promise.resolve(t(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=QR(e);this._notificationHandlers.set(n,o=>{let i=ex(e,o);return Promise.resolve(t(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let o of n)if(o.type==="request"&&OR(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new ce(pe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(t.aborted){i(new ce(pe.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(a),i(new ce(pe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async o=>{let i=await n.getTask(o,t);if(!i)throw new ce(pe.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,t);let s=await n.getTask(o,t);if(s){let l=sf.parse({method:"notifications/tasks/status",params:s});await this.notification(l),ms(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,t),updateTaskStatus:async(o,i,a)=>{let s=await n.getTask(o,t);if(!s)throw new ce(pe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ms(s.status))throw new ce(pe.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,t);let l=await n.getTask(o,t);if(l){let c=sf.parse({method:"notifications/tasks/status",params:l});await this.notification(c),ms(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,t)}}};function $W(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function HW(r,e){let t={...r};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=t[o];$W(a)&&$W(i)?t[o]={...a,...i}:t[o]=i}return t}var L2=Jf(U_(),1),D2=Jf(N2(),1);function vSe(){let r=new L2.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,D2.default)(r),r}var RE=class{constructor(e){this._ajv=e??vSe()}getValidator(e){let t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>t(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};var xE=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function k2(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!r.tools?.call)throw new Error(`${t} does not support task creation for tools/call (required for ${e})`);break;default:break}}function F2(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!r.sampling?.createMessage)throw new Error(`${t} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!r.elicitation?.create)throw new Error(`${t} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var _E=class extends Wb{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(cf.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new RE,this.setRequestHandler(DR,n=>this._oninitialize(n)),this.setNotificationHandler(kR,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(jR,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=cf.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xE(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=HW(this._capabilities,e)}setRequestHandler(e,t){let o=us(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Ao(o)){let s=o;i=s._zod?.def?.value??s.value}else{let s=o;i=s._def?.value??s.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let s=async(l,c)=>{let u=cs(ud,l);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new ce(pe.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=u.data,m=await Promise.resolve(t(l,c));if(d.task){let f=cs(ld,m);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new ce(pe.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let p=cs(Ub,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new ce(pe.InvalidParams,`Invalid tools/call result: ${f}`)}return p.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){F2(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&k2(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:GG.includes(t)?t:PR,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},vb)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(c=>c.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],l=s.some(c=>c.type==="tool_use");if(i){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let c=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==u.size||![...c].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},WR,t):this.request({method:"sampling/createMessage",params:e},GR,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Bb,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Bb,t);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!s.valid)throw new ce(pe.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof ce?a:new ce(pe.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},VR,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var B2=Symbol.for("mcp.completable");function V_(r){return!!r&&typeof r=="object"&&B2 in r}function z2(r){return r[B2]?.complete}var U2;(function(r){r.Completable="McpCompletable"})(U2||(U2={}));var ASe=/^[A-Za-z0-9._-]{1,128}$/;function wSe(r){let e=[];if(r.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(r.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${r.length})`]};if(r.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),r.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(r.startsWith("-")||r.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(r.startsWith(".")||r.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!ASe.test(r)){let t=r.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${t.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function CSe(r,e){if(e.length>0){console.warn(`Tool name validation warning for "${r}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function q_(r){let e=wSe(r);return CSe(r,e.warnings),e.isValid}var ME=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let o={taskSupport:"required",...t.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,o,t._meta,n)}};import{ZodOptional as RSe}from"zod";var PE=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new _E(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new ME(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Ts(Fb)),this.server.assertCanSetRequestHandler(Ts(ud)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Fb,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let o=ad(t.inputSchema);return o?ZR(o,{strictUnions:!0,pipeStrategy:"input"}):xSe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=ad(t.outputSchema);o&&(n.outputSchema=ZR(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(ud,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new ce(pe.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new ce(pe.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,a="createTask"in n.handler;if((i==="required"||i==="optional")&&!a)throw new ce(pe.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new ce(pe.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,e,t);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,s,t);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof ce&&n.code===pe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let i=ad(e.inputSchema)??e.inputSchema,a=await gb(i,t);if(!a.success){let s="error"in a?a.error:"Unknown error",l=yb(s);throw new ce(pe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new ce(pe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=ad(e.outputSchema),i=await gb(o,t.structuredContent);if(!i.success){let a="error"in i?i.error:"Unknown error",s=yb(a);throw new ce(pe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${s}`)}}async executeToolHandler(e,t,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let a={...n,taskStore:n.taskStore};if(e.inputSchema){let s=o;return await Promise.resolve(s.createTask(t,a))}else{let s=o;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=o;return await Promise.resolve(a(t,n))}else{let a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},s=o?await Promise.resolve(i.createTask(o,a)):await Promise.resolve(i.createTask(a)),l=s.task.taskId,c=s.task,u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(m=>setTimeout(m,u));let d=await n.taskStore.getTask(l);if(!d)throw new ce(pe.InternalError,`Task ${l} not found during polling`);c=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Ts(zb)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zb,async e=>{switch(e.params.ref.type){case"ref/prompt":return aW(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return sW(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ce(pe.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new ce(pe.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new ce(pe.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return $f;let i=us(n.argsSchema)?.[e.params.argument.name];if(!V_(i))return $f;let a=z2(i);if(!a)return $f;let s=await a(e.params.argument.value,e.params.context);return H2(s)}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return $f;throw new ce(pe.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return $f;let i=await o(e.params.argument.value,e.params.context);return H2(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Ts(Ob)),this.server.assertCanSetRequestHandler(Ts(Nb)),this.server.assertCanSetRequestHandler(Ts(Lb)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ob,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(t);for(let s of a.resources)o.push({...i.metadata,...s})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Nb,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,n])=>({name:t,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Lb,async(e,t)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ce(pe.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,t)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(n.toString());if(a)return i.readCallback(n,a,t)}throw new ce(pe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Ts(Db)),this.server.assertCanSetRequestHandler(Ts(kb)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Db,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?MSe(t.argsSchema):void 0}))})),this.server.setRequestHandler(kb,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new ce(pe.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new ce(pe.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=ad(n.argsSchema),i=await gb(o,e.params.arguments);if(!i.success){let l="error"in i?i.error:"Unknown error",c=yb(l);throw new ce(pe.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let a=i.data,s=n.callback;return await Promise.resolve(s(a,t))}else{let o=n.callback;return await Promise.resolve(o(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,void 0,t,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,t,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,t,n,o){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,o,i){let a={name:e,title:t,metadata:o,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==n&&(delete this._registeredResources[n],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,o,i){let a={resourceTemplate:n,title:t,metadata:o,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,o,i){let a={title:t,description:n,argsSchema:o===void 0?void 0:Ul(o),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=Ul(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,o&&Object.values(o).some(l=>{let c=l instanceof RSe?l._def?.innerType:l;return V_(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,o,i,a,s,l,c){q_(e);let u={title:t,description:n,inputSchema:$2(o),outputSchema:$2(i),annotations:a,execution:s,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&q_(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Ul(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Ul(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,a;if(typeof t[0]=="string"&&(n=t.shift()),t.length>1){let l=t[0];K_(l)?(o=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!K_(t[0])&&(a=t.shift())):typeof l=="object"&&l!==null&&(a=t.shift())}let s=t[0];return this._createRegisteredTool(e,void 0,n,o,i,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:i,inputSchema:a,outputSchema:s,annotations:l,_meta:c}=t;return this._createRegisteredTool(e,o,i,a,s,l,{taskSupport:"forbidden"},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof t[0]=="string"&&(n=t.shift());let o;t.length>1&&(o=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:a}=t,s=this._createRegisteredPrompt(e,o,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var xSe={type:"object",properties:{}};function j2(r){return r!==null&&typeof r=="object"&&"parse"in r&&typeof r.parse=="function"&&"safeParse"in r&&typeof r.safeParse=="function"}function _Se(r){return"_def"in r||"_zod"in r||j2(r)}function K_(r){return typeof r!="object"||r===null||_Se(r)?!1:Object.keys(r).length===0?!0:Object.values(r).some(j2)}function $2(r){if(r)return K_(r)?Ul(r):r}function MSe(r){let e=us(r);return e?Object.entries(e).map(([t,n])=>{let o=HG(n),i=jG(n);return{name:t,description:o,required:!i}}):[]}function Ts(r){let t=us(r)?.method;if(!t)throw new Error("Schema is missing a method literal");let n=Sb(t);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function H2(r){return{completion:{values:r.slice(0,100),total:r.length,hasMore:r.length>100}}}var $f={completion:{values:[],hasMore:!1}};import W2 from"node:process";var IE=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
4901
4901
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),PSe(t)}clear(){this._buffer=void 0}};function PSe(r){return ZG.parse(JSON.parse(r))}function G2(r){return JSON.stringify(r)+`
4902
- `}var OE=class{constructor(e=W2.stdin,t=W2.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new IE,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=G2(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var V2=!1;function ISe({task:r,logger:e,errorMessage:t}){(async()=>{try{await r()}catch(n){e.warn({err:n},t)}})()}function OSe(r,e,t){for(let n of t)n.addToolToMcpServer(e,r)}function NSe(r,e,t){V2||(V2=!0,ISe({task:async()=>UG(r.project?.rootDir),logger:r.logger,errorMessage:"Failed to clean up old MCP artifacts"}));let n=new PE({name:e.applicationName,version:e.cliVersion},{capabilities:{logging:{},tools:{}}});return OSe(n,r,t),n}function LSe({server:r,logger:e,shutdownHandlers:t=[]}){return[async()=>{try{await r.close()}catch{}},...t.map(n=>async()=>void await n("shutdown",e))]}async function q2({context:r,info:e,tools:t,shutdownHandlers:n}){let o=NSe(r,e,t),i=new OE;for(let a of LSe({server:o,logger:r.logger,shutdownHandlers:n}))dl(a);return await o.connect(i),{server:o,transport:i}}function K2({moduleName:r,existingModuleNames:e,parameterNames:t,defaultParameters:n,parameterEnums:o,moduleInputs:i,testPath:a,startIndex:s,endIndex:l,availableSteps:c,containsNestedModuleStep:u}){if(e.includes(r))throw new Error(`Error: module with the name "${r}" already exists. Please use a different name.`);let d=t??[],m=[...Object.keys(n??{}),...Object.keys(o??{})];for(let y of m)if(!d.includes(y)){let b=d.length?d.join(", "):"none";throw new Error(`Error: Parameter metadata "${y}" is not defined in parameters. Available parameters: ${b}`)}let p=new Set(d);for(let y of Object.keys(i??{}))if(!p.has(y)){let b=p.size?Array.from(p).join(", "):"none";throw new Error(`Error: Module input "${y}" is not defined in parameters. Available parameters: ${b}`)}let f=s??0,h=l??f+1;if(l!==void 0&&s===void 0)throw new Error("Error: startIndex is required when endIndex is provided for extraction.");if(s===void 0)return{stepsToExtract:[],startIndex:f,endIndex:h};if(!a)throw new Error("Error: testPath is required when extracting steps from the test.");if(!c)throw new Error("Error: resolved steps are required to validate module extraction.");if(f<0||f>=c.length)throw new Error(`Error: startIndex ${f} is out of bounds. Test has ${c.length} steps.`);if(h<=f||h>c.length)throw new Error(`Error: endIndex ${h} is out of bounds. Must be between ${f+1} and ${c.length}.`);let g=c.slice(f,h);for(let y of g)if(u(y))throw new Error("Error: Modules cannot be nested. Please select steps that do not include module references.");return{stepsToExtract:g,startIndex:f,endIndex:h}}import{InvalidArgumentError as Y2}from"@commander-js/extra-typings";function tn(r){let e=parseInt(r,10);if(Number.isNaN(e))throw new Y2("Not a number.");return e}function Hf(r){let e=Number.parseFloat(r);if(Number.isNaN(e))throw new Y2("Not a number.");return e}function LE(r){if(!r?.length)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Key=value pair must contain '=': ${t}`);e[t.slice(0,n)]=t.slice(n+1)}return e}function Y_(r){if(!r?.length)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`--parameter-enum pair must contain '=': ${t}`);let o=t.slice(0,n).trim(),i=t.slice(n+1).split(",").map(a=>a.trim()).filter(Boolean);e[o]=i}return e}function NE(r){let e=JSON.parse(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object");let t={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")throw new Error("Expected a JSON object with string values");t[n]=o}return t}function DSe(r,e){let t=r??e?.defaultMethod;if(!t)throw new Error("REQUEST requires --method");let n=Ud.safeParse(t);if(n.success)return n.data;throw new Error(`REQUEST --method must be one of: ${Ud.options.join(", ")}`)}function kSe(r,e){if(r!==void 0){if((e??"json")==="json")return{type:"json",content:r};if(e==="form-urlencoded")return{type:"form-urlencoded",content:NE(r)};throw new Error(`Unsupported request body type: ${e}`)}}function X_(r,e){if(!r.url)throw new Error("REQUEST requires --url");let t=kSe(r.body,r.bodyType);return{url:r.url,method:DSe(r.method,e),...r.headers?{headers:NE(r.headers)}:{},...r.params?{params:NE(r.params)}:{},...t?{body:t}:{},...r.timeoutSeconds!==void 0?{timeout:r.timeoutSeconds}:{}}}var Ujt={CONTAINS:"CONTAINS",EQUALS:"EQUALS",STARTS_WITH:"STARTS_WITH"},Bjt={EXISTS:"EXISTS",VISIBLE:"VISIBLE",ENABLED:"ENABLED",EDITABLE:"EDITABLE",FOCUSED:"FOCUSED"};var FSe=Jf(Z_(),1);import{Command as Jjt,Option as Zjt}from"@commander-js/extra-typings";var cGt=`Refer to the data returned from the ${$i} tool for the proper step schema.`;import pGt from"dedent";var gGt={CLICK:bt.CLICK,TYPE:bt.TYPE,SELECT_OPTION:"Select an option from a native HTML select element.",HOVER:"Hover over an element on the page. Automatically scrolls the element into view, so can be used as a 'scroll to'.",BLUR:bt.BLUR,ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks. Primarily useful if the user asks to verify a specific condition on an element available in the a11y tree. Otherwise, prefer AI_ASSERTION.",DRAG:bt.DRAG,PRESS:bt.PRESS,NAVIGATE:bt.NAVIGATE,NEW_TAB:bt.NEW_TAB,SCROLL:"Scroll by a specified amount. Use delta-x for horizontal, delta-y for vertical.",WAIT:"Hardcoded wait. Prefer AI_ASSERTION for more stability. Use WAITs only when you know an operation will take a long time such as 5 minutes.",AI_ASSERTION:bt.AI_ASSERTION,PAGE_CHECK:"Assert on the active page body's innerHTML content. Prefer AI_ASSERTION for broader and more stable checks.",COPY:bt.COPY,PASTE:bt.PASTE,REQUEST:bt.REQUEST,GRAPHQL_REQUEST:bt.GRAPHQL_REQUEST,COOKIE:bt.COOKIE,LOCAL_STORAGE:bt.LOCAL_STORAGE,JAVASCRIPT:bt.JAVASCRIPT,AI_EXTRACT:bt.AI_EXTRACT,GO_BACK:bt.GO_BACK,GO_FORWARD:bt.GO_FORWARD,REFRESH:bt.REFRESH,SWITCH_TAB:bt.TAB,WAIT_FOR_URL:bt.WAIT_FOR_URL,MODULE:bt.RESOLVED_MODULE,AI_ACTION_DYNAMIC:bt.AI_ACTION_DYNAMIC,SET_HEADER:bt.SET_HEADER,MOCK_ROUTE:bt.MOCK_ROUTE,REMOVE_ROUTE_MOCK:bt.REMOVE_ROUTE_MOCK,FILE_UPLOAD:"Upload a file from local disk or a publicly accessible URL. This command registers a handler for the next file chooser event that occurs on the active page.",DIALOG:bt.DIALOG,MOUSE_DRAG:"Drag the mouse by pixel deltas. Useful for sliders, scrubbers, color pickers, and canvas controls.",CONDITIONAL:bt.CONDITIONAL};import USe from"dedent";function X2(){return USe`
4902
+ `}var OE=class{constructor(e=W2.stdin,t=W2.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new IE,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=G2(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var V2=!1;function ISe({task:r,logger:e,errorMessage:t}){(async()=>{try{await r()}catch(n){e.warn({err:n},t)}})()}function OSe(r,e,t){for(let n of t)n.addToolToMcpServer(e,r)}function NSe(r,e,t){V2||(V2=!0,ISe({task:async()=>UG(r.project?.rootDir),logger:r.logger,errorMessage:"Failed to clean up old MCP artifacts"}));let n=new PE({name:e.applicationName,version:e.cliVersion},{capabilities:{logging:{},tools:{}}});return OSe(n,r,t),n}function LSe({server:r,logger:e,shutdownHandlers:t=[]}){return[async()=>{try{await r.close()}catch{}},...t.map(n=>async()=>void await n("shutdown",e))]}async function q2({context:r,info:e,tools:t,shutdownHandlers:n}){let o=NSe(r,e,t),i=new OE;for(let a of LSe({server:o,logger:r.logger,shutdownHandlers:n}))dl(a);return await o.connect(i),{server:o,transport:i}}function K2({moduleName:r,existingModuleNames:e,parameterNames:t,defaultParameters:n,parameterEnums:o,moduleInputs:i,testPath:a,startIndex:s,endIndex:l,availableSteps:c,containsNestedModuleStep:u}){if(e.includes(r))throw new Error(`Error: module with the name "${r}" already exists. Please use a different name.`);let d=t??[],m=[...Object.keys(n??{}),...Object.keys(o??{})];for(let y of m)if(!d.includes(y)){let b=d.length?d.join(", "):"none";throw new Error(`Error: Parameter metadata "${y}" is not defined in parameters. Available parameters: ${b}`)}let p=new Set(d);for(let y of Object.keys(i??{}))if(!p.has(y)){let b=p.size?Array.from(p).join(", "):"none";throw new Error(`Error: Module input "${y}" is not defined in parameters. Available parameters: ${b}`)}let f=s??0,h=l??f+1;if(l!==void 0&&s===void 0)throw new Error("Error: startIndex is required when endIndex is provided for extraction.");if(s===void 0)return{stepsToExtract:[],startIndex:f,endIndex:h};if(!a)throw new Error("Error: testPath is required when extracting steps from the test.");if(!c)throw new Error("Error: resolved steps are required to validate module extraction.");if(f<0||f>=c.length)throw new Error(`Error: startIndex ${f} is out of bounds. Test has ${c.length} steps.`);if(h<=f||h>c.length)throw new Error(`Error: endIndex ${h} is out of bounds. Must be between ${f+1} and ${c.length}.`);let g=c.slice(f,h);for(let y of g)if(u(y))throw new Error("Error: Modules cannot be nested. Please select steps that do not include module references.");return{stepsToExtract:g,startIndex:f,endIndex:h}}import{InvalidArgumentError as Y2}from"@commander-js/extra-typings";function tn(r){let e=parseInt(r,10);if(Number.isNaN(e))throw new Y2("Not a number.");return e}function Hf(r){let e=Number.parseFloat(r);if(Number.isNaN(e))throw new Y2("Not a number.");return e}function LE(r){if(!r?.length)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Key=value pair must contain '=': ${t}`);e[t.slice(0,n)]=t.slice(n+1)}return e}function Y_(r){if(!r?.length)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`--parameter-enum pair must contain '=': ${t}`);let o=t.slice(0,n).trim(),i=t.slice(n+1).split(",").map(a=>a.trim()).filter(Boolean);e[o]=i}return e}function NE(r){let e=JSON.parse(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object");let t={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")throw new Error("Expected a JSON object with string values");t[n]=o}return t}function DSe(r,e){let t=r??e?.defaultMethod;if(!t)throw new Error("REQUEST requires --method");let n=Ud.safeParse(t);if(n.success)return n.data;throw new Error(`REQUEST --method must be one of: ${Ud.options.join(", ")}`)}function kSe(r,e){if(r!==void 0){if((e??"json")==="json")return{type:"json",content:r};if(e==="form-urlencoded")return{type:"form-urlencoded",content:NE(r)};throw new Error(`Unsupported request body type: ${e}`)}}function X_(r,e){if(!r.url)throw new Error("REQUEST requires --url");let t=kSe(r.body,r.bodyType);return{url:r.url,method:DSe(r.method,e),...r.headers?{headers:NE(r.headers)}:{},...r.params?{params:NE(r.params)}:{},...t?{body:t}:{},...r.timeoutSeconds!==void 0?{timeout:r.timeoutSeconds}:{}}}var zjt={CONTAINS:"CONTAINS",EQUALS:"EQUALS",STARTS_WITH:"STARTS_WITH"},$jt={EXISTS:"EXISTS",VISIBLE:"VISIBLE",ENABLED:"ENABLED",EDITABLE:"EDITABLE",FOCUSED:"FOCUSED"};var FSe=Jf(Z_(),1);import{Command as Qjt,Option as eGt}from"@commander-js/extra-typings";var dGt=`Refer to the data returned from the ${$i} tool for the proper step schema.`;import hGt from"dedent";var SGt={CLICK:bt.CLICK,TYPE:bt.TYPE,SELECT_OPTION:"Select an option from a native HTML select element.",HOVER:"Hover over an element on the page. Automatically scrolls the element into view, so can be used as a 'scroll to'.",BLUR:bt.BLUR,ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks. Primarily useful if the user asks to verify a specific condition on an element available in the a11y tree. Otherwise, prefer AI_ASSERTION.",DRAG:bt.DRAG,PRESS:bt.PRESS,NAVIGATE:bt.NAVIGATE,NEW_TAB:bt.NEW_TAB,SCROLL:"Scroll by a specified amount. Use delta-x for horizontal, delta-y for vertical.",WAIT:"Hardcoded wait. Prefer AI_ASSERTION for more stability. Use WAITs only when you know an operation will take a long time such as 5 minutes.",AI_ASSERTION:bt.AI_ASSERTION,PAGE_CHECK:"Assert on the active page body's innerHTML content. Prefer AI_ASSERTION for broader and more stable checks.",COPY:bt.COPY,PASTE:bt.PASTE,REQUEST:bt.REQUEST,GRAPHQL_REQUEST:bt.GRAPHQL_REQUEST,COOKIE:bt.COOKIE,LOCAL_STORAGE:bt.LOCAL_STORAGE,JAVASCRIPT:bt.JAVASCRIPT,AI_EXTRACT:bt.AI_EXTRACT,GO_BACK:bt.GO_BACK,GO_FORWARD:bt.GO_FORWARD,REFRESH:bt.REFRESH,SWITCH_TAB:bt.TAB,WAIT_FOR_URL:bt.WAIT_FOR_URL,MODULE:bt.RESOLVED_MODULE,AI_ACTION_DYNAMIC:bt.AI_ACTION_DYNAMIC,SET_HEADER:bt.SET_HEADER,MOCK_ROUTE:bt.MOCK_ROUTE,REMOVE_ROUTE_MOCK:bt.REMOVE_ROUTE_MOCK,FILE_UPLOAD:"Upload a file from local disk or a publicly accessible URL. This command registers a handler for the next file chooser event that occurs on the active page.",DIALOG:bt.DIALOG,MOUSE_DRAG:"Drag the mouse by pixel deltas. Useful for sliders, scrubbers, color pickers, and canvas controls.",CONDITIONAL:bt.CONDITIONAL};import USe from"dedent";function X2(){return USe`
4903
4903
  # Android Mobile Agent Step Schema (CLI-style)
4904
4904
 
4905
4905
  Steps are specified as CLI-style strings: \`--step-type <type> [options]\`.
@@ -5021,13 +5021,13 @@ The "Installed apps" list may still include default or system packages; it is a
5021
5021
  `)}import{Readable as mEe}from"node:stream";import pEe from"open";import Zo,{dirname as fEe,resolve as hEe}from"path";import{pipeline as gEe}from"stream/promises";import{fileURLToPath as xM}from"url";import lM from"fs";import zE from"path";import{cwd as Ibe}from"process";async function cM({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,labels:a,logger:s,quarantinedTestsMetadata:l}){let c=new Set;if(r&&r.length>0){let d=r.some(p=>lM.existsSync(p)),m=Ibe();d?(m!==t.rootDir&&s.warn(`The current working directory ('${m}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
5022
5022
  - ${r.join(`
5023
5023
  - `)}
5024
- `),r.forEach(p=>{if(!lM.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let f,h;try{f=lM.statSync(p),h=f.isDirectory()}catch(y){s.warn({err:y},`Skipping path ${p} because it cannot be read`);return}let g=zE.resolve(p);Object.values(e.mobileTests).filter(y=>h?y.fullFilePath.startsWith(g):y.fullFilePath===g).forEach(y=>{c.add(y.fullFilePath)})})):(s.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(f=>p.relativePath.includes(f))&&c.add(p.fullFilePath)}))}else{!n&&!await ry("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let d=Object.values(e.mobileTests);s.info(`Reading all ${d.length} mobile tests in the project from local disk.`),d.forEach(m=>{c.add(m.fullFilePath)})}for(let d of Array.from(c)){let m=zE.relative(t.rootDir,d);o&&!o.some(p=>new RegExp(p).test(m))&&c.delete(d),i&&i.some(p=>new RegExp(p).test(m))&&c.delete(d)}return(await Promise.all(Array.from(c).map(async d=>{try{let m=zE.relative(t.rootDir,d),p=await Er(d,s,e),f=zE.basename(d,".test.yaml");if(p.disabled)return null;if(a&&a.length>0){let g=p.labels||[];if(!a.some(b=>g.includes(b)))return null}let h={id:p.id,name:f,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,fullFilePath:d,relativeFilePath:m,quarantined:!!l[p.id],quarantinedMetadata:l[p.id],labels:p.labels};switch(p.platform){case"ANDROID":return{...h,platform:"ANDROID",steps:p.steps};case"IOS":return{...h,platform:"IOS",steps:p.steps};default:return(y=>{throw new Error("You missed a case in the switch above")})(p)}}catch(m){s.error(`Failed to read and resolve mobile test at '${d}': ${m}`),process.exit(1)}}))).filter(d=>!!d)}import{InvalidArgumentError as Vf,Option as ut}from"@commander-js/extra-typings";import{z as Obe}from"zod";var GK=58890;function vs(r){let e=parseInt(r,10);if(isNaN(e))throw new Vf("Not a number.");return e}var WK=new ut("--port <port>",`Port to run the local app on. Defaults to ${GK}.`).env("PORT").default(GK).argParser(vs),As=new ut("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Vf("API key is required.");return r}).makeOptionMandatory(),qf=new ut("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),uM=new ut("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),ws=new ut("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return Obe.string().url().parse(r),r}catch{throw new Vf("Not a valid URL.")}}),dM=new ut("-y, --yes","Skip all confirmation prompts.").env("CI"),mM=new ut("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times."),$E=new ut("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),HE=new ut("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1}),pM=new ut("--tag <tag>","Tag identifier for the asset."),VK=new ut("--channel <channel>","Channel name for the asset."),fM=new ut("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),qK=new ut("--tag <tag>","Tag identifier for the asset.").makeOptionMandatory(),KK=new ut("--platform <platform>","Mobile platform for the asset.");function YK(r){if(!r)return"ANDROID";switch(r.toLowerCase()){case"android":return"ANDROID";case"ios":return"IOS";default:throw new Vf('Invalid platform. Valid options are "android" and "ios".')}}var XK=new ut("--env <env>","Environment to run all tests in (overrides test-level configuration)."),JK=new ut("--android-home <androidHome>","Path to the Android SDK root. Sets ANDROID_HOME for this command."),ZK=new ut("--java-home <javaHome>","Path to the Java home directory. Sets JAVA_HOME for this command."),Kf="closest",QK=new ut("--region <region>",`Region to run all tests in (overrides all other configuration). Valid values: ${Object.values(Js).join(", ")}, ${Kf}, ${Object.values(ci).join(", ")}.`),e4=new ut("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),t4=new ut("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),r4=new ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(vs),n4=new ut("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=vs(r);if(e<1)throw new Vf("Shard index must be greater than 0.");return e}),o4=new ut("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(vs),hM=new ut("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),gM=new ut("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),yM=new ut("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),i4=new ut("--upload-results","Upload test results to Momentic Cloud.").default(!1),SM=new ut("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),a4=new ut("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),s4=new ut("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(vs),l4=new ut("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(am)),c4=new ut("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),u4=new ut("--name <name>","A name to associate with this run for easier identification in the Momentic dashboard."),d4=new ut("--session-idle-timeout-minutes <timeoutMinutes>","Session idle timeout in minutes. When set, MCP sessions that remain idle for this duration will be automatically terminated. Defaults to 5 minutes.").env("MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES").argParser(vs);import{randomUUID as aEe}from"crypto";import{existsSync as sEe}from"fs";import{randomUUID as Lbe}from"crypto";import Dbe from"zod";var m4={prepareRunParams:async({runTracer:r,metadata:{orgId:e},fixtures:{logger:t,apiClient:n,mobileGenerator:o,storage:i,cacheStorage:a,usageTracker:s,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u},inputs:{channel:d,tag:m,project:p,testDefinition:f},env:{envName:h,envVariables:g},settings:{emulatorSettings:y,aiSettings:b},options:{logLevel:E,localAvdId:v,localApkPath:w,region:L}})=>{let I=Math.floor(Math.random()*1e4)+4e4,A=await zo(I,"appium"),_=Fc.or(Dbe.literal(Kf)).optional().parse(L??y.region),O=_==="local",k;if(O){let{avdId:B,apkFilePath:Z,apkFilePathSource:ie}=Hh({overrideAvdId:v,overrideApkFilePath:w,emulatorSettings:y,defaultApkFilePath:f.settings?.defaultApkFilePath,envVariables:g}),se=sS({apkFilePath:Z,source:ie});if(!B)throw new Error(`An AVD ID is required when using a local region. Provide --local-avd-id, configure a default local AVD ID on the test's settings, or set the ${ji} key on the environment.`);k={avdId:B,apkFilePath:se}}else k={region:_==="closest"?void 0:_,apkToInstall:d?{channel:d,tag:m}:void 0,osVersion:y.remoteEmulatorSettings?.androidVersion??Dh};let D=Lbe(),j=t.child({runAttemptId:D}),$=await Du({apiClient:n,logger:t,driverLogLevel:E,creationOpts:k,callbacks:{onStatusUpdate:B=>{t.debug({status:B},"Emulator status update")},onHeartbeatFailure:()=>{let B="Appium heartbeat connection lost \u2014 possible ADB tunnel/emulator failure";P.warn(B)},onHeartbeatRestored:()=>{let B="Appium heartbeat connection restored";P.info(B)},onLimbarConnectionStateChange:B=>{B==="disconnected"?P.warn("Emulator websocket connection lost. Emulator may be unavailable."):(B==="reconnecting"||B==="connecting")&&P.info("Emulator websocket is reconnecting...")}},appiumPort:A,orgId:e,sessionId:D}),xe;try{let B=await r.startAttempt({emulatorName:$.emulatorName,runAttemptId:D,assetDetails:{avdId:"avdId"in k?k.avdId:void 0,tag:"apkToInstall"in k?k.apkToInstall?.tag:void 0,channel:"apkToInstall"in k?k.apkToInstall?.channel:void 0}});j=j.child(B.loggerBindings||{}),xe=await aS({driver:$.driver,onLogs:we=>{B.appendLogs(we)}});let Z=new io({variablesFromEnvironment:g,envName:h,testName:f.name}),ie="limbarClient"in $?$.limbarClient:void 0,se="playwrightDevice"in $?$.playwrightDevice:void 0,Pe=await ss.init({driver:$.driver,generator:o,logger:j,limbarClient:ie,playwrightDevice:se,orgId:e,adbPort:$.adbPort,options:{emulator:{...y,browserSettings:p.config.browser}},aiSettings:b,fixtures:{storage:i,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u,testContext:Z}});return{platform:"ANDROID",tracer:B,fixtures:{controller:Pe,logger:j,cacheStorage:a,usageTracker:s},work:{state:{failureRecoveryDisabled:b.failureRecovery===!1,failureRecoveryAttempts:0}},inputs:{testName:f.name,steps:f.steps,orgId:e,testMetadata:f},callbacks:{},cleanup:async()=>{await xe?.(),await $.cleanup(),await Pe.cleanup()}}}catch(B){throw await xe?.(),await $.cleanup(),B}}};import{randomUUID as kbe}from"crypto";import Fbe from"zod";var p4={prepareRunParams:async({runTracer:r,metadata:{orgId:e},fixtures:{logger:t,apiClient:n,mobileGenerator:o,storage:i,cacheStorage:a,usageTracker:s,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u},inputs:{channel:d,tag:m,project:p,testDefinition:f},env:{envName:h,envVariables:g},settings:{emulatorSettings:y,aiSettings:b},options:{logLevel:E,region:v}})=>{let w=Math.floor(Math.random()*1e4)+4e4,L=await zo(w,"appium"),I=Fc.or(Fbe.literal(Kf)).optional().parse(v??y.region);if(I==="local")throw new Error("Local region is not supported for iOS tests, as we do not support local iOS emulators.");let _={region:I==="closest"?void 0:I,appToInstall:d?{channel:d,tag:m}:void 0},O=kbe(),k=t.child({runAttemptId:O}),D=await GS({apiClient:n,logger:t,driverLogLevel:E,creationOpts:_,callbacks:{onStatusUpdate:j=>{t.debug({status:j},"Emulator status update")},onHeartbeatFailure:()=>{P.warn("Appium heartbeat connection lost \u2014 possible emulator failure")},onHeartbeatRestored:()=>{P.info("Appium heartbeat connection restored")},onLimbarConnectionStateChange:j=>{j==="disconnected"?P.warn("Emulator websocket connection lost. Emulator may be unavailable."):(j==="reconnecting"||j==="connecting")&&P.info("Emulator websocket is reconnecting...")}},appiumPort:L,orgId:e,sessionId:O});try{let j=await r.startAttempt({emulatorName:D.emulatorName,runAttemptId:O});k=k.child(j.loggerBindings||{});let $=new io({variablesFromEnvironment:g,envName:h,testName:f.name}),xe=await Zu.init({driver:D.driver,generator:o,logger:k,limbarClient:D.limbarClient,orgId:e,options:{emulator:{...y,browserSettings:p.config.browser}},aiSettings:b,fixtures:{storage:i,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u,testContext:$}});return{platform:"IOS",tracer:j,fixtures:{controller:xe,logger:k,cacheStorage:a,usageTracker:s},work:{state:{failureRecoveryDisabled:b.failureRecovery===!1,failureRecoveryAttempts:0}},inputs:{testName:f.name,steps:f.steps,orgId:e,testMetadata:f},callbacks:{},cleanup:async()=>{await D.cleanup(),await xe.cleanup()}}}catch(j){throw await D.cleanup(),j}}};import{dirname as Hbe}from"path";import{cloneDeep as Ube}from"lodash-es";import{debounce as Bbe}from"ts-debounce";var Zl="0.59.0";function zbe(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function $be(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var bM=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.parentTracer=i;this.orgId=a;this.interactionTracer=new Eo,Yr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}recordStepDuration(e){let{durationMs:t,step:n}=e;if(!ag(n))return;let o=ig(n);gt.distribution("test_step_duration",t,[`type:${o}`,"platform:mobile","executor:cli",`orgId:${this.orgId}`])}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.jpeg`,contents:n})}attachBeforeXmlSnapshot(e){let{snapshotId:t,xml:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.xml`,contents:n})}attachAfterXmlSnapshot(e){let{snapshotId:t,xml:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.xml`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:$be(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}},Md=class{constructor(e,t,n,o,i){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.orgId=i}children=[];finished=!1;async getScreenshot(e){return this.diskStorage.readFile(`${La}/${e}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new bM(this.keepalive,this.testId,this.testName,this.diskStorage,this,this.orgId);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:zbe(e.status),finishedAt:e.finishedAt}))))}},EM=class{constructor(e,t,n,o,i,a,s,l){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.orgId=s;this.assetDetails=l;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat"),this.resourceUsageStream=this.diskStorage.createFileStream(`${La}/resource-usage.ndjson`),this.resourceUsageSampler=T0({keepSamples:!1,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
5024
+ `),r.forEach(p=>{if(!lM.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let f,h;try{f=lM.statSync(p),h=f.isDirectory()}catch(y){s.warn({err:y},`Skipping path ${p} because it cannot be read`);return}let g=zE.resolve(p);Object.values(e.mobileTests).filter(y=>h?y.fullFilePath.startsWith(g):y.fullFilePath===g).forEach(y=>{c.add(y.fullFilePath)})})):(s.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(f=>p.relativePath.includes(f))&&c.add(p.fullFilePath)}))}else{!n&&!await ry("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let d=Object.values(e.mobileTests);s.info(`Reading all ${d.length} mobile tests in the project from local disk.`),d.forEach(m=>{c.add(m.fullFilePath)})}for(let d of Array.from(c)){let m=zE.relative(t.rootDir,d);o&&!o.some(p=>new RegExp(p).test(m))&&c.delete(d),i&&i.some(p=>new RegExp(p).test(m))&&c.delete(d)}return(await Promise.all(Array.from(c).map(async d=>{try{let m=zE.relative(t.rootDir,d),p=await Er(d,s,e),f=zE.basename(d,".test.yaml");if(p.disabled)return null;if(a&&a.length>0){let g=p.labels||[];if(!a.some(b=>g.includes(b)))return null}let h={id:p.id,name:f,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,fullFilePath:d,relativeFilePath:m,quarantined:!!l[p.id],quarantinedMetadata:l[p.id],labels:p.labels};switch(p.platform){case"ANDROID":return{...h,platform:"ANDROID",steps:p.steps};case"IOS":return{...h,platform:"IOS",steps:p.steps};default:return(y=>{throw new Error("You missed a case in the switch above")})(p)}}catch(m){s.error(`Failed to read and resolve mobile test at '${d}': ${m}`),process.exit(1)}}))).filter(d=>!!d)}import{InvalidArgumentError as Vf,Option as ut}from"@commander-js/extra-typings";import{z as Obe}from"zod";var GK=58890;function vs(r){let e=parseInt(r,10);if(isNaN(e))throw new Vf("Not a number.");return e}var WK=new ut("--port <port>",`Port to run the local app on. Defaults to ${GK}.`).env("PORT").default(GK).argParser(vs),As=new ut("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Vf("API key is required.");return r}).makeOptionMandatory(),qf=new ut("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),uM=new ut("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),ws=new ut("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return Obe.string().url().parse(r),r}catch{throw new Vf("Not a valid URL.")}}),dM=new ut("-y, --yes","Skip all confirmation prompts.").env("CI"),mM=new ut("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times."),$E=new ut("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),HE=new ut("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1}),pM=new ut("--tag <tag>","Tag identifier for the asset."),VK=new ut("--channel <channel>","Channel name for the asset."),fM=new ut("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),qK=new ut("--tag <tag>","Tag identifier for the asset.").makeOptionMandatory(),KK=new ut("--platform <platform>","Mobile platform for the asset.");function YK(r){if(!r)return"ANDROID";switch(r.toLowerCase()){case"android":return"ANDROID";case"ios":return"IOS";default:throw new Vf('Invalid platform. Valid options are "android" and "ios".')}}var XK=new ut("--env <env>","Environment to run all tests in (overrides test-level configuration)."),JK=new ut("--android-home <androidHome>","Path to the Android SDK root. Sets ANDROID_HOME for this command."),ZK=new ut("--java-home <javaHome>","Path to the Java home directory. Sets JAVA_HOME for this command."),Kf="closest",QK=new ut("--region <region>",`Region to run all tests in (overrides all other configuration). Valid values: ${Object.values(Js).join(", ")}, ${Kf}, ${Object.values(ci).join(", ")}.`),e4=new ut("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),t4=new ut("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),r4=new ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(vs),n4=new ut("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=vs(r);if(e<1)throw new Vf("Shard index must be greater than 0.");return e}),o4=new ut("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(vs),hM=new ut("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),gM=new ut("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),yM=new ut("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),i4=new ut("--upload-results","Upload test results to Momentic Cloud.").default(!1),SM=new ut("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),a4=new ut("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),s4=new ut("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(vs),l4=new ut("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(am)),c4=new ut("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),u4=new ut("--name <name>","A name to associate with this run for easier identification in the Momentic dashboard."),d4=new ut("--session-idle-timeout-minutes <timeoutMinutes>","Session idle timeout in minutes. When set, MCP sessions that remain idle for this duration will be automatically terminated. Defaults to 5 minutes.").env("MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES").argParser(vs);import{randomUUID as aEe}from"crypto";import{existsSync as sEe}from"fs";import{randomUUID as Lbe}from"crypto";import Dbe from"zod";var m4={prepareRunParams:async({runTracer:r,metadata:{orgId:e},fixtures:{logger:t,apiClient:n,mobileGenerator:o,storage:i,cacheStorage:a,usageTracker:s,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u},inputs:{channel:d,tag:m,project:p,testDefinition:f},env:{envName:h,envVariables:g},settings:{emulatorSettings:y,aiSettings:b},options:{logLevel:E,localAvdId:v,localApkPath:w,region:L}})=>{let I=Math.floor(Math.random()*1e4)+4e4,A=await zo(I,"appium"),_=Fc.or(Dbe.literal(Kf)).optional().parse(L??y.region),O=_==="local",k;if(O){let{avdId:B,apkFilePath:Z,apkFilePathSource:ie}=Hh({overrideAvdId:v,overrideApkFilePath:w,emulatorSettings:y,defaultApkFilePath:f.settings?.defaultApkFilePath,envVariables:g}),se=sS({apkFilePath:Z,source:ie});if(!B)throw new Error(`An AVD ID is required when using a local region. Provide --local-avd-id, configure a default local AVD ID on the test's settings, or set the ${ji} key on the environment.`);k={avdId:B,apkFilePath:se}}else k={region:_==="closest"?void 0:_,apkToInstall:d?{channel:d,tag:m}:void 0,osVersion:y.remoteEmulatorSettings?.androidVersion??Dh};let D=Lbe(),j=t.child({runAttemptId:D}),$=await Du({apiClient:n,logger:t,driverLogLevel:E,creationOpts:k,callbacks:{onStatusUpdate:B=>{t.debug({status:B},"Emulator status update")},onHeartbeatFailure:()=>{let B="Appium heartbeat connection lost \u2014 possible ADB tunnel/emulator failure";P.warn(B)},onHeartbeatRestored:()=>{let B="Appium heartbeat connection restored";P.info(B)},onLimbarConnectionStateChange:B=>{B==="disconnected"?P.warn("Emulator websocket connection lost. Emulator may be unavailable."):(B==="reconnecting"||B==="connecting")&&P.info("Emulator websocket is reconnecting...")}},appiumPort:A,orgId:e,sessionId:D}),xe;try{let B=await r.startAttempt({emulatorName:$.emulatorName,runAttemptId:D,assetDetails:{avdId:"avdId"in k?k.avdId:void 0,tag:"apkToInstall"in k?k.apkToInstall?.tag:void 0,channel:"apkToInstall"in k?k.apkToInstall?.channel:void 0}});j=j.child(B.loggerBindings||{}),xe=await aS({driver:$.driver,onLogs:we=>{B.appendLogs(we)}});let Z=new io({variablesFromEnvironment:g,envName:h,testName:f.name}),ie="limbarClient"in $?$.limbarClient:void 0,se="playwrightDevice"in $?$.playwrightDevice:void 0,Pe=await ss.init({driver:$.driver,generator:o,logger:j,limbarClient:ie,playwrightDevice:se,orgId:e,adbPort:$.adbPort,options:{emulator:{...y,browserSettings:p.config.browser}},aiSettings:b,fixtures:{storage:i,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u,testContext:Z}});return{platform:"ANDROID",tracer:B,fixtures:{controller:Pe,logger:j,cacheStorage:a,usageTracker:s},work:{state:{failureRecoveryDisabled:b.failureRecovery===!1,failureRecoveryAttempts:0}},inputs:{testName:f.name,steps:f.steps,orgId:e,testMetadata:f},callbacks:{},cleanup:async()=>{await xe?.(),await $.cleanup(),await Pe.cleanup()}}}catch(B){throw await xe?.(),await $.cleanup(),B}}};import{randomUUID as kbe}from"crypto";import Fbe from"zod";var p4={prepareRunParams:async({runTracer:r,metadata:{orgId:e},fixtures:{logger:t,apiClient:n,mobileGenerator:o,storage:i,cacheStorage:a,usageTracker:s,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u},inputs:{channel:d,tag:m,project:p,testDefinition:f},env:{envName:h,envVariables:g},settings:{emulatorSettings:y,aiSettings:b},options:{logLevel:E,region:v}})=>{let w=Math.floor(Math.random()*1e4)+4e4,L=await zo(w,"appium"),I=Fc.or(Fbe.literal(Kf)).optional().parse(v??y.region);if(I==="local")throw new Error("Local region is not supported for iOS tests, as we do not support local iOS emulators.");let _={region:I==="closest"?void 0:I,appToInstall:d?{channel:d,tag:m}:void 0},O=kbe(),k=t.child({runAttemptId:O}),D=await GS({apiClient:n,logger:t,driverLogLevel:E,creationOpts:_,callbacks:{onStatusUpdate:j=>{t.debug({status:j},"Emulator status update")},onHeartbeatFailure:()=>{P.warn("Appium heartbeat connection lost \u2014 possible emulator failure")},onHeartbeatRestored:()=>{P.info("Appium heartbeat connection restored")},onLimbarConnectionStateChange:j=>{j==="disconnected"?P.warn("Emulator websocket connection lost. Emulator may be unavailable."):(j==="reconnecting"||j==="connecting")&&P.info("Emulator websocket is reconnecting...")}},appiumPort:L,orgId:e,sessionId:O});try{let j=await r.startAttempt({emulatorName:D.emulatorName,runAttemptId:O});k=k.child(j.loggerBindings||{});let $=new io({variablesFromEnvironment:g,envName:h,testName:f.name}),xe=await Zu.init({driver:D.driver,generator:o,logger:k,limbarClient:D.limbarClient,orgId:e,options:{emulator:{...y,browserSettings:p.config.browser}},aiSettings:b,fixtures:{storage:i,browserEnricher:l,browserGenerator:c,localCodeEvalTools:u,testContext:$}});return{platform:"IOS",tracer:j,fixtures:{controller:xe,logger:k,cacheStorage:a,usageTracker:s},work:{state:{failureRecoveryDisabled:b.failureRecovery===!1,failureRecoveryAttempts:0}},inputs:{testName:f.name,steps:f.steps,orgId:e,testMetadata:f},callbacks:{},cleanup:async()=>{await D.cleanup(),await xe.cleanup()}}}catch(j){throw await D.cleanup(),j}}};import{dirname as Hbe}from"path";import{cloneDeep as Ube}from"lodash-es";import{debounce as Bbe}from"ts-debounce";var Zl="0.59.1";function zbe(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function $be(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var bM=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.parentTracer=i;this.orgId=a;this.interactionTracer=new Eo,Yr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}recordStepDuration(e){let{durationMs:t,step:n}=e;if(!ag(n))return;let o=ig(n);gt.distribution("test_step_duration",t,[`type:${o}`,"platform:mobile","executor:cli",`orgId:${this.orgId}`])}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.jpeg`,contents:n})}attachBeforeXmlSnapshot(e){let{snapshotId:t,xml:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.xml`,contents:n})}attachAfterXmlSnapshot(e){let{snapshotId:t,xml:n}=e;this.diskStorage.storeFile({name:`${La}/${t}.xml`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:$be(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}},Md=class{constructor(e,t,n,o,i){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.orgId=i}children=[];finished=!1;async getScreenshot(e){return this.diskStorage.readFile(`${La}/${e}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new bM(this.keepalive,this.testId,this.testName,this.diskStorage,this,this.orgId);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:zbe(e.status),finishedAt:e.finishedAt}))))}},EM=class{constructor(e,t,n,o,i,a,s,l){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.orgId=s;this.assetDetails=l;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat"),this.resourceUsageStream=this.diskStorage.createFileStream(`${La}/resource-usage.ndjson`),this.resourceUsageSampler=T0({keepSamples:!1,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
5025
5025
  `)}})}finished=!1;children=[];logStream;resourceUsageStream;resourceUsageSampler;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
5026
5026
  `);this.logStream.write(t+`
5027
- `)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,assetDetails:this.assetDetails,finishedAt:new Date,results:nS(o,t),beforeResults:i?nS(i,t):void 0,afterResults:a?nS(a,t):void 0};await Promise.all(this.children.map(l=>l.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}try{this.resourceUsageSampler.stop(),this.resourceUsageStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}async startMainStepList(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}async startAfterStepList(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${La}/${t}.jpeg`)}},TM=class{constructor(e,t,n,o,i,a,s,l){this.client=e;this.testId=t;this.testName=n;this.platform=o;this.runId=i;this.metadata=a;this.diskStorage=s;this.orgId=l}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){let{runAttemptId:t}=e;this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let n=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),o={id:t,schemaVersion:Sa,runAttemptSchemaVersion:l0,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=Bbe(async()=>{await this.client.extendEmulatorTtl(this.platform,e.emulatorName)},3e4,{maxWait:6e4}),a=new EM(()=>void i(),this.testId,this.testName,t,o,n,this.orgId,e.assetDetails);return this.children.push(a),a}},jE=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a,suiteName:s}){let l={...i,suiteName:s,id:t,trigger:An.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Zl,labels:a??[]},c=new Op(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,directory:e.directory,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:Zl,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:nm(e.platform),aiSettings:e.aiSettings};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new TM(this.client,e.testId,e.testName,e.platform,e.runId,n,t,this.orgId);return this.children.push(o),o}};function f4(r){return{platform:r.platform,originalSteps:{steps:Ube(r.steps),beforeSteps:void 0,afterSteps:void 0}}}async function vM(r){let{inputs:e,fixtures:t,metadata:n}=r,{tracer:o,logger:i}=t,{runId:a}=n,{platform:s,testDefinition:l,project:c}=e,u=new Date,d=await o.startRun({...f4(l),logger:i,testId:l.id,testName:l.name,directory:Hbe(l.relativeFilePath),runId:a,testDescription:l.description,testLabels:l.labels,schemaVersion:l.schemaVersion,quarantined:l.quarantined,quarantinedReason:l.quarantinedMetadata?.quarantinedReason,aiSettings:c.config.ai}),m=i.child(d.loggerBindings||{}),p=1+(l.settings?.retries??c.config.retries??1);for(let f=0;f<p;f++){let h=new Date,g=await jbe({...r,runTracer:d,fixtures:{...t,logger:m},constants:{attemptNumber:f,totalAttempts:p}}),y=new Date;if(g.status!=="FAILED")return await d.finish({logger:m,status:g.status,failureRecoveryDetails:g.failureRecoveryDetails,finishedAt:y}),{...g,testMetadata:l,platformType:nm(s),steps:l.steps,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,runId:a,attempts:f+1,filePath:l.relativeFilePath,quarantined:l.quarantined,quarantinedMetadata:l.quarantinedMetadata,status:g.status};if(f!==p-1){m.warn("Retrying failed mobile run");continue}m.error("Mobile test failed after all exhausting attempts");let b={failureReason:g.error?.reason,failureDetails:g.error?{errorMessage:g.error.message,errorStack:g.error.stack}:void 0};return await d.finish({logger:m,status:g.status,...b,finishedAt:y}),{...g,testMetadata:l,platformType:nm(s),steps:l.steps,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,runId:a,...b,attempts:f+1,filePath:l.relativeFilePath,quarantined:l.quarantined,quarantinedMetadata:l.quarantinedMetadata,status:g.status}}throw new Error("This code should not be reachable")}async function jbe(r){let{runTracer:e,metadata:t,constants:n,fixtures:o,inputs:i,options:a}=r,{attemptNumber:s,totalAttempts:l}=n,{orgId:c,gitMetadata:u}=t,{apiClient:d,logger:m,usageTracker:p,platformHelpers:f}=o,{testDefinition:h,logUpdate:g,project:y,envOverride:b}=i,{regenerateCache:E,alwaysSaveCache:v,noCache:w}=a;s!==0&&g("RETRY",`attempt ${s}/${l}`);let L={...i.project.config.emulator,...h.settings?.emulator},I={...y.config.ai,useMemory:y.config.ai?.useMemory!==!1,...h.settings?.ai},A=b||h.settings?.defaultEnv,O=(A?pl(A,y,m):void 0)?.variables??{},k=yo({logger:m,orgId:c,client:d,gitMetadata:u,regenerateCache:E,alwaysSaveCache:v,noCache:w,isolateCachesByEnvironment:y.config?.advanced?.isolateCachesByEnvironment}),D=new xu(d,c),j={type:"API_KEY",baseUrl:d.baseUrl,apiKey:d.apiKey,logger:m,mode:"runner"},$=new Ai(j),xe=new aa(I.agentConfig,j),B=new Za(j,xe),Z=new Qa({httpClient:d,fakerSeed:y.config.advanced?.fakerConstantSeed?qc:void 0});return await Gbe({metadata:t,options:a,runTracer:e,inputs:i,fixtures:{logger:m,apiClient:d,mobileGenerator:$,storage:D,cacheStorage:k,usageTracker:p,browserEnricher:B,browserGenerator:xe,localCodeEvalTools:Z,platformHelpers:f},env:{envName:A,envVariables:O},settings:{aiSettings:I,emulatorSettings:L}})}async function Gbe(r){let{fixtures:{platformHelpers:e},inputs:{testDefinition:t},env:{envName:n}}=r,o;try{o=await e.prepareRunParams(r)}catch(s){return{status:"FAILED",results:[],error:new C("UserConfigurationError",`Fatal error creating mobile driver: ${s.message}`)}}let i;try{i=await Nu({...o,containerName:`mobile test ${t.name}`,envName:n})}finally{await o.cleanup()}await o.tracer.finish({logger:o.fixtures.logger,results:i.results,status:i.status});let a;if(i.status==="FAILED"&&i.terminalResult){let s=i.terminalResult.message;s?a=C.fromMessage(s):a=new C("UnknownError",s||"Unknown failure")}return{...i,error:a}}import{existsSync as rEe,mkdirSync as nEe,statSync as oEe}from"fs";import iEe from"path";import{z as q4t}from"zod";import{randomUUID as y4}from"crypto";import Wbe from"fs";import WE from"path";function GE(r){if(r.status!=="FAILED")return"none";switch(r.failureReason){case"SetupFailureError":return"setup";case"TeardownFailureError":return"teardown";default:return"main"}}function Vbe(r){switch(r){case"PASSED":return"passed";case"FAILED":return"failed";case"CANCELLED":return"skipped";case"RETRYING":case"WAITING_FOR_USER":case"PENDING":case"RUNNING":return"unknown";default:return Wh(r)}}function S4(r){let e=WE.relative(".",r);return e===""?r:e}function h4(r,e){return Math.max(0,(r.getTime()-e.getTime())/1e3)}function qbe(r,e,t){let n=h4(e,r),o=h4(t,r);return{start_at:n,end_at:o,duration:Math.max(0,o-n)}}function b4(r){let e=r.reduce((t,[n,o])=>(!o||Object.keys(t).length>=10||(t[n]=o),t),{});return Object.keys(e).length>0?e:void 0}function Kbe(r){if(r.status!=="FAILED"||!r.failureReason)return;let e=r.failureDetails?.classification,t=Wd[e?.reason||r.failureReason],n=e?.summary||r.failureDetails?.errorMessage||hc[r.failureReason];return`${t}: ${n}`}function Ybe(r){if(r.status!=="FAILED")return;let e=[r.failureDetails?.classification?.summary,r.failureDetails?.classification?.rootCause,r.failureDetails?.errorMessage].filter(n=>!!n),t=r.failureDetails?.errorStack?.split(`
5027
+ `)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,assetDetails:this.assetDetails,finishedAt:new Date,results:nS(o,t),beforeResults:i?nS(i,t):void 0,afterResults:a?nS(a,t):void 0};await Promise.all(this.children.map(l=>l.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}try{this.resourceUsageSampler.stop(),this.resourceUsageStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}async startMainStepList(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}async startAfterStepList(){let e=new Md(this.keepalive,this.testId,this.testName,this.diskStorage,this.orgId);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${La}/${t}.jpeg`)}},TM=class{constructor(e,t,n,o,i,a,s,l){this.client=e;this.testId=t;this.testName=n;this.platform=o;this.runId=i;this.metadata=a;this.diskStorage=s;this.orgId=l}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){let{runAttemptId:t}=e;this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let n=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),o={id:t,schemaVersion:Sa,runAttemptSchemaVersion:l0,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=Bbe(async()=>{await this.client.extendEmulatorTtl(this.platform,e.emulatorName)},3e4,{maxWait:6e4}),a=new EM(()=>void i(),this.testId,this.testName,t,o,n,this.orgId,e.assetDetails);return this.children.push(a),a}},jE=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a,suiteName:s}){let l={...i,suiteName:s,id:t,trigger:An.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Zl,labels:a??[]},c=new Op(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,directory:e.directory,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:Zl,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:nm(e.platform),aiSettings:e.aiSettings};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new TM(this.client,e.testId,e.testName,e.platform,e.runId,n,t,this.orgId);return this.children.push(o),o}};function f4(r){return{platform:r.platform,originalSteps:{steps:Ube(r.steps),beforeSteps:void 0,afterSteps:void 0}}}async function vM(r){let{inputs:e,fixtures:t,metadata:n}=r,{tracer:o,logger:i}=t,{runId:a}=n,{platform:s,testDefinition:l,project:c}=e,u=new Date,d=await o.startRun({...f4(l),logger:i,testId:l.id,testName:l.name,directory:Hbe(l.relativeFilePath),runId:a,testDescription:l.description,testLabels:l.labels,schemaVersion:l.schemaVersion,quarantined:l.quarantined,quarantinedReason:l.quarantinedMetadata?.quarantinedReason,aiSettings:c.config.ai}),m=i.child(d.loggerBindings||{}),p=1+(l.settings?.retries??c.config.retries??1);for(let f=0;f<p;f++){let h=new Date,g=await jbe({...r,runTracer:d,fixtures:{...t,logger:m},constants:{attemptNumber:f,totalAttempts:p}}),y=new Date;if(g.status!=="FAILED")return await d.finish({logger:m,status:g.status,failureRecoveryDetails:g.failureRecoveryDetails,finishedAt:y}),{...g,testMetadata:l,platformType:nm(s),steps:l.steps,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,runId:a,attempts:f+1,filePath:l.relativeFilePath,quarantined:l.quarantined,quarantinedMetadata:l.quarantinedMetadata,status:g.status};if(f!==p-1){m.warn("Retrying failed mobile run");continue}m.error("Mobile test failed after all exhausting attempts");let b={failureReason:g.error?.reason,failureDetails:g.error?{errorMessage:g.error.message,errorStack:g.error.stack}:void 0};return await d.finish({logger:m,status:g.status,...b,finishedAt:y}),{...g,testMetadata:l,platformType:nm(s),steps:l.steps,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,runId:a,...b,attempts:f+1,filePath:l.relativeFilePath,quarantined:l.quarantined,quarantinedMetadata:l.quarantinedMetadata,status:g.status}}throw new Error("This code should not be reachable")}async function jbe(r){let{runTracer:e,metadata:t,constants:n,fixtures:o,inputs:i,options:a}=r,{attemptNumber:s,totalAttempts:l}=n,{orgId:c,gitMetadata:u}=t,{apiClient:d,logger:m,usageTracker:p,platformHelpers:f}=o,{testDefinition:h,logUpdate:g,project:y,envOverride:b}=i,{regenerateCache:E,alwaysSaveCache:v,noCache:w}=a;s!==0&&g("RETRY",`attempt ${s}/${l}`);let L={...i.project.config.emulator,...h.settings?.emulator},I={...y.config.ai,useMemory:y.config.ai?.useMemory!==!1,...h.settings?.ai},A=b||h.settings?.defaultEnv,O=(A?pl(A,y,m):void 0)?.variables??{},k=yo({logger:m,orgId:c,client:d,gitMetadata:u,regenerateCache:E,alwaysSaveCache:v,noCache:w,isolateCachesByEnvironment:y.config?.advanced?.isolateCachesByEnvironment}),D=new xu(d,c),j={type:"API_KEY",baseUrl:d.baseUrl,apiKey:d.apiKey,logger:m,mode:"runner"},$=new Ai(j),xe=new aa(I.agentConfig,j),B=new Za(j,xe),Z=new Qa({httpClient:d,fakerSeed:y.config.advanced?.fakerConstantSeed?qc:void 0});return await Gbe({metadata:t,options:a,runTracer:e,inputs:i,fixtures:{logger:m,apiClient:d,mobileGenerator:$,storage:D,cacheStorage:k,usageTracker:p,browserEnricher:B,browserGenerator:xe,localCodeEvalTools:Z,platformHelpers:f},env:{envName:A,envVariables:O},settings:{aiSettings:I,emulatorSettings:L}})}async function Gbe(r){let{fixtures:{platformHelpers:e},inputs:{testDefinition:t},env:{envName:n}}=r,o;try{o=await e.prepareRunParams(r)}catch(s){return{status:"FAILED",results:[],error:new C("UserConfigurationError",`Fatal error creating mobile driver: ${s.message}`)}}let i;try{i=await Nu({...o,containerName:`mobile test ${t.name}`,envName:n})}finally{await o.cleanup()}await o.tracer.finish({logger:o.fixtures.logger,results:i.results,status:i.status});let a;if(i.status==="FAILED"&&i.terminalResult){let s=i.terminalResult.message;s?a=C.fromMessage(s):a=new C("UnknownError",s||"Unknown failure")}return{...i,error:a}}import{existsSync as rEe,mkdirSync as nEe,statSync as oEe}from"fs";import iEe from"path";import{z as Y4t}from"zod";import{randomUUID as y4}from"crypto";import Wbe from"fs";import WE from"path";function GE(r){if(r.status!=="FAILED")return"none";switch(r.failureReason){case"SetupFailureError":return"setup";case"TeardownFailureError":return"teardown";default:return"main"}}function Vbe(r){switch(r){case"PASSED":return"passed";case"FAILED":return"failed";case"CANCELLED":return"skipped";case"RETRYING":case"WAITING_FOR_USER":case"PENDING":case"RUNNING":return"unknown";default:return Wh(r)}}function S4(r){let e=WE.relative(".",r);return e===""?r:e}function h4(r,e){return Math.max(0,(r.getTime()-e.getTime())/1e3)}function qbe(r,e,t){let n=h4(e,r),o=h4(t,r);return{start_at:n,end_at:o,duration:Math.max(0,o-n)}}function b4(r){let e=r.reduce((t,[n,o])=>(!o||Object.keys(t).length>=10||(t[n]=o),t),{});return Object.keys(e).length>0?e:void 0}function Kbe(r){if(r.status!=="FAILED"||!r.failureReason)return;let e=r.failureDetails?.classification,t=Wd[e?.reason||r.failureReason],n=e?.summary||r.failureDetails?.errorMessage||hc[r.failureReason];return`${t}: ${n}`}function Ybe(r){if(r.status!=="FAILED")return;let e=[r.failureDetails?.classification?.summary,r.failureDetails?.classification?.rootCause,r.failureDetails?.errorMessage].filter(n=>!!n),t=r.failureDetails?.errorStack?.split(`
5028
5028
  `).map(n=>n.trim()).filter(Boolean)||[];if(!(e.length===0&&t.length===0))return[{expanded:e,backtrace:t}]}function Xbe(r){let e=r.status==="FAILED"?GE(r):void 0;return b4([["failure_section",e],["quarantined",r.quarantined?"true":"false"],["failure_recovery",r.failureRecoveryDetails?.attempts?"true":"false"]])}function Jbe(r,e,t){let n=S4(t.filePath);return{id:t.runId||y4(),scope:r,name:t.testName,location:n,file_name:WE.basename(n),result:Vbe(t.status),failure_reason:Kbe(t),failure_expanded:Ybe(t),history:qbe(e,t.lastAttemptStartedAt,t.finishedAt),tags:Xbe(t)}}function g4(r,e,t,n,o){let i=S4(e);return{id:y4(),scope:r,name:t,location:i,file_name:WE.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:b4([["quarantined",o?.quarantined||"false"],["failure_recovery","false"]])}}function Zbe(r,e){let t=e.map(i=>Jbe(r.suiteName,r.startedAt,i)),n=r.testsToSkip.map(i=>g4(r.suiteName,i.relativeFilePath,i.name,i.id,void 0)),o=r.quarantinedTestsToSkip.map(i=>g4(r.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return[...t,...n,...o]}function AM(r,e,t){let n=Zbe(e,t);Wbe.writeFileSync(WE.join(r,`${e.suiteName}.buildkite.json`),JSON.stringify(n,null,2))}import Qbe from"junit-report-builder";import VE from"path";function E4(r,e){r.property("quarantined","true"),r.property("dd_tags[quarantined]","true"),e.quarantinedReason&&(r.property("quarantined_reason",e.quarantinedReason),r.property("dd_tags[quarantined_reason]",e.quarantinedReason)),e.quarantinedAt&&(r.property("quarantined_at",e.quarantinedAt.toISOString()),r.property("dd_tags[quarantined_at]",e.quarantinedAt.toISOString()))}function eEe(r,e){let t=GE(r);if(e.name(r.testName).className(r.testName).file(VE.relative(".",r.filePath)).property("id",r.testId).property("dd_tags[id]",r.testId),r.labels&&(e.property("labels",r.labels.join(",")),r.labels.forEach(n=>{e.property("dd_tags[label]",n)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantinedMetadata&&E4(e,r.quarantinedMetadata),t==="setup"&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t==="main"&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t==="teardown"&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let n=Wd[r.failureDetails?.classification?.reason||r.failureReason],o=r.failureDetails?.classification?.summary||hc[r.failureReason];r.runId&&(o+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(o,n)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters?.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters?.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function tEe(r,e,t){let{suiteId:n,suiteName:o,startedAt:i,finishedAt:a,testsToSkip:s,quarantinedTestsToSkip:l,quarantinedTestsMetadata:c}=e,u=r.testSuite().name(o);n&&u.property("id",n),u.timestamp(i).property("startedAt",i.toISOString()).property("finishedAt",a.toISOString()).time((a.getTime()-i.getTime())/1e3);for(let d of t){let m=u.testCase();eEe(d,m)}for(let d of s){let m=u.testCase();m.name(d.name).className(d.name).file(VE.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&m.property("baseUrl",d.baseUrl),d.labels&&(m.property("labels",d.labels.join(",")),d.labels.forEach(p=>{m.property("dd_tags[label]",p)})),m.skipped()}for(let d of l){let m=u.testCase();m.name(d.name).className(d.name).file(VE.relative(".",d.relativeFilePath)).property("id",d.id);let p=c[d.id];p&&E4(m,p),d.baseUrl&&m.property("baseUrl",d.baseUrl),d.labels&&(m.property("labels",d.labels.join(",")),d.labels.forEach(f=>{m.property("dd_tags[label]",f)})),m.skipped()}return u}function wM(r,e,t){let n=Qbe.newBuilder();tEe(n,e,t),n.writeTo(VE.join(r,`${e.suiteName}.xml`))}function T4(r){return{testName:iEe.basename(r.filePath,".test.yaml")||r.filePath.split("/").pop()?.replace(".yaml","")||r.filePath,testId:r.testMetadata.id,filePath:r.filePath,labels:r.testMetadata.labels,baseUrl:void 0,runId:r.runId,quarantined:r.quarantined,quarantinedMetadata:r.quarantinedMetadata,status:r.status,failureRecoveryDetails:r.failureRecoveryDetails,failureDetails:r.failureDetails,failureReason:r.failureReason,finishedAt:r.finishedAt,lastAttemptStartedAt:r.lastAttemptStartedAt,attempts:r.attempts,parameters:r.parameters}}async function v4({format:r,params:e,runs:t,folder:n}){switch(rEe(n)?oEe(n).isDirectory()||(P.error(`The specified reporter output directory '${n}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(P.info(`Reporter output directory '${n}' does not exist on disk, creating it now...`),nEe(n,{recursive:!0})),r){case"junit":{let o=t.map(T4);wM(n,e,o);return}case"buildkite-json":{let o=t.map(T4);AM(n,e,o);return}case"allure":case"allure-json":P.error(`The specified reporter format '${r}' is not supported for mobile tests.`);return;case"playwright-json":P.error(`The specified reporter format '${r}' is not supported for mobile tests.`);return;default:throw new Error(`Unknown reporter format requested: '${r}'`)}}async function A4(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]={quarantinedAt:i.quarantinedAt,quarantinedReason:i.quarantinedReason},o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function fa(){try{await J(Promise.all([sg(),gt.flush()]),{milliseconds:5e3})}catch{}}async function w4(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:l,runGroupId:c,gitMetadata:u}=o,{suiteName:d,outputDir:m,parallel:p}=e;sEe(m)&&P.warn(`Output directory ${m} already exists, removing before test execution...`);let f=FF({items:n.testDefinitions,shardIndex:e.shardIndex??1,shardCount:e.shardCount??1,sortKey:D=>D.relativeFilePath}),h=new Set;n.testDefinitions.forEach(D=>{D.labels?.forEach(j=>h.add(j))});let g=s.child({orgId:l,runGroupId:c,branch:u.gitBranchName}),y=await jE.start({suiteName:d,logger:g,orgId:l,runGroupId:c,outputDir:m,client:a,gitMetadata:u,labels:Array.from(h)}),b=[],E=new Date,v=new Set,w=async()=>lEe({runResults:b,startTime:E,ranTests:v,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:m}),L=async D=>{P.warn(`${D} Stopping tests and printing latest results.`),await y.finish({logger:g,status:"CANCELLED"}),await w(),await fa(),process.exit(1)},I=async()=>{await L("SIGINT received.")};process.once("SIGINT",I);let A;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let D=e.timeoutMinutes*60*1e3;A=setTimeout(()=>{L(`Timeout of ${e.timeoutMinutes} minute(s) reached.`)},D)}let _={};for(let D=0;D<f.length;D++){let j=Object.values(_);j.length===p&&await Promise.race(j.map(B=>B.promise));let $=f[D],xe=`test-${D}`;_[xe]={done:!1,promise:(async({testDefinition:B})=>{v.add(xe);let Z=B.relativeFilePath.includes("..")?B.fullFilePath:B.relativeFilePath;gp({status:"START",testLogRef:Z,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>f.length});let ie=setInterval(()=>gp({status:"RUN",testLogRef:Z,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>f.length}),5*60*1e3),se=aEe(),Pe=g.child({testId:B.id,runId:se}),we=new Cy({logger:Pe,reporter:new Wy(a),runType:"mobile-test-run",runId:se,testMetadata:B,suiteMetadata:void 0});try{let he=await cEe({testDefinition:B,metadata:{...o,runId:se},fixtures:{...t,tracer:y,logger:Pe,usageTracker:we},inputs:{...n,project:i,channel:n.channel??B.settings?.defaultChannel,tag:n.tag??B.settings?.defaultTag,logUpdate:(Ie,Ot)=>gp({status:Ie,testLogRef:Z,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>f.length,additionalText:Ot})},options:e});gp({status:he.status,testLogRef:Z,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>f.length}),b.push(he)}catch(he){let Ie=`Encountered unexpected fatal error when running test '${B.name}': ${he.message}
5029
5029
  ${he.stack}`;P.error(Ie),Pe.error({err:he},`Encountered unexpected fatal error when running test ${B.name}`),await L("Fatal error occurred.")}finally{clearInterval(ie),_[xe].done=!0,delete _[xe]}await we.flush(s)})({testDefinition:$})}}await Promise.allSettled(Object.values(_).map(D=>D.promise)),A&&clearTimeout(A);let k=b.some(D=>D.status==="FAILED"&&!D.quarantined)?"FAILED":"PASSED";return await y.finish({logger:g,status:k}),process.off("SIGINT",I),e.reporter&&e.reporterDir&&await v4({logger:g,callbacks:{createDebugDataReaderForRunAttempt:(D,j)=>new Yy(m,D,j)},format:e.reporter,params:{projectConfigPath:i.configFilePath,suiteName:d??i.config.name,startedAt:E,finishedAt:new Date,testsToSkip:[],quarantinedTestsToSkip:[],quarantinedTestsMetadata:{}},runs:b,folder:e.reporterDir}),w()}async function lEe({runResults:r,startTime:e,apiClient:t,uploadResults:n,outputDir:o}){let i=t.getAppUrl(),a=IF({results:r,startTime:e.getTime(),onFailed:s=>{},getDisplayLine:s=>{let l=`${fu}- ${s.filePath}`;return s.runId&&(l+=` ( link when uploaded: ${i}/runs/${s.runId} )`),l},entity:"mobile test"});return P.log(""),n?(P.success(`Test results have been saved to the folder ${o}. Uploading to Momentic Cloud...`),await Ky({client:t,consoleLogger:P,resultsPath:o})):P.success(`Test results have been saved to the folder ${o}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${o}'.`),a}async function cEe({testDefinition:r,metadata:e,fixtures:t,inputs:n,options:o}){switch(r.platform){case"ANDROID":return await vM({metadata:e,fixtures:{...t,platformHelpers:m4},inputs:{...n,platform:"ANDROID",testDefinition:r},options:o});case"IOS":return await vM({metadata:e,fixtures:{...t,platformHelpers:p4},inputs:{...n,platform:"IOS",testDefinition:r},options:o});default:{let i=r;throw new Error(`Unsupported platform on test definition: ${JSON.stringify(i)}`)}}}async function CM(){V1(),DF("Chromium")||(tl?(await ry("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await iy({rawBrowsers:["chromium"],force:!1,all:!1})):(P.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}async function RM({project:r,logger:e}){let t=await xt(r),n=Object.values(t.mobileTests),o=0,i=new Set,a=[];for(let s of n)try{await Er(s.fullFilePath,e,t)}catch(l){e.error(`Failed to parse mobile test ${s.name} (${s.relativePath})`),UF(l,s.relativePath,a),o++,i.add(s.relativePath)}return{parsingErrors:o,parsingErrorDetails:a,failedTestFilePaths:i}}CF({serviceName:"mobile-cli"});br.setApp("mobile-cli");rw||br.warn("Sentry is not enabled in this environment due to unsupported node version");var yEe=xM(import.meta.url),SEe=fEe(yEe),KE=hEe(SEe,"..");br.info(`Setting APPIUM_HOME to ${KE}`);process.env.APPIUM_HOME=KE;var Qo=new uEe;Qo.name("momentic-mobile").description("Momentic Mobile CLI").version(Zl);Qo.command("install-skills").description("Install the Momentic skill markdown as SKILL.md.").option("--cursor","Install into Cursor's default skill directory.").option("--claude-code","Install into Claude Code's default skill directory.").option("--codex","Install into Codex's default skill directory.").option("--opencode","Install into OpenCode's default skill directory.").argument("[installPath]","Optional target directory path where SKILL.md should be installed.").option("--copilot","Install into Copilot (VS Code)'s default skill directory.").action(async(r,e)=>{HF({rawInstallPath:r,options:e})});var C4=Qo.command("assets").description("Manage mobile testing assets");C4.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(As).addOption(ws).addOption(pM).addOption(fM).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=Zo.resolve(r);Cs.existsSync(a)||(P.error(`File not found: ${a}`),process.exit(1));let s=new Or({baseUrl:n,apiKey:t,logger:P}),l=/\.apk$/i.test(a),c=a.endsWith(".app")&&Cs.statSync(a).isDirectory();!l&&!c&&(P.error(`Unsupported file type: ${a}. Supported formats: .apk (Android), .app directory (iOS development builds)`),process.exit(1)),await ib({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:P,platform:l?"ANDROID":"IOS"})});C4.command("download").description("Download an asset for mobile tests").addOption(As).addOption(ws).addOption(fM).addOption(qK).addOption(KK).argument("[path]","Path to download the asset to (file or directory)").action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,platform:a}=e,s=new Or({baseUrl:n,apiKey:t,logger:P}),l=YK(a),{downloadUrl:c}=await s.getLimbarAssetDownloadUrl(i,o,l),u=r?Zo.resolve(r):process.cwd(),d=`${i}-${o}.${KI(l)}`;r?Cs.existsSync(u)&&Cs.statSync(u).isDirectory()&&(u=Zo.join(u,d)):u=Zo.join(u,d),P.info(`Downloading asset to ${u}...`);let m=await fetch(c);if(!m.ok)throw new Error(`Failed to download asset: ${m.statusText}`);if(!m.body)throw new Error("No response body");await gEe(mEe.fromWeb(m.body),Cs.createWriteStream(u)),P.success(`Asset downloaded to ${u}`)});Qo.command("app").addOption(As).addOption(ws).addOption(dM).addOption(qf).addOption(SM).addOption(WK).addOption(mM).addOption($E).addOption(HE).action(async r=>{let{apiKey:e,server:t,yes:n,port:o,disableCache:i,saveCache:a,regenerateCache:s}=r;sy({disableCache:i,saveCache:a,regenerateCache:s});let l=ow(r.logLevel);br.setApp("mobile-desktop-server");let c=new Or({baseUrl:t,apiKey:e,logger:br});await Gy({client:c,skipPrompts:n}),P.debug("API key check complete");let u=xM(import.meta.url),d=Zo.dirname(u),m=Zo.resolve(d,"..","static");await CM(),P.debug({appiumHome:KE},"Resolved resource paths");let p=await oa({configFilePath:r.config}),{parsingErrors:f,parsingErrorDetails:h,failedTestFilePaths:g}=await RM({project:p,logger:P});f>0&&(aw({parsingErrors:f,parsingErrorDetails:h,failedTestFilePaths:g}),process.exit(1)),await jK({momenticServerUrl:t,serverPort:o,apiKey:e,staticDir:m,initialProject:p,driverLogLevel:l,logger:br,regenerateCache:s??!1,noCache:i??!1,alwaysSaveCache:a??!1});let y=`http://localhost:${o}`;P.info(`Local app started on: ${y}`),await pEe(y)});Qo.command("mcp").description("Start the mobile MCP server over stdio.").addOption(As).addOption(ws).addOption(qf).addOption($E).addOption(HE).addOption(JK).addOption(ZK).addOption(d4).action(async r=>{r.androidHome&&(process.env.ANDROID_HOME=Zo.resolve(r.androidHome)),r.javaHome&&(process.env.JAVA_HOME=Zo.resolve(r.javaHome)),br.setApp("mobile-mcp"),P.setMinLevel(Number.POSITIVE_INFINITY);let{apiKey:e,server:t,saveCache:n,disableCache:o,sessionIdleTimeoutMinutes:i}=r;sy({disableCache:o,saveCache:n});let a=await oa({configFilePath:r.config}),s=new Or({baseUrl:t,apiKey:e,logger:br});if(await Gy({client:s,skipPrompts:!0}),!Zl)throw new Error("CLI_VERSION is not set");await sM({project:a,logger:br,apiKey:e,serverUrl:t,cliVersion:Zl,supportsFileOutput:!0,alwaysSaveCache:n??!1,noCache:o??!1,sessionIdleTimeoutMinutes:i})});var _M=Qo.command("results").description("Merge and upload test results.");_M.command("merge").description("Merge test results files.").addOption(hM).addArgument(new Yf("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(P.error("Output directory is required."),process.exit(1)),Cs.existsSync(r)||(P.warn("Results path does not exist, skipping merge."),process.exit(0)),Cs.existsSync(t)&&P.warn(`Output directory ${t} already exists, removing before merging...`),oB(br,t,r),await fa(),process.exit(0)});var R4=new Yf("<results>","Path to the results archive.").argRequired();_M.command("upload").description("Upload test results to Momentic cloud.").addOption(As).addOption(ws).addArgument(R4).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=br,i=new Or({baseUrl:n,apiKey:t,logger:o});await Ky({consoleLogger:P,resultsPath:r,client:i}),await fa(),process.exit(0)});_M.command("view").description("View test results locally.").addOption(As).addOption(ws).addOption(new qE("--port <port>",`Port to run the run viewer on. Defaults to ${Xh}.`).argParser(vs)).addArgument(R4).addArgument(new Yf("<runId>","Run ID to open in the viewer.").argOptional()).action(async(r,e,t)=>{br.setApp("local-run-viewer");let n=xM(import.meta.url),o=Zo.dirname(n),i=Zo.resolve(o,"..","run-viewer-static");await rC({logger:br,staticDir:i,resultsPath:r,runId:e,port:t.port})});var bEe=Qo.command("list").description("List mobile test paths");bEe.addOption(qf).addOption(uM).addOption(gM).addOption(yM).addOption(new qE("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(new Yf("[tests...]","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let t=await oa({configFilePath:e.config,nameFilter:e.filter}),n=await xt(t),o=await cM({tests:r,momenticFiles:n,yes:!0,include:e.include,exclude:e.exclude,project:t,labels:e.labels,logger:new zm(40,{}),quarantinedTestsMetadata:{}});P.info(o.map(i=>i.relativeFilePath).join(`
5030
5030
  `)),process.exit(0)});var EEe=Qo.command("run").alias("test").description("Run tests on the local machine");EEe.addOption(As).addOption(ws).addOption(qf).addOption(uM).addOption(gM).addOption(yM).addOption(dM).addOption(r4).addOption(SM).addOption(o4).addOption(n4).addOption(mM).addOption($E).addOption(HE).addOption(hM).addOption(i4).addOption(l4).addOption(c4).addOption(u4).addOption(a4).addOption(s4).addOption(new qE("--labels <labels...>","Only run tests with the specified label(s).")).addOption(pM).addOption(VK).addOption(XK).addOption(QK).addOption(e4).addOption(t4).addArgument(new Yf("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{name:t,apiKey:n,server:o,tag:i,channel:a,outputDir:s,reporter:l,reporterDir:c,disableCache:u,saveCache:d,regenerateCache:m}=e,p=ow(e.logLevel);await CM(),P.debug({appiumHome:KE},"Resolved resource paths"),sy({disableCache:u,saveCache:d,regenerateCache:m}),kF({shardIndex:e.shardIndex,shardCount:e.shardCount});let f=await oa({configFilePath:e.config,nameFilter:e.filter}),h=s??f.config.outputDir??KU,g=e.parallel??f.config.parallel??1,{parsingErrors:y,parsingErrorDetails:b,failedTestFilePaths:E}=await RM({project:f,logger:P});y>0&&(aw({parsingErrors:y,parsingErrorDetails:b,failedTestFilePaths:E}),process.exit(1)),P.debug("Checking API key and dependencies");let v=new Or({baseUrl:o,apiKey:n,logger:P}),{orgId:w,userId:L}=await Gy({client:v,skipPrompts:e.yes});P.debug("API key check and browser installation complete");let I=dEe(),A=br.child({runGroupId:I,orgId:w,userId:L}),_=await Wr(br,v,f);A.debug({gitMetadata:_,config:f.config,nodeVersion:process.versions.node},"Got local git metadata");let O=await A4(A,v,e.ignoreQuarantine),k=await xt(f),D=await cM({tests:r,yes:e.yes,project:f,momenticFiles:k,include:e.include,exclude:e.exclude,labels:e.labels,logger:P,quarantinedTestsMetadata:O});try{let j=await w4({options:{...e,parallel:g,outputDir:h,alwaysSaveCache:d??!1,regenerateCache:m??!1,noCache:u??!1,logLevel:p,timeoutMinutes:e.timeoutMinutes,shardIndex:e.shardIndex,shardCount:e.shardCount,reporter:l,reporterDir:c,labels:e.labels,suiteName:t},fixtures:{logger:A,project:f,apiClient:v},inputs:{envOverride:e.env,tag:i,channel:a,testDefinitions:D},metadata:{gitMetadata:_,runGroupId:I,orgId:w}});await fa(),j.failed>0?process.exit(1):process.exit(0)}catch(j){P.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),P.error(j),br.error({err:j},"Failed to run tests locally"),await fa(),process.exit(1)}});Qo.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new qE("--name <name>","Name of the project")).action(async r=>{P.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
5031
5031
  `),P.info("This wizard will help you bootstrap a new Momentic project."),Cs.existsSync(Tu)&&(P.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??await _F("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:xy};My(t,Tu),P.success(`Initialized Momentic project file at ${Zo.resolve(Tu)}`)});Qo.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${oy.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(P.error("No browsers specified"),process.exit(1)),await iy({rawBrowsers:r,force:e.force,all:e.all})});async function TEe(){try{await Qo.parseAsync(process.argv),await fa()}catch(r){br.error({err:r},"Uncaught error in CLI"),P.error(r),await fa(),process.exit(1)}}TEe();
5032
5032
  //# sourceMappingURL=cli.js.map
5033
- //# debugId=432f71fe-6620-5c85-b8e8-00b634d5aa15
5033
+ //# debugId=71a2b584-0a49-55d7-9b02-be449570bf78