@genesislcap/foundation-rapid-cdn 15.50.2 → 15.50.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -234,7 +234,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
234
234
  `){super(r),this.sent=t,this.received=n,Object.setPrototypeOf(this,e.prototype)}isIgnorableError(){return!!(((this.received?.DETAILS?.ERROR)?.toLowerCase())?.includes(`request needs the user to be logged`)||((this.received?.DETAILS?.ERROR)?.toLowerCase())?.includes(`is not logged in`))}getMessageError(){return Array.isArray(this.received?.ERROR)?this.received?.ERROR.map(e=>this.errorDetailFormatter(e)).join(`
235
235
  `):``}getDetailsError(){return Array.isArray(this.received?.DETAILS?.ERROR)?(this.received?.DETAILS)?.ERROR.map(e=>this.errorDetailFormatter(e)).join(`
236
236
  `):``}hasPasswordExpiredError(){return this.hasErrorCode(`PASSWORD_EXPIRED`)}hasMFAError(){return this.hasErrorCode(`MFA_REQUIRED`)||this.hasErrorCode(`MFA_FAILED`)}requiresTermsAndConditions(){return this.hasErrorCode(`TERMS_ACCEPTANCE_REQUIRED`)}hasErrorCode(e){return Array.isArray(this.received?.ERROR)?this.received?.ERROR.some(t=>t.CODE===e):!1}errorDetailFormatter(e){return`\n ${e.CODE}: \n ${e.TEXT}`}},Ng;(function(e){e.LOGON_ACK=`LOGON_ACK`,e.LOGON_NACK=`LOGON_NACK`,e.LOGOFF_ACK=`LOGOFF_ACK`,e.LOGOFF_NACK=`LOGOFF_NACK`,e.HEARTBEAT_PING=`HEARTBEAT_PING`,e.HEARTBEAT_PONG=`HEARTBEAT_PONG`,e.MORE_ROWS=`MORE_ROWS`,e.MORE_COLUMNS=`MORE_COLUMNS`,e.MORE_COLUMNS_ACK=`MORE_COLUMNS_ACK`,e.MSG_ACK=`MSG_ACK`,e.MSG_NACK=`MSG_NACK`,e.LOGOUT_ACK=`LOGOUT_ACK`,e.LOGOUT_NACK=`LOGOUT_NACK`,e.QUERY_UPDATE=`QUERY_UPDATE`})(Ng||(Ng={}));var Pg;(function(e){e.EVENT_LOGIN_AUTH=`EVENT_LOGIN_AUTH`,e.EVENT_LOGIN_AUTH_ACK=`EVENT_LOGIN_AUTH_ACK`,e.EVENT_LOGIN_AUTH_NACK=`EVENT_LOGIN_AUTH_NACK`,e.EVENT_LOGOUT=`EVENT_LOGOUT`,e.DATA_LOGON=`DATA_LOGON`,e.DATA_LOGOFF=`DATA_LOGOFF`,e.META_REQUEST=`META_REQUEST`,e.JSON_SCHEMA_REQUEST=`JSON_SCHEMA_REQUEST`,e.RESOURCES_REQUEST=`RESOURCES_REQUEST`,e.RESOURCES_REQUEST_ACK=`RESOURCES_REQUEST_ACK`,e.RESOURCES_REQUEST_NACK=`RESOURCES_REQUEST_NACK`,e.EVENT_CHANGE_USER_PASSWORD=`EVENT_CHANGE_USER_PASSWORD`,e.EVENT_SELF_SERVICE_PASSWORD_RESET=`EVENT_SELF_SERVICE_PASSWORD_RESET`,e.EVENT_PASSWORD_RESET_ACTION=`EVENT_PASSWORD_RESET_ACTION`})(Pg||(Pg={}));var Fg;(function(e){e.SESSION_NOT_FOUND=`SESSION_NOT_FOUND`,e.UNKNOWN_MESSAGE_TYPE=`UNKNOWN_MESSAGE_TYPE`})(Fg||(Fg={}));let Ig=e=>Array.isArray(e)?e.map(Ig):e&&typeof e==`object`&&e.constructor===Object?Object.keys(e).sort().reduce((t,n)=>(t[n]=Ig(e[n]),t),{}):e;function Lg(e,t){return`${e}::${JSON.stringify(Ig(t??{}))}`}let Rg=(e,t)=>Array.isArray(e?.ERROR)?e?.ERROR.some(e=>e.CODE?.includes(`${t}`)||e.STATUS_CODE?.includes(`${t}`)):!1,zg=class{constructor(e,t){this.session=e,this.uuid=t}createLoginMessage(e){let t;switch(e.type){case jg.BASIC:t={USER_NAME:e.username,PASSWORD:e.password,MFA_CODE:e.mfaToken};break;case jg.REFRESH:t={USER_NAME:e.username,REFRESH_AUTH_TOKEN:e.refreshToken,MFA_CODE:e.mfaToken};break;case jg.SSO:t={SSO_TOKEN:e.ssoToken};break;case jg.JWT:t={JWT:e.jwt,DOMAIN:e.domain}}return{DETAILS:t,SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Pg.EVENT_LOGIN_AUTH}}createLogoutMessage(e){return{SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Pg.EVENT_LOGOUT,SESSION_AUTH_TOKEN:e.authToken??this.session.getSessionStorageItem(`authToken`),SESSION_ID:e.sessionId??this.session.getSessionStorageItem(`sessionId`)}}createDataLogonMessage(e,t){return{SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Pg.DATA_LOGON,DETAILS:Object.assign({DATASOURCE_NAME:e},t),SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}createDataLogoffMessage(e){return{SOURCE_REF:e,MESSAGE_TYPE:Pg.DATA_LOGOFF,SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}createRequestMessage(e,t){return Object.assign({SOURCE_REF:this.uuid.createId(),SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`),MESSAGE_TYPE:e.startsWith(`REQ_`)?e:`REQ_${e}`},t)}createResourcesMessage(e){return Object.assign({SOURCE_REF:this.uuid.createId(),SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`),MESSAGE_TYPE:Pg.RESOURCES_REQUEST},e)}createMetaRequestMessage(e,t=Pg.META_REQUEST){return{SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:t,DETAILS:{FEATURE:e},SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}createCommitMessage(e,t){return Object.assign({SOURCE_REF:this.uuid.createId(),SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`),MESSAGE_TYPE:e},t)}createRefreshTokenMessage(){return{SOURCE_REF:this.uuid.createId(),SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`),MESSAGE_TYPE:Pg.EVENT_LOGIN_AUTH,DETAILS:{REFRESH_AUTH_TOKEN:this.session.getSessionStorageItem(`refreshToken`),MFA_CODE:this.session.getSessionStorageItem(`mfaToken`)}}}createChangePasswordMessage(e,t,n){return{USER_NAME:e,SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Pg.EVENT_CHANGE_USER_PASSWORD,DETAILS:{OLD_PASSWORD:t,NEW_PASSWORD:n}}}createForgotPasswordMessage(e,t,n=e){return{USER_NAME:n,SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Pg.EVENT_SELF_SERVICE_PASSWORD_RESET,DETAILS:{USER_NAME:e,RETURN_URL:t}}}createForgotPasswordTokenMessage(e,t,n,r=e){return{USER_NAME:r,SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Pg.EVENT_PASSWORD_RESET_ACTION,DETAILS:{USER_NAME:e,RESET_TOKEN:t,NEW_PASSWORD:n}}}createMoreRowsMessage(e,t){return{SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:Ng.MORE_ROWS,DETAILS:{SOURCE_REF:e,VIEW_NUMBER:t},SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}createMoreColumnsMessage(e){return Object.assign(Object.assign({},this.createMoreRowsMessage(e)),{MESSAGE_TYPE:Ng.MORE_COLUMNS})}createHTTPHeadersFromMessage(e,t=`application/json; charset=UTF-8`){let n={"Content-type":t};return e.SOURCE_REF&&(n[`source-ref`]=e.SOURCE_REF,n.SOURCE_REF=e.SOURCE_REF),e.SESSION_AUTH_TOKEN&&(n[`SESSION-AUTH-TOKEN`]=e.SESSION_AUTH_TOKEN),e.MESSAGE_TYPE===Pg.EVENT_LOGOUT&&(n[`SESSION-ID`]=e.SESSION_ID),n}createHeartbeatPingMessage(e=!1){return{MESSAGE_TYPE:Ng.HEARTBEAT_PING,SOURCE_REF:this.uuid.createId(),VERBOSE:e,DETAILS:{},SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}};zg=q([_d(0,Og),_d(1,fg)],zg);let Bg=N.createInterface(e=>e.singleton(zg));var Vg;let Hg=Vg=class{constructor(e,t){this.http=e,this.messageBuilder=t}toHttpHost(e){if(!e)return``;let t=e;return t.startsWith(`ws`)&&(t=t.replace(`ws`,`http`)),t.endsWith(`/`)||(t=t.concat(`/`)),t}post(e,t){return this.http.post(Vg.getUrl(e,t),{body:Vg.getBody(t),headers:this.messageBuilder.createHTTPHeadersFromMessage(t)})}get(e,t){return this.http.get(Vg.getUrl(e,t),{headers:this.messageBuilder.createHTTPHeadersFromMessage(t)})}requestServer(e,t){let n=Vg.getUrl(e,t),r=[];return t.REQUEST&&Object.keys(t.REQUEST).length>0&&Object.keys(t.REQUEST).forEach(e=>{let n=t.REQUEST[e];n!=null&&!Number.isNaN(n)&&r.push(`REQUEST.${e}=${encodeURIComponent(String(n))}`)}),t.DETAILS&&Object.keys(t.DETAILS).forEach(e=>{let n=t.DETAILS[e];n!=null&&!Number.isNaN(n)&&r.push(`${e}=${encodeURIComponent(String(n))}`)}),r.length>0&&(n=`${n}?${r.join(`&`)}`),Y.debug(`HTTP transport - REQUEST_SERVER GET URL: ${n}`),this.http.get(n,{headers:this.messageBuilder.createHTTPHeadersFromMessage(t)})}static getBody(e){return JSON.stringify(e)}static getUrl(e,t){let n=t.MESSAGE_TYPE,r=t.MESSAGE_TYPE.replace(/_/g,`-`).toLowerCase();return n===Pg.DATA_LOGON&&(r=t.DETAILS.DATASOURCE_NAME.replace(/_/g,`-`).toLowerCase()),`${e}${r}`}};Hg=Vg=q([_d(0,Ag),_d(1,Bg)],Hg);let Ug=N.createInterface(e=>e.singleton(Hg));function Wg(e,t,n){let r=e=>typeof e==`function`?e:()=>e,i=r(t),a=r(n);return(t,n)=>e(t,n)?i(t,n):a(t,n)}var Gg=class{constructor(e){this.path=e}};let Kg=/* @__PURE__ */ new Set,qg=Object.freeze({register(e){Kg.add(e)},unregister(e){Kg.delete(e)}}),Jg=/^([a-z][a-z0-9+\-.]*:)?\/\//i,Yg=Object.freeze({path:Object.freeze({get current(){return location.pathname+location.search},generateRoute(e,t,n={}){return J(this,void 0,void 0,function*(){let r=`config`in e?e:u_.find(e);for(;r!==null;){let e=yield r.config.generateRouteFromPath(t,n);if(e!==null)return e;r=r.parent}return null})},push(e,t=!0){if(e&&Jg.test(e)){location.href=e;return}history.pushState({},document.title,e),t&&Yg.path.trigger(e)},replace(e,t=!0){if(e&&Jg.test(e)){location.href=e;return}history.replaceState({},document.title,e),t&&Yg.path.trigger(e)},trigger(e){let t=new Gg(e);for(let e of Kg)e.enqueue(t)}}),name:Object.freeze({generateRoute(e,t,n={}){return J(this,void 0,void 0,function*(){let r=`config`in e?e:u_.find(e);for(;r!==null;){let e=yield r.config.generateRouteFromName(t,n);if(e!==null)return e;r=r.parent}return null})},push(e,t,n={},r=!0){return J(this,void 0,void 0,function*(){let i=yield Yg.name.generateRoute(e,t,n);i!==null&&Yg.path.push(i,r)})},replace(e,t,n={},r=!0){return J(this,void 0,void 0,function*(){let i=yield Yg.name.generateRoute(e,t,n);i!==null&&Yg.path.replace(i,r)})},trigger(e,t,n={}){return J(this,void 0,void 0,function*(){let r=yield Yg.name.generateRoute(e,t,n);r!==null&&Yg.path.trigger(r)})}})});var Mie=class{constructor(){this.queue=[],this.promise=null,this.resolve=null}connect(){this.enqueue(new Gg(Yg.path.current)),window.addEventListener(`popstate`,this),qg.register(this)}disconnect(){this.queue=[],this.promise=null,this.resolve=null,window.removeEventListener(`popstate`,this),qg.unregister(this)}receive(){return this.promise===null?(this.promise=new Promise(e=>this.resolve=e),Promise.resolve().then(()=>this.tryDequeue()),this.promise):this.promise}enqueue(e){this.queue.push(e),this.tryDequeue()}tryDequeue(){if(this.resolve===null||this.queue.length===0)return;let e=this.queue[this.queue.length-1],t=this.resolve;this.queue.length=0,this.promise=null,this.resolve=null,t(e)}handleEvent(e){this.enqueue(new Gg(Yg.path.current))}};let Xg=encodeURIComponent,Zg=e=>Xg(e).replace(`%24`,`$`);function Qg(e,t,n){let r=[];if(t==null)return r;if(Array.isArray(t))for(let i=0,a=t.length;i<a;i++)if(n)r.push(`${Zg(e)}=${Xg(t[i])}`);else{let n=e+`[`+(typeof t[i]==`object`&&t[i]!==null?i:``)+`]`;r=r.concat(Qg(n,t[i]))}else if(typeof t==`object`&&!n)for(let n in t)r=r.concat(Qg(e+`[`+n+`]`,t[n]));else r.push(`${Zg(e)}=${Xg(t)}`);return r}function Nie(e,t){return Array.isArray(e)?(e.push(t),e):e===void 0?t:[e,t]}function Pie(e,t,n){let r=e,i=t.length-1;for(let e=0;e<=i;e++){let a=t[e]===``?r.length:t[e];if(e<i){let n=!r[a]||typeof r[a]==`object`?r[a]:[r[a]];r=r[a]=n||(isNaN(t[e+1])?{}:[])}else r=r[a]=n}}let $g=Object.freeze({get current(){return location.search},build(e,t){let n=[],r=Object.keys(e||{}).sort();for(let i=0,a=r.length;i<a;i++){let a=r[i];n=n.concat(Qg(a,e[a],t))}return n.length===0?``:n.join(`&`)},separate(e){let t=e.indexOf(`?`),n=``;return t!==-1&&(n=e.substr(t+1,e.length),e=e.substr(0,t)),{path:e,queryString:n}},parse(e){let t={};if(!e||typeof e!=`string`)return t;let n=e;n.charAt(0)===`?`&&(n=n.substr(1));let r=n.replace(/\+/g,` `).split(`&`);for(let e=0;e<r.length;e++){let n=r[e].split(`=`),i=decodeURIComponent(n[0]);if(!i)continue;let a=i.split(`][`),o=a.length-1;if(/\[/.test(a[0])&&/\]$/.test(a[o])?(a[o]=a[o].replace(/\]$/,``),a=a.shift().split(`[`).concat(a),o=a.length-1):o=0,n.length>=2){let e=n[1]?decodeURIComponent(n[1]):``;o?Pie(t,a,e):t[i]=Nie(t[i],e)}else t[i]=!0}return t}}),Fie=e=>e;var e_=class{constructor(e,t,n){this.path=e,this.name=t,this.caseSensitive=n}},t_=class{constructor(e,t,n,r){this.route=e,this.paramNames=t,this.paramTypes=n,this.settings=r}get path(){return this.route.path}},n_=class{constructor(e,t,n,r){this.endpoint=e,this.params=t,this.typedParams=n,this.queryParams=r,this.allParams=Object.assign(Object.assign({},t),r),this.allTypedParams=Object.assign(Object.assign({},n),r)}get settings(){return this.endpoint.settings}},Iie=class e{constructor(e,t,n,r){this.chars=e,this.states=t,this.skippedStates=n,this.result=r,this.head=t[t.length-1],this.endpoint=this.head?.endpoint}advance(t){let{chars:n,states:r,skippedStates:i,result:a}=this,o=null,s=0,c=r[r.length-1];function l(u,d){if(u.isMatch(t)&&(++s===1?o=u:a.add(new e(n.concat(t),r.concat(u),d===null?i:i.concat(d),a))),c.segment===null&&u.isOptional&&u.nextStates!==null){if(u.nextStates.length>1)throw Error(`${u.nextStates.length} nextStates`);let e=u.nextStates[0];if(!e.isSeparator)throw Error(`Not a separator`);if(e.nextStates!==null)for(let t of e.nextStates)l(t,u)}}if(c.isDynamic&&l(c,null),c.nextStates!==null)for(let e of c.nextStates)l(e,null);o!==null&&(r.push(this.head=o),n.push(t),o.endpoint!==null&&(this.endpoint=o.endpoint)),s===0&&a.remove(this)}finalize(){function e(t,n){let r=n.nextStates;if(r!==null){if(r.length===1&&r[0].segment===null)e(t,r[0]);else for(let n of r)if(n.isOptional&&n.endpoint!==null){if(t.push(n),n.nextStates!==null)for(let r of n.nextStates)e(t,r);break}}}e(this.skippedStates,this.head)}getParams(){let{states:e,chars:t,endpoint:n}=this,r={};for(let e of n.paramNames)r[e]=void 0;for(let n=0,i=e.length;n<i;++n){let i=e[n];if(i.isDynamic){let e=i.segment.name;r[e]===void 0?r[e]=t[n]:r[e]+=t[n]}}return r}compareTo(e){let t=this.states,n=e.states;for(let e=0,r=0,i=Math.max(t.length,n.length);e<i;++e){let i=t[e];if(i===void 0)return 1;let a=n[r];if(a===void 0)return-1;let o=i.segment,s=a.segment;if(o===null){if(s===null){++r;continue}if((i=t[++e])===void 0)return 1;o=i.segment}else if(s===null){if((a=n[++r])===void 0)return-1;s=a.segment}if(o.kind<s.kind)return 1;if(o.kind>s.kind)return-1;++r}let r=this.skippedStates,i=e.skippedStates,a=r.length,o=i.length;if(a<o)return 1;if(a>o)return-1;for(let e=0;e<a;++e){let t=r[e],n=i[e];if(t.length<n.length)return 1;if(t.length>n.length)return-1}return 0}};function Lie(e){return e.head.endpoint!==null}function Rie(e,t){return e.compareTo(t)}var zie=class{constructor(e){this.candidates=[],this.candidates=[new Iie([``],[e],[],this)]}get isEmpty(){return this.candidates.length===0}getSolution(){let e=this.candidates.filter(Lie);if(e.length===0)return null;for(let t of e)t.finalize();return e.sort(Rie),e[0]}add(e){this.candidates.push(e)}remove(e){this.candidates.splice(this.candidates.indexOf(e),1)}advance(e){let t=this.candidates.slice();for(let n of t)n.advance(e)}},Bie=class{constructor(){this.names=/* @__PURE__ */ new Map,this.paths=/* @__PURE__ */ new Map,this.rootState=new Vie(null,null,``)}add(e,t){if(e instanceof Array)for(let n of e)this.$add(n,t);else this.$add(e,t)}$add(e,t){let n=e.path,r=new e_(e.path,e.name||``,e.caseSensitive===!0),i=n===``?[``]:n.split(`/`).filter(Hie),a=[],o=[],s=this.rootState,c=[];for(let e of i)switch(s=s.append(null,`/`),e.charAt(0)){case`{`:{let t=e.slice(1,-1).split(`:`).map(e=>e.trim());t.length===2?o.push(t[1]):o.push(`string`);let n=t[0].endsWith(`?`),r=n?t[0].slice(0,-1):t[0];a.push(r);let i=new r_(r,n);c.push(i),s=i.appendTo(s);break}case`*`:{let t=e.slice(1);a.push(t),o.push(`string`);let n=new Wie(t);c.push(n),s=n.appendTo(s);break}default:{let t=new Uie(e,r.caseSensitive);c.push(t),s=t.appendTo(s);break}}let l=new t_(r,a,o,t||null);s.setEndpoint(l),this.paths.set(n,c),e.name&&this.names.set(e.name,c)}recognize(e,t={}){return J(this,void 0,void 0,function*(){let n=$g.separate(e),r=$g.parse(n.queryString);e=decodeURI(n.path),e.startsWith(`/`)||(e=`/${e}`),e.length>1&&e.endsWith(`/`)&&(e=e.slice(0,-1));let i=new zie(this.rootState);for(let t=0,n=e.length;t<n;++t){let n=e.charAt(t);if(i.advance(n),i.isEmpty)return null}let a=i.getSolution();if(a===null)return null;let{endpoint:o}=a,s=o.paramNames,c=o.paramTypes,l=a.getParams(),u={};for(let e=0,n=s.length;e<n;++e){let n=s[e],r=t[c[e]]||Fie,i=l[n];u[n]=yield r(i)}return new n_(o,l,u,r)})}generateFromName(e,t){return this.generate(this.names.get(e),t)}generateFromPath(e,t){return this.generate(this.paths.get(e),t)}generate(e,t){if(!e)return null;let n=Object.assign({},t),r={},i=``;for(let t=0,a=e.length;t<a;t++){let a=e[t],o=a.generate(n,r);if(o==null){if(a instanceof r_&&!a.optional)throw Error(`A value is required for route parameter '${a.name}'.`)}else i+=`/`,i+=o}i.charAt(0)!==`/`&&(i=`/`+i);for(let e in r)delete n[e];let a=$g.build(n);return i+=a?`?${a}`:``,i}},Vie=class e{constructor(e,t,n){switch(this.prevState=e,this.segment=t,this.value=n,this.nextStates=null,this.endpoint=null,t?.kind){case 2:this.length=e.length+1,this.isSeparator=!1,this.isDynamic=!0,this.isOptional=t.optional;break;case 1:this.length=e.length+1,this.isSeparator=!1,this.isDynamic=!0,this.isOptional=!1;break;case 3:this.length=e.length+1,this.isSeparator=!1,this.isDynamic=!1,this.isOptional=!1;break;case void 0:this.length=e===null?0:e.length,this.isSeparator=!0,this.isDynamic=!1,this.isOptional=!1}}append(t,n){let r,i=this.nextStates;return i===null?(r=void 0,i=this.nextStates=[]):r=t===null?i.find(e=>e.value===n):i.find(e=>e.segment?.equals(t)),r===void 0&&i.push(r=new e(this,t,n)),r}setEndpoint(e){if(this.endpoint!==null)throw Error(`Cannot add ambiguous route. The pattern '${e.route.path}' clashes with '${this.endpoint.route.path}'`);this.endpoint=e,this.isOptional&&(this.prevState.setEndpoint(e),this.prevState.isSeparator&&this.prevState.prevState!==null&&this.prevState.prevState.setEndpoint(e))}isMatch(e){switch(this.segment?.kind){case 2:return!this.value.includes(e);case 1:return!0;case 3:case void 0:return this.value.includes(e)}}};function Hie(e){return e.length>0}var Uie=class{constructor(e,t){this.value=e,this.caseSensitive=t}get kind(){return 3}appendTo(e){let{value:t,value:{length:n}}=this;if(this.caseSensitive)for(let r=0;r<n;++r)e=e.append(this,t.charAt(r));else for(let r=0;r<n;++r){let n=t.charAt(r);e=e.append(this,n.toUpperCase()+n.toLowerCase())}return e}generate(){return this.value}equals(e){return e.kind===3&&e.caseSensitive===this.caseSensitive&&e.value===this.value}},r_=class{constructor(e,t){this.name=e,this.optional=t}get kind(){return 2}appendTo(e){return e=e.append(this,`/`),e}generate(e,t){return t[this.name]=!0,e[this.name]}equals(e){return e.kind===2&&e.optional===this.optional&&e.name===this.name}},Wie=class{constructor(e){this.name=e}get kind(){return 1}appendTo(e){return e=e.append(this,``),e}generate(e,t){return t[this.name]=!0,e[this.name]}equals(e){return e.kind===1&&e.name===this.name}};let i_=`fast-child-route`;function a_(e,t){return`command`in t?t.command:`redirect`in t?new h_(t.redirect):y_.fromDefinition(e,t)}let o_=e=>{if(e==null)return!1;switch(e.toLowerCase().trim()){case`true`:case`yes`:case`1`:return!0;default:return!1}},Gie={number:e=>e===void 0?NaN:parseFloat(e),float:e=>e===void 0?NaN:parseFloat(e),int:e=>e===void 0?NaN:parseInt(e),integer:e=>e===void 0?NaN:parseInt(e),Date:e=>e===void 0?new Date(Date.now()):new Date(e),boolean:o_,bool:o_};var s_=class{constructor(e){this.owner=e,this._recognizer=null,this.pathToCommand=/* @__PURE__ */ new Map,this.fallbackCommand=null,this.fallbackSettings=null,this.converters={}}get recognizer(){return this._recognizer===null&&(this._recognizer=this.owner.createRouteRecognizer()),this._recognizer}ignore(e){typeof e==`string`&&(e={path:e}),this.pathToCommand.set(e.path,new eae),this.recognizer.add(e,e.settings)}map(...e){for(let t of e){if(`children`in t){let e=this.owner.createTitleBuilder(),n=t.children.map(n=>{let r=Object.assign(Object.assign(Object.assign({},t),n),{path:`${t.path}/${n.path}`});if(`title`in t||`title`in n){let i=t.title||``,a=n.title||``;r.title=e.joinTitles(i,a)}return`name`in n&&(r.name=(t.name?t.name+`/`:``)+n.name),r.children===t.children&&delete r.children,r});this.map(...n);continue}let e;if(e=`command`in t?t.command:`redirect`in t?new h_(t.redirect):y_.fromDefinition(this.owner,t),this.pathToCommand.set(t.path,e),this.recognizer.add(t,t.settings),`childRouters`in t&&t.childRouters){let n=Object.assign(Object.assign({},t),{path:t.path+`/*${i_}`});this.pathToCommand.set(n.path,e),this.recognizer.add(n,n.settings)}}}fallback(e){let t=this.owner;this.fallbackCommand=typeof e==`function`?{createContributor(n,r){return J(this,void 0,void 0,function*(){let i=yield e();return a_(t,i).createContributor(n,r)})}}:a_(t,e)}converter(e,t){let n;n=`convert`in t?t.convert.bind(t):t.prototype&&`convert`in t.prototype?e=>this.owner.construct(t).convert(e):t,this.converters[e]=n}recognize(e){return J(this,void 0,void 0,function*(){let t=yield this.recognizer.recognize(e,this.aggregateConverters());if(t!==null)return{route:t,command:this.pathToCommand.get(t.endpoint.path)};if(this.fallbackCommand!==null){let t=$g.separate(e),n=$g.parse(t.queryString);return{route:new n_(new t_(new e_(`*`,``,!1),[],[],this.fallbackSettings),{},{},n),command:this.fallbackCommand}}return null})}generateFromName(e,t){return this.recognizer.generateFromName(e,t)}generateFromPath(e,t){return this.recognizer.generateFromPath(e,t)}aggregateConverters(){return this.owner.parent===null?Object.assign(Object.assign({},Gie),this.converters):Object.assign(Object.assign({},this.owner.parent.routes.aggregateConverters()),this.converters)}};let c_=`$router`;function Kie(e){let t=e.parentElement;if(t)return t;{let t=e.getRootNode();if(t.host instanceof HTMLElement)return t.host}return null}function l_(e){let t=e;for(;t=Kie(t);)if(c_ in t)return t[c_];return null}let u_=Object.freeze({getOrCreateFor(e){let t=e[c_];return t===void 0?e[c_]=new d_(e):t},find(e){return e[c_]||l_(e)},from(e){class t extends e{constructor(){super(),u_.getOrCreateFor(this)}get config(){return this[c_].config}set config(e){this[c_].config=e}}let n=t.prototype;if(`connectedCallback`in n){let e=n.connectedCallback;n.connectedCallback=function(){e.call(this),this[c_].connect()}}else n.connectedCallback=function(){this[c_].connect()};if(`disconnectedCallback`in n){let e=n.disconnectedCallback;n.disconnectedCallback=function(){e.call(this),this[c_].disconnect()}}else n.disconnectedCallback=function(){this[c_].disconnect()};return t}});function qie(e){return e instanceof Qe}var d_=class{constructor(e){this.host=e,this.parentRouter=void 0,this.contributors=/* @__PURE__ */ new Set,this.navigationQueue=null,this.linkHandler=null,this.newView=null,this.newRoute=null,this.childCommandContributor=null,this.childRoute=null,this.isConnected=!1,this.routerConfig=null,this.view=null,this.route=null,this.onNavigationMessage=e=>J(this,void 0,void 0,function*(){yield this.config.createNavigationProcess().run(this,e),this.navigationQueue.receive().then(this.onNavigationMessage)}),e[c_]=this}get config(){return this.routerConfig}set config(e){this.routerConfig=e,this.tryConnect()}get parent(){if(this.parentRouter===void 0){if(!this.isConnected)return null;this.parentRouter=l_(this.host)}return this.parentRouter||null}get level(){return this.parent===null?0:this.parent.level+1}shouldRender(e){if(this.route&&this.route.endpoint.path===e.endpoint.path){let t=e?.allParams,n=this.route?.allParams;if(JSON.stringify(n)===JSON.stringify(t))return!1}return!0}beginRender(e,t){return J(this,void 0,void 0,function*(){return this.newRoute=e,this.newView=yield t.createView(),this.newView.bind(e.allTypedParams,Jie.create(this)),this.newView.appendTo(this.host),yield t.transition.begin(this.host,this.view,this.newView),{commit:this.renderOperationCommit.bind(this,t.layout,t.transition),rollback:this.renderOperationRollback.bind(this,t.transition)}})}connect(){this.isConnected=!0,this.tryConnect()}disconnect(){this.parent===null?(this.navigationQueue!==null&&(this.navigationQueue.disconnect(),this.navigationQueue=null),this.linkHandler!==null&&(this.linkHandler.disconnect(),this.linkHandler=null)):this.parent.removeContributor(this),this.isConnected=!1,this.parentRouter=void 0}addContributor(e){this.contributors.add(e)}removeContributor(e){this.contributors.delete(e)}tryConnect(){this.config!==null&&this.isConnected&&(this.parent===null?(this.navigationQueue!==null&&this.navigationQueue.disconnect(),this.navigationQueue=this.config.createNavigationQueue(),this.navigationQueue.connect(),this.navigationQueue.receive().then(this.onNavigationMessage),this.linkHandler!==null&&this.linkHandler.disconnect(),this.linkHandler=this.config.createLinkHandler(),this.linkHandler.connect()):(this.config.parent=this.parent.config,this.parent.addContributor(this)))}renderOperationCommit(e,t){return J(this,void 0,void 0,function*(){yield e.beforeCommit(this.host),yield t.commit(this.host,this.view,this.newView),yield e.afterCommit(this.host),this.view!==null&&this.view.dispose(),this.route=this.newRoute,this.view=this.newView,this.newRoute=null,this.newView=null})}renderOperationRollback(e){return J(this,void 0,void 0,function*(){this.newView!==null&&(yield e.rollback(this.host,this.view,this.newView),this.newView.dispose(),this.newRoute=null,this.newView=null)})}navigate(e){return J(this,void 0,void 0,function*(){yield this.tunnel(e)})}leave(e){return J(this,void 0,void 0,function*(){if(yield this.tunnel(e),!e.canceled){let t=this.contributors;this.contributors=/* @__PURE__ */ new Set,e.onCancel(()=>this.contributors=t)}})}construct(e){return J(this,void 0,void 0,function*(){if(this.parent!==null){let t=e.route.allParams[`fast-child-route`]||``,n=yield this.config.recognizeRoute(t);if(n===null){this.config.createEventSink().onUnhandledNavigationMessage(this,new Gg(t)),e.cancel();return}this.childRoute=n.route,this.childCommandContributor=yield n.command.createContributor(this,n.route)}yield this.tunnel(e)})}enter(e){return J(this,void 0,void 0,function*(){yield this.tunnel(e)})}commit(e){return J(this,void 0,void 0,function*(){yield this.tunnel(e)})}tunnel(e){return J(this,void 0,void 0,function*(){let t=this.childRoute,n=this.childCommandContributor;if(t&&n&&(yield e.evaluateContributor(n,t,this)),e.canceled)return;let r=[...this.config.findContributors(e.name),...Array.from(this.contributors)];for(let t of r)if(yield e.evaluateContributor(t,void 0,this),e.canceled)return})}};let Jie=Object.freeze({create(e){return Object.create(ae,{router:{value:e}})}}),Yie=Object.freeze({default:Object.freeze({begin(e,t,n){return J(this,void 0,void 0,function*(){})},rollback(e,t,n){return J(this,void 0,void 0,function*(){})},commit(e,t,n){return J(this,void 0,void 0,function*(){})}})});var f_=class{constructor(e=null,t=null,n=!0){this.template=e,this.runBeforeCommit=n,this.styles=t==null?null:Array.isArray(t)?Ne.create(t):t instanceof Ne?t:Ne.create([t])}beforeCommit(e){return J(this,void 0,void 0,function*(){this.runBeforeCommit&&this.apply(e)})}afterCommit(e){return J(this,void 0,void 0,function*(){this.runBeforeCommit||this.apply(e)})}apply(e){qie(e)&&(e.$fastController.template!==this.template&&(e.$fastController.template=this.template),e.$fastController.styles!==this.styles&&(e.$fastController.styles=this.styles))}};let Xie=Object.freeze({default:new f_(T`<slot></slot>`)});function p_(e,t){return t in e}let Zie={lifecycle:!0,parameters:!0};var Qie=class extends oe{constructor(e){super(),this.options=e}createPlaceholder(e){return x.createCustomAttributePlaceholder(`fast-navigation-contributor`,e)}createBehavior(e){return new $ie(e,this.options)}},$ie=class{constructor(e,t){this.contributor=e,this.options=t,this.router=null}bind(e,t){if(this.options.lifecycle&&(this.router=t.router||u_.find(this.contributor),this.router.addContributor(this.contributor)),this.options.parameters){let t=this.contributor,n=e;for(let e in n)t[e]=n[e]}}unbind(e){this.router!==null&&this.router.removeContributor(this.contributor)}};function m_(e){return new Qie(Object.assign({},Zie,e))}var eae=class{createContributor(){return J(this,void 0,void 0,function*(){return{navigate(e){return J(this,void 0,void 0,function*(){e.cancel()})}}})}},h_=class{constructor(e){this.redirect=e}createContributor(){return J(this,void 0,void 0,function*(){let e=this.redirect;return{navigate(t){return J(this,void 0,void 0,function*(){let n=t.router.config,r=(yield n.generateRouteFromName(e,t.route.allParams))||(yield n.generateRouteFromPath(e,t.route.allParams));if(r===null)throw Error(`Invalid redirect. Name or path not found: ${e}`);t.cancel(()=>J(this,void 0,void 0,function*(){return Yg.path.replace(r)}))})}}})}};function g_(e){return T`<${e} ${m_()}></${e}>`}function __(e){let t=document.createDocumentFragment();t.appendChild(e);let n=new Ae(t,[m_().createBehavior(e)]);return{create(){return n}}}var v_=class{constructor(e,t,n){this.router=e,this.route=t,this.command=n}construct(e){return J(this,void 0,void 0,function*(){if(!this.router.shouldRender(this.route)){e.cancel();return}this.operation=yield this.router.beginRender(this.route,this.command),e.onCancel(()=>this.operation.rollback())})}commit(e){return J(this,void 0,void 0,function*(){yield this.operation.commit(),this.command.title&&e.setTitle(this.command.title)})}},y_=class e{constructor(e,t){this.owner=e,this.createView=t,this._layout=null,this._transition=null,this.title=``}get transition(){return this._transition||this.owner.defaultTransition}set transition(e){this._transition=e}get layout(){return this._layout||this.owner.defaultLayout}set layout(e){this._layout=e}createContributor(e,t){return J(this,void 0,void 0,function*(){return new v_(e,t,this)})}static fromDefinition(t,n){let r;r=`template`in n?()=>J(this,void 0,void 0,function*(){let e=n.template;return typeof e==`function`&&(e=yield e()),e.create()}):()=>J(this,void 0,void 0,function*(){let e=n.element,t=null;if(n.factory)t=n.factory;else if(typeof e==`function`){let n=qe.forType(e);if(n)t=g_(n.name);else if(e=yield e(),typeof e==`string`)t=g_(e);else if(e instanceof HTMLElement)t=__(e);else if(n=qe.forType(e),n)t=g_(n.name);else throw Error(`Invalid value for element in route config.`)}else n.factory=t=e instanceof HTMLElement?__(e):g_(e);return t.create()});let i=new e(t,r);return n.layout&&(i.layout=n.layout instanceof je?new f_(n.layout):n.layout),n.transition&&(i.transition=n.transition),n.title&&(i.title=n.title),i}},b_=class{constructor(){this.handler=e=>{let{shouldHandleEvent:t,href:n}=this.getEventInfo(e);t&&(e.preventDefault(),Yg.path.push(n))}}connect(){window.addEventListener(`click`,this.handler,!0)}disconnect(){window.removeEventListener(`click`,this.handler)}getEventInfo(e){let t={shouldHandleEvent:!1,href:null,anchor:null},n=this.findClosestAnchor(e);if(!n||!this.targetIsThisWindow(n)||n.hasAttribute(`download`)||n.hasAttribute(`router-ignore`)||n.hasAttribute(`data-router-ignore`)||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return t;let r=n.getAttribute(`href`);t.anchor=n,t.href=r;let i=e.which===1,a=r&&!(r.charAt(0)===`#`||/^[a-z]+:/i.test(r));return t.shouldHandleEvent=i&&!!a,t}findClosestAnchor(e){let t=e.composedPath();for(let e=0,n=t.length;e<n;++e){let n=t[e];if(n.tagName===`A`)return n}return e.target}targetIsThisWindow(e){let t=e.getAttribute(`target`);return!t||t===window.name||t===`_self`}},x_=class{constructor(e,t,n,r,i){this.name=e,this.commitActions=r,this.cancelActions=i,this.routes=[],this.routers=[],this.canceled=!1,this.titles=[],this.routes.push(t),this.routers.push(n)}get route(){return this.routes[this.routes.length-1]}get router(){return this.routers[this.routers.length-1]}cancel(e){this.canceled=!0,e&&this.cancelActions.push(e)}onCommit(e){this.commitActions.push(e)}onCancel(e){this.cancelActions.push(e)}setTitle(e){let t=this.router.level;for(;this.titles.length<t+1;)this.titles.push([]);this.titles[t].push(e)}evaluateContributor(e,t=this.route,n=this.router){return J(this,void 0,void 0,function*(){p_(e,this.name)&&(this.routes.push(t),this.routers.push(n),yield e[this.name](this),this.routes.pop(),this.routers.pop())})}},S_=class{constructor(){this.phases=[`navigate`,`leave`,`construct`,`enter`,`commit`]}run(e,t){return J(this,void 0,void 0,function*(){let n=e.config.createEventSink(),r=yield e.config.recognizeRoute(t.path);if(r===null){n.onUnhandledNavigationMessage(e,t);return}let i=r.route,a=r.command;n.onNavigationBegin(e,i,a);let o=[],s=[],c=o,l=[yield a.createContributor(e,i),e,this];for(let t of this.phases){let r=new x_(t,i,e,o,s);if(n.onPhaseBegin(r),r.canceled)c=s;else for(let e of l)if(yield r.evaluateContributor(e),r.canceled){c=s;break}if(n.onPhaseEnd(r),r.canceled)break}yield Promise.all(c.map(e=>e())).then(()=>n.onNavigationEnd(e,i,a))})}commit(e){let t=e.router.config.createTitleBuilder();document.title=t.buildTitle(e.router.config.title,e.titles)}},C_=class{constructor(e=` - `,t=`:`){this.segmentSeparator=e,this.fragmentSeparator=t}joinTitles(e,t){return e===``?t:t===``?e:`${e}${this.segmentSeparator}${t}`}buildTitle(e,t){let n=e;for(let e of t){n&&(n+=this.segmentSeparator);let t=``;for(let n of e)t&&(t+=this.fragmentSeparator),t+=n;n+=t}return n}},w_=class{onUnhandledNavigationMessage(e,t){}onNavigationBegin(e,t,n){}onPhaseBegin(e){}onPhaseEnd(e){}onNavigationEnd(e,t,n){}},T_=class{constructor(){this.isConfigured=!1,this.routes=new s_(this),this.contributors=[],this.defaultLayout=Xie.default,this.defaultTransition=Yie.default,this.title=``,this.parent=null}createNavigationQueue(){return this.construct(Mie)}createLinkHandler(){return this.construct(b_)}createNavigationProcess(){return new S_}createEventSink(){return this.construct(w_)}createTitleBuilder(){return this.construct(C_)}createRouteRecognizer(){return this.construct(Bie)}construct(e){return this.parent===null?new e:this.parent.construct(e)}recognizeRoute(e){return J(this,void 0,void 0,function*(){return yield this.ensureConfigured(),this.routes.recognize(e)})}generateRouteFromName(e,t){return J(this,void 0,void 0,function*(){return yield this.ensureConfigured(),this.routes.generateFromName(e,t)})}generateRouteFromPath(e,t){return J(this,void 0,void 0,function*(){return yield this.ensureConfigured(),this.routes.generateFromPath(e,t)})}findContributors(e){return this.contributors.filter(t=>p_(t,e))}cached(e){let t=null;return()=>J(this,void 0,void 0,function*(){return t===null&&(t=new e),t})}ensureConfigured(){return J(this,void 0,void 0,function*(){this.isConfigured||(yield this.configure(),this.isConfigured=!0)})}};let E_=class extends u_.from(Qe){};E_=q([$e(`fast-router`)],E_);let D_=[];setTimeout(()=>{D_.length&&console.warn(`${D_.length} attribute deprecation notice(s):\n ${D_.join(`
237
- `)}`)},5e3);let O_=`reauthActionLock`;var k_;(function(e){e.SUCCESS=`SUCCESS`,e.FAILED=`FAILED`,e.HANDLED_BY_OTHER_TAB=`HANDLED_BY_OTHER_TAB`,e.ALREADY_VALID=`ALREADY_VALID`})(k_||(k_={}));function A_(){let e=parseInt(localStorage.getItem(O_)||`0`);Date.now()-e>3e4&&localStorage.removeItem(O_)}function j_(){return!localStorage.getItem(O_)&&(localStorage.setItem(O_,Date.now().toString()),!0)}function M_(){localStorage.removeItem(O_)}function N_(){return J(this,void 0,void 0,function*(){return(yield(yield fetch(Bf,{credentials:`include`})).json()).MESSAGE_TYPE===`EVENT_LOGIN_DETAILS_ACK`})}function P_(){return J(this,void 0,void 0,function*(){return(yield N.getOrCreateDOMContainer().get(Ag).post(zf,{body:JSON.stringify({DETAILS:{},MESSAGE_TYPE:`EVENT_LOGIN_AUTH`})})).MESSAGE_TYPE===`EVENT_LOGIN_AUTH_ACK`})}function F_(){return J(this,arguments,void 0,function*(e={}){let{reloadOnFailure:t=!0}=e;if(A_(),!j_())return k_.HANDLED_BY_OTHER_TAB;try{return(yield N_())?k_.ALREADY_VALID:(yield P_())?k_.SUCCESS:(t&&window.location.reload(),k_.FAILED)}finally{M_()}})}function I_(e){let t=n=>{n.key===O_&&n.newValue===null&&(e(),window.removeEventListener(`storage`,t))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)}let L_=(e,t)=>(t?.ROW&&e&&e.length>0?t.ROW.forEach(t=>{let n=t;if(n&&n.DETAILS){let r=n.DETAILS.ROW_REF,i=n.DETAILS.OPERATION;i===`INSERT`&&(e.find(e=>e.DETAILS?.ROW_REF===r)||e.unshift(n)),i===`DELETE`&&(e=e.filter(e=>t.DETAILS?.ROW_REF!==e.DETAILS?.ROW_REF)),i===`MODIFY`&&(e=e.map(e=>e.DETAILS?.ROW_REF===r?Object.assign(Object.assign({},e),n):e))}}):t&&(!e||e.length===0)&&(e=[...new Set(t.ROW)]),e);var R_;let z_=R_=class{get isConnected(){return this._isConnected}set isConnected(e){this._isConnected=e,this.isConnectedSubject.next(this._isConnected)}constructor(e,t,n,r,i,a,o){this.http=e,this.messageBuilder=t,this.session=n,this.metaCache=r,this.serializer=i,this.config=a,this.transport=o,this.isWorking=!1,this._isConnected=!1,this.isConnectedSubject=new Ym(this._isConnected),this.isConnected$=this.isConnectedSubject?.asObservable(),this.ongoingTurbo={},this.streams=/* @__PURE__ */ new Map,this.inFlightRequests=/* @__PURE__ */ new Map,this.ongoingRefresh=null}handleSessionRefresh(){return this.ongoingRefresh||(this.ongoingRefresh=J(this,void 0,void 0,function*(){let e=this.host;this.disconnect();let t=yield F_();return t===k_.HANDLED_BY_OTHER_TAB&&(yield new Promise(e=>{setTimeout(e,R_.REAUTH_WAIT_MS)}),t=yield F_()),t===k_.SUCCESS||t===k_.ALREADY_VALID?(this.connect(e),!0):!1}).finally(()=>{this.ongoingRefresh=null})),this.ongoingRefresh}checkHost(){return J(this,void 0,void 0,function*(){try{return this.getMessage({MESSAGE_TYPE:Ng.HEARTBEAT_PING,SOURCE_REF:`host check`}).then(e=>e.MESSAGE_TYPE===Ng.HEARTBEAT_PONG)}catch(e){return Y.error(e),!1}})}send(e,t){return J(this,void 0,void 0,function*(){if(this.ongoingRefresh&&!(yield this.ongoingRefresh))throw Error(`Cannot send message: session refresh failed`);return this.transport.post(this.host,e)})}httpMode(){return!0}setValidSession(e){Y.deprecated(`setValidSession`,`Please refrain from calling this API as this state is managed internally.`,`15.0.0`)}connect(e){return J(this,void 0,void 0,function*(){return this.host=this.transport.toHttpHost(e),this.checkHost().then(e=>(this.isConnected=e,this.session.setSessionStorageItem(`hostUrl`,this.host),e))})}disconnect(){this.isConnected=!1,this.streams.clear(),this.ongoingTurbo={},this.host=void 0}snapshot(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createDataLogonMessage(e,t);return Y.debug(`HTTP MODE - ${n.MESSAGE_TYPE} (snapshot) message created -> `,n),this.send(n).then(e=>(this.dataLogoff(n.SOURCE_REF).catch(e=>Y.error(e)),e))})}stream(e,t,n,r){let i=this.messageBuilder.createDataLogonMessage(e,r);Y.debug(`HTTP MODE - ${i.MESSAGE_TYPE} (stream) message created -> `,i);let a=i.SOURCE_REF,o=this.config.polling?.POLLING_INTERVAL_MAP?.[e]||this.config.polling.POLLING_FREQUENCY;this.streams.set(a,{SOURCE_REF:a,POLLING_FREQUENCY:new Ym(o),RESOURCE_NAME:e});let s=this.streams.get(a).POLLING_FREQUENCY,c=Nh(Eh(this.send(i)),s.pipe(Fh(()=>document.visibilityState===`visible`)).pipe(Rh(e=>qre(e))).pipe(Rh(()=>Eh(this.getMessage(i))))).pipe(zh(()=>this.streams.has(a)),Xre({count:R_.MAX_RETRIES,delay:(e,t)=>{let n=e;if(Y.error(`Retry ${t}/${R_.MAX_RETRIES}:`,n.status,n),!(n.status===0||n.status&&n.status>=Tg.BAD_REQUEST&&n.status<Tg.INTERNAL_SERVER_ERROR))throw e;return n.status===Tg.NOT_FOUND&&this.streams.delete(a),n.status===Tg.UNAUTHORIZED?Eh(this.handleSessionRefresh()):Ph(R_.RETRY_DELAY_MS)}}),Yre(()=>{Y.debug(`Terminating stream for ${e} - ${a}`),this.dataLogoff(a)}));return this.streams.get(a).STREAM=c,c}streamState(e,t=()=>{},n=()=>{},r,i=[]){return this.stream(e,t,n,r).pipe(Ih(L_,i))}streamWithoutAutoTeardown(e,t,n,r){return Y.deprecated(`streamWithoutAutoTeardown`,`Please use 'stream' api instead.`,`15.0.0`),this.stream(e,t,n,r)}getMessage(e){return J(this,void 0,void 0,function*(){if(this.ongoingRefresh&&!(yield this.ongoingRefresh))throw Error(`Cannot get message: session refresh failed`);return this.transport.get(this.host,e)})}getMoreRows(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMoreRowsMessage(e);return Y.debug(`HTTP MODE - ${t.MESSAGE_TYPE} message created -> `,t),this.send(t)})}getMoreColumns(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMoreColumnsMessage(e);return this.send(t)})}dataLogoff(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createDataLogoffMessage(e);return this.send(t).then(t=>(this.streams.has(e)&&(Y.debug(`Removing stream ${e}`),this.streams.delete(e)),t))})}getMetadata(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasMetadataFor(e))return Y.debug(`HTTP MODE - Cached metadata retrieved for ${e}`),this.metaCache.getMetadataFor(e);let n=this.messageBuilder.createMetaRequestMessage(e);Y.debug(`HTTP MODE - ${n.MESSAGE_TYPE} (metadata) message created -> `,n);let r=yield this.send(n).then(e=>e.DETAILS);return Object.keys(r).length&&this.metaCache.setMetadataFor(e,r),r})}getJSONSchema(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMetaRequestMessage(e,Pg.JSON_SCHEMA_REQUEST);return Y.debug(`HTTP MODE! - ${t.MESSAGE_TYPE} (json schema) message created -> `,t),this.send(t)})}request(e,t){return J(this,arguments,void 0,function*(e,t,n=!1){let r=Lg(e,t);if(n&&this.metaCache.hasRequestFor(r))return Y.debug(`HTTP MODE - Cached request response retrieved for ${r}`),this.metaCache.getRequestFor(r);let i=this.inFlightRequests.get(r);if(i)return Y.debug(`HTTP MODE - In-flight request collapsed for ${r}`),i;let a=this.messageBuilder.createRequestMessage(e,t);Y.debug(`HTTP MODE! - ${a.MESSAGE_TYPE} (request server) message created -> `,a);let o=this.transport.requestServer(this.host,a).finally(()=>{this.inFlightRequests.delete(r)});this.inFlightRequests.set(r,o);let s=yield o;return n&&s&&this.metaCache.setRequestFor(r,s),s})}getAvailableResources(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasResources())return Y.debug(`HTTP MODE - Cached resources retrieved`),this.metaCache.getResources();let n=this.messageBuilder.createResourcesMessage(e);Y.debug(`HTTP MODE! - ${n.MESSAGE_TYPE} (getResources) message created -> `,n);let r=yield this.send(n);return this.metaCache.setResources(r),r})}commitEvent(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createCommitMessage(e,t);return Y.debug(`HTTP MODE! - ${n.MESSAGE_TYPE} (commit) message created -> `,n),this.send(n).then(t=>(this.maybeTurbo(e,t),t))})}maybeTurbo(e,t){if(!(t?.MESSAGE_TYPE)?.endsWith(`_ACK`))return;if(this.ongoingTurbo[e]){Y.debug(`${e} polling frequency is already accelerated.`);return}let n=this.config.polling.POLLING_MAP[e];if(!(n?.TEMP_FREQUENCY&&n.AMOUNT_OF_POLLS))return;let r=n.TEMP_FREQUENCY,i=r*n.AMOUNT_OF_POLLS,a=JSON.parse(JSON.stringify(this.config.polling.POLLING_INTERVAL_MAP)),o=JSON.parse(JSON.stringify(this.config.polling.POLLING_INTERVAL_MAP));for(let e of n.QUERIES)o[e]=r,a[e]||(a[e]=this.config.polling.POLLING_FREQUENCY);Y.debug(`${e} TRIGGERED -> ENFORCING TURBO | FREQUENCY=${r}ms DURATION=${i}`),this.ongoingTurbo[e]=!0,this.updateIntervals({polling:{POLLING_INTERVAL_MAP:o}}),setTimeout(()=>{Y.debug(`RESTORED ORIGINAL POLLING INTERVALS FOR ${e}`),this.updateIntervals({polling:{POLLING_INTERVAL_MAP:a}}),this.ongoingTurbo[e]=!1},i)}updateIntervals(e){let{POLLING_INTERVAL_MAP:t}=e.polling;t&&(this.config.polling.POLLING_INTERVAL_MAP=t,this.handlePollingIntervalMapUpdate(t))}handlePollingIntervalMapUpdate(e){if(e)for(let t in e){if(!e.hasOwnProperty(t))continue;let n=e[t];this.config.polling.POLLING_INTERVAL_MAP[t]=n,Y.debug(`Setting polling frequency for ${t} = ${n}`),[...this.streams.values()].filter(e=>e.RESOURCE_NAME===t).forEach(e=>(e?.POLLING_FREQUENCY)?.next(n))}}};z_.REAUTH_WAIT_MS=5e3,z_.RETRY_DELAY_MS=1e3,z_.MAX_RETRIES=3,q([C],z_.prototype,`host`,void 0),q([C],z_.prototype,`isWorking`,void 0),q([C],z_.prototype,`_isConnected`,void 0),q([w],z_.prototype,`isConnected`,null),z_=R_=q([_d(0,Ag),_d(1,Bg),_d(2,Og),_d(3,_g),_d(4,_m),_d(5,jie),_d(6,Ug)],z_);let B_=N.createInterface(e=>e.singleton(z_));var V_={url:``,deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},H_=`WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }`,U_=function(e){md(t,e);function t(t,n){var r=e.call(this)||this;if(r._socket=null,t instanceof Bm)r.destination=n,r.source=t;else{var i=r._config=hd({},V_);if(r._output=new qm,typeof t==`string`)i.url=t;else for(var a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);if(!i.WebSocketCtor&&WebSocket)i.WebSocketCtor=WebSocket;else if(!i.WebSocketCtor)throw Error(`no WebSocket constructor can be found`);r.destination=new Zm}return r}return t.prototype.lift=function(e){var n=new t(this._config,this.destination);return n.operator=e,n.source=this,n},t.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new Zm),this._output=new qm},t.prototype.multiplex=function(e,t,n){var r=this;return new Bm(function(i){try{r.next(e())}catch(e){i.error(e)}var a=r.subscribe({next:function(e){try{n(e)&&i.next(e)}catch(e){i.error(e)}},error:function(e){return i.error(e)},complete:function(){return i.complete()}});return function(){try{r.next(t())}catch(e){i.error(e)}a.unsubscribe()}})},t.prototype._connectSocket=function(){var e=this,t=this._config,n=t.WebSocketCtor,r=t.protocol,i=t.url,a=t.binaryType,o=this._output,s=null;try{s=r?new n(i,r):new n(i),this._socket=s,a&&(this._socket.binaryType=a)}catch(e){o.error(e);return}var c=new Sm(function(){e._socket=null,s&&s.readyState===1&&s.close()});s.onopen=function(t){if(!e._socket){s.close(),e._resetState();return}var n=e._config.openObserver;n&&n.next(t);var r=e.destination;e.destination=Nm.create(function(t){if(s.readyState===1)try{var n=e._config.serializer;s.send(n(t))}catch(t){e.destination.error(t)}},function(t){var n=e._config.closingObserver;n&&n.next(void 0),t&&t.code?s.close(t.code,t.reason):o.error(TypeError(H_)),e._resetState()},function(){var t=e._config.closingObserver;t&&t.next(void 0),s.close(),e._resetState()}),r&&r instanceof Zm&&c.add(r.subscribe(e.destination))},s.onerror=function(t){e._resetState(),o.error(t)},s.onclose=function(t){s===e._socket&&e._resetState();var n=e._config.closeObserver;n&&n.next(t),t.wasClean?o.complete():o.error(t)},s.onmessage=function(t){try{var n=e._config.deserializer;o.next(n(t))}catch(e){o.error(e)}}},t.prototype._subscribe=function(e){var t=this,n=this.source;return n?n.subscribe(e):(this._socket||this._connectSocket(),this._output.subscribe(e),e.add(function(){var e=t._socket;t._output.observers.length===0&&(e&&(e.readyState===1||e.readyState===0)&&e.close(),t._resetState())}),e)},t.prototype.unsubscribe=function(){var t=this._socket;t&&(t.readyState===1||t.readyState===0)&&t.close(),this._resetState(),e.prototype.unsubscribe.call(this)},t}(Jm);let W_=1e4,G_=6e4;var K_;(function(e){e.Linear=`linear`,e.Exponential=`exponential`})(K_||(K_={}));let q_=(e,t)=>new Bm(n=>{let r=0,i;function a(){n.next(r),clearTimeout(i),i=setTimeout(a,t(e,r)),r+=1}return a(),()=>{clearTimeout(i)}}),J_=(e,t)=>{let{reconnectInterval:n=W_}=e,r=n>G_?G_:n;return r*2**(t%Math.round(Math.log2(G_/r)))},Y_=e=>{let{reconnectInterval:t=W_}=e;return t>G_?G_:t};var X_=class{constructor(){this.isConfigured=!1,this.isConnecting=!1,this.isConnected=!1,this.isReconnecting=!1,this.reconnectionLimitReached=!1,this.isConnectedSubject=new Ym(this.isConnected)}get hasValidSession(){return this.user.isAuthenticated}get isDisconnected(){return!this.isConnected}get isDisconnectedByServer(){return this.closedClean!==void 0&&!this.closedClean}isConnectedChanged(){var e;this.isConnected&&this.resetClosedState(),this.isConnecting=!1,this.isReconnecting=!1,(e=this.isConnectedSubject)==null||e.next(this.isConnected)}isReconnectingChanged(){this.isReconnecting&&(this.reconnectionLimitReached=!1)}resetClosedState(){this.closedCode=void 0,this.closedReason=void 0,this.closedClean=void 0}serialize(){return{isConfigured:this.isConfigured,isConnecting:this.isConnecting,isConnected:this.isConnected,isDisconnected:this.isDisconnected,isDisconnectedByServer:this.isDisconnectedByServer,isReconnecting:this.isReconnecting,reconnectionLimitReached:this.reconnectionLimitReached,hasValidSession:this.hasValidSession,closedCode:this.closedCode,closedReason:this.closedReason,closedClean:this.closedClean}}onClose(e){this.isConnected=!1,this.closedCode=e.code,this.closedReason=e.reason,this.closedClean=e.wasClean}};q([C],X_.prototype,`isConfigured`,void 0),q([C],X_.prototype,`isConnecting`,void 0),q([C],X_.prototype,`isConnected`,void 0),q([C],X_.prototype,`isReconnecting`,void 0),q([C],X_.prototype,`reconnectionLimitReached`,void 0),q([C],X_.prototype,`closedCode`,void 0),q([C],X_.prototype,`closedReason`,void 0),q([C],X_.prototype,`closedClean`,void 0),q([gg],X_.prototype,`user`,void 0);let Z_=N.createInterface(e=>e.singleton(X_));var Q_=class{constructor(e){this.interval=e}get workerScript(){return`
237
+ `)}`)},5e3);let O_=`reauthActionLock`;var k_;(function(e){e.SUCCESS=`SUCCESS`,e.FAILED=`FAILED`,e.HANDLED_BY_OTHER_TAB=`HANDLED_BY_OTHER_TAB`,e.ALREADY_VALID=`ALREADY_VALID`})(k_||(k_={}));function A_(){let e=parseInt(localStorage.getItem(O_)||`0`);Date.now()-e>3e4&&localStorage.removeItem(O_)}function j_(){return!localStorage.getItem(O_)&&(localStorage.setItem(O_,Date.now().toString()),!0)}function M_(){localStorage.removeItem(O_)}function N_(){return J(this,void 0,void 0,function*(){let e=yield fetch(Bf,{credentials:`include`});return e.status!==401&&(yield e.json()).MESSAGE_TYPE===`EVENT_LOGIN_DETAILS_ACK`})}function P_(){return J(this,void 0,void 0,function*(){return(yield N.getOrCreateDOMContainer().get(Ag).post(zf,{body:JSON.stringify({DETAILS:{},MESSAGE_TYPE:`EVENT_LOGIN_AUTH`})})).MESSAGE_TYPE===`EVENT_LOGIN_AUTH_ACK`})}function F_(){return J(this,arguments,void 0,function*(e={}){let{reloadOnFailure:t=!0}=e;if(A_(),!j_())return k_.HANDLED_BY_OTHER_TAB;try{return(yield N_())?k_.ALREADY_VALID:(yield P_())?k_.SUCCESS:(t&&window.location.reload(),k_.FAILED)}finally{M_()}})}function I_(e){let t=n=>{n.key===O_&&n.newValue===null&&(e(),window.removeEventListener(`storage`,t))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)}let L_=(e,t)=>(t?.ROW&&e&&e.length>0?t.ROW.forEach(t=>{let n=t;if(n&&n.DETAILS){let r=n.DETAILS.ROW_REF,i=n.DETAILS.OPERATION;i===`INSERT`&&(e.find(e=>e.DETAILS?.ROW_REF===r)||e.unshift(n)),i===`DELETE`&&(e=e.filter(e=>t.DETAILS?.ROW_REF!==e.DETAILS?.ROW_REF)),i===`MODIFY`&&(e=e.map(e=>e.DETAILS?.ROW_REF===r?Object.assign(Object.assign({},e),n):e))}}):t&&(!e||e.length===0)&&(e=[...new Set(t.ROW)]),e);var R_;let z_=R_=class{get isConnected(){return this._isConnected}set isConnected(e){this._isConnected=e,this.isConnectedSubject.next(this._isConnected)}constructor(e,t,n,r,i,a,o){this.http=e,this.messageBuilder=t,this.session=n,this.metaCache=r,this.serializer=i,this.config=a,this.transport=o,this.isWorking=!1,this._isConnected=!1,this.isConnectedSubject=new Ym(this._isConnected),this.isConnected$=this.isConnectedSubject?.asObservable(),this.ongoingTurbo={},this.streams=/* @__PURE__ */ new Map,this.inFlightRequests=/* @__PURE__ */ new Map,this.ongoingRefresh=null}handleSessionRefresh(){return this.ongoingRefresh||(this.ongoingRefresh=J(this,void 0,void 0,function*(){let e=this.host;this.disconnect();let t=yield F_();return t===k_.HANDLED_BY_OTHER_TAB&&(yield new Promise(e=>{setTimeout(e,R_.REAUTH_WAIT_MS)}),t=yield F_()),t===k_.SUCCESS||t===k_.ALREADY_VALID?(this.connect(e),!0):!1}).finally(()=>{this.ongoingRefresh=null})),this.ongoingRefresh}checkHost(){return J(this,void 0,void 0,function*(){try{return this.getMessage({MESSAGE_TYPE:Ng.HEARTBEAT_PING,SOURCE_REF:`host check`}).then(e=>e.MESSAGE_TYPE===Ng.HEARTBEAT_PONG)}catch(e){return Y.error(e),!1}})}send(e,t){return J(this,void 0,void 0,function*(){if(this.ongoingRefresh&&!(yield this.ongoingRefresh))throw Error(`Cannot send message: session refresh failed`);return this.transport.post(this.host,e)})}httpMode(){return!0}setValidSession(e){Y.deprecated(`setValidSession`,`Please refrain from calling this API as this state is managed internally.`,`15.0.0`)}connect(e){return J(this,void 0,void 0,function*(){return this.host=this.transport.toHttpHost(e),this.checkHost().then(e=>(this.isConnected=e,this.session.setSessionStorageItem(`hostUrl`,this.host),e))})}disconnect(){this.isConnected=!1,this.streams.clear(),this.ongoingTurbo={},this.host=void 0}snapshot(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createDataLogonMessage(e,t);return Y.debug(`HTTP MODE - ${n.MESSAGE_TYPE} (snapshot) message created -> `,n),this.send(n).then(e=>(this.dataLogoff(n.SOURCE_REF).catch(e=>Y.error(e)),e))})}stream(e,t,n,r){let i=this.messageBuilder.createDataLogonMessage(e,r);Y.debug(`HTTP MODE - ${i.MESSAGE_TYPE} (stream) message created -> `,i);let a=i.SOURCE_REF,o=this.config.polling?.POLLING_INTERVAL_MAP?.[e]||this.config.polling.POLLING_FREQUENCY;this.streams.set(a,{SOURCE_REF:a,POLLING_FREQUENCY:new Ym(o),RESOURCE_NAME:e});let s=this.streams.get(a).POLLING_FREQUENCY,c=Nh(Eh(this.send(i)),s.pipe(Fh(()=>document.visibilityState===`visible`)).pipe(Rh(e=>qre(e))).pipe(Rh(()=>Eh(this.getMessage(i))))).pipe(zh(()=>this.streams.has(a)),Xre({count:R_.MAX_RETRIES,delay:(e,t)=>{let n=e;if(Y.error(`Retry ${t}/${R_.MAX_RETRIES}:`,n.status,n),!(n.status===0||n.status&&n.status>=Tg.BAD_REQUEST&&n.status<Tg.INTERNAL_SERVER_ERROR))throw e;return n.status===Tg.NOT_FOUND&&this.streams.delete(a),n.status===Tg.UNAUTHORIZED?Eh(this.handleSessionRefresh()):Ph(R_.RETRY_DELAY_MS)}}),Yre(()=>{Y.debug(`Terminating stream for ${e} - ${a}`),this.dataLogoff(a)}));return this.streams.get(a).STREAM=c,c}streamState(e,t=()=>{},n=()=>{},r,i=[]){return this.stream(e,t,n,r).pipe(Ih(L_,i))}streamWithoutAutoTeardown(e,t,n,r){return Y.deprecated(`streamWithoutAutoTeardown`,`Please use 'stream' api instead.`,`15.0.0`),this.stream(e,t,n,r)}getMessage(e){return J(this,void 0,void 0,function*(){if(this.ongoingRefresh&&!(yield this.ongoingRefresh))throw Error(`Cannot get message: session refresh failed`);return this.transport.get(this.host,e)})}getMoreRows(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMoreRowsMessage(e);return Y.debug(`HTTP MODE - ${t.MESSAGE_TYPE} message created -> `,t),this.send(t)})}getMoreColumns(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMoreColumnsMessage(e);return this.send(t)})}dataLogoff(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createDataLogoffMessage(e);return this.send(t).then(t=>(this.streams.has(e)&&(Y.debug(`Removing stream ${e}`),this.streams.delete(e)),t))})}getMetadata(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasMetadataFor(e))return Y.debug(`HTTP MODE - Cached metadata retrieved for ${e}`),this.metaCache.getMetadataFor(e);let n=this.messageBuilder.createMetaRequestMessage(e);Y.debug(`HTTP MODE - ${n.MESSAGE_TYPE} (metadata) message created -> `,n);let r=yield this.send(n).then(e=>e.DETAILS);return Object.keys(r).length&&this.metaCache.setMetadataFor(e,r),r})}getJSONSchema(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMetaRequestMessage(e,Pg.JSON_SCHEMA_REQUEST);return Y.debug(`HTTP MODE! - ${t.MESSAGE_TYPE} (json schema) message created -> `,t),this.send(t)})}request(e,t){return J(this,arguments,void 0,function*(e,t,n=!1){let r=Lg(e,t);if(n&&this.metaCache.hasRequestFor(r))return Y.debug(`HTTP MODE - Cached request response retrieved for ${r}`),this.metaCache.getRequestFor(r);let i=this.inFlightRequests.get(r);if(i)return Y.debug(`HTTP MODE - In-flight request collapsed for ${r}`),i;let a=this.messageBuilder.createRequestMessage(e,t);Y.debug(`HTTP MODE! - ${a.MESSAGE_TYPE} (request server) message created -> `,a);let o=this.transport.requestServer(this.host,a).finally(()=>{this.inFlightRequests.delete(r)});this.inFlightRequests.set(r,o);let s=yield o;return n&&s&&this.metaCache.setRequestFor(r,s),s})}getAvailableResources(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasResources())return Y.debug(`HTTP MODE - Cached resources retrieved`),this.metaCache.getResources();let n=this.messageBuilder.createResourcesMessage(e);Y.debug(`HTTP MODE! - ${n.MESSAGE_TYPE} (getResources) message created -> `,n);let r=yield this.send(n);return this.metaCache.setResources(r),r})}commitEvent(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createCommitMessage(e,t);return Y.debug(`HTTP MODE! - ${n.MESSAGE_TYPE} (commit) message created -> `,n),this.send(n).then(t=>(this.maybeTurbo(e,t),t))})}maybeTurbo(e,t){if(!(t?.MESSAGE_TYPE)?.endsWith(`_ACK`))return;if(this.ongoingTurbo[e]){Y.debug(`${e} polling frequency is already accelerated.`);return}let n=this.config.polling.POLLING_MAP[e];if(!(n?.TEMP_FREQUENCY&&n.AMOUNT_OF_POLLS))return;let r=n.TEMP_FREQUENCY,i=r*n.AMOUNT_OF_POLLS,a=JSON.parse(JSON.stringify(this.config.polling.POLLING_INTERVAL_MAP)),o=JSON.parse(JSON.stringify(this.config.polling.POLLING_INTERVAL_MAP));for(let e of n.QUERIES)o[e]=r,a[e]||(a[e]=this.config.polling.POLLING_FREQUENCY);Y.debug(`${e} TRIGGERED -> ENFORCING TURBO | FREQUENCY=${r}ms DURATION=${i}`),this.ongoingTurbo[e]=!0,this.updateIntervals({polling:{POLLING_INTERVAL_MAP:o}}),setTimeout(()=>{Y.debug(`RESTORED ORIGINAL POLLING INTERVALS FOR ${e}`),this.updateIntervals({polling:{POLLING_INTERVAL_MAP:a}}),this.ongoingTurbo[e]=!1},i)}updateIntervals(e){let{POLLING_INTERVAL_MAP:t}=e.polling;t&&(this.config.polling.POLLING_INTERVAL_MAP=t,this.handlePollingIntervalMapUpdate(t))}handlePollingIntervalMapUpdate(e){if(e)for(let t in e){if(!e.hasOwnProperty(t))continue;let n=e[t];this.config.polling.POLLING_INTERVAL_MAP[t]=n,Y.debug(`Setting polling frequency for ${t} = ${n}`),[...this.streams.values()].filter(e=>e.RESOURCE_NAME===t).forEach(e=>(e?.POLLING_FREQUENCY)?.next(n))}}};z_.REAUTH_WAIT_MS=5e3,z_.RETRY_DELAY_MS=1e3,z_.MAX_RETRIES=3,q([C],z_.prototype,`host`,void 0),q([C],z_.prototype,`isWorking`,void 0),q([C],z_.prototype,`_isConnected`,void 0),q([w],z_.prototype,`isConnected`,null),z_=R_=q([_d(0,Ag),_d(1,Bg),_d(2,Og),_d(3,_g),_d(4,_m),_d(5,jie),_d(6,Ug)],z_);let B_=N.createInterface(e=>e.singleton(z_));var V_={url:``,deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},H_=`WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }`,U_=function(e){md(t,e);function t(t,n){var r=e.call(this)||this;if(r._socket=null,t instanceof Bm)r.destination=n,r.source=t;else{var i=r._config=hd({},V_);if(r._output=new qm,typeof t==`string`)i.url=t;else for(var a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);if(!i.WebSocketCtor&&WebSocket)i.WebSocketCtor=WebSocket;else if(!i.WebSocketCtor)throw Error(`no WebSocket constructor can be found`);r.destination=new Zm}return r}return t.prototype.lift=function(e){var n=new t(this._config,this.destination);return n.operator=e,n.source=this,n},t.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new Zm),this._output=new qm},t.prototype.multiplex=function(e,t,n){var r=this;return new Bm(function(i){try{r.next(e())}catch(e){i.error(e)}var a=r.subscribe({next:function(e){try{n(e)&&i.next(e)}catch(e){i.error(e)}},error:function(e){return i.error(e)},complete:function(){return i.complete()}});return function(){try{r.next(t())}catch(e){i.error(e)}a.unsubscribe()}})},t.prototype._connectSocket=function(){var e=this,t=this._config,n=t.WebSocketCtor,r=t.protocol,i=t.url,a=t.binaryType,o=this._output,s=null;try{s=r?new n(i,r):new n(i),this._socket=s,a&&(this._socket.binaryType=a)}catch(e){o.error(e);return}var c=new Sm(function(){e._socket=null,s&&s.readyState===1&&s.close()});s.onopen=function(t){if(!e._socket){s.close(),e._resetState();return}var n=e._config.openObserver;n&&n.next(t);var r=e.destination;e.destination=Nm.create(function(t){if(s.readyState===1)try{var n=e._config.serializer;s.send(n(t))}catch(t){e.destination.error(t)}},function(t){var n=e._config.closingObserver;n&&n.next(void 0),t&&t.code?s.close(t.code,t.reason):o.error(TypeError(H_)),e._resetState()},function(){var t=e._config.closingObserver;t&&t.next(void 0),s.close(),e._resetState()}),r&&r instanceof Zm&&c.add(r.subscribe(e.destination))},s.onerror=function(t){e._resetState(),o.error(t)},s.onclose=function(t){s===e._socket&&e._resetState();var n=e._config.closeObserver;n&&n.next(t),t.wasClean?o.complete():o.error(t)},s.onmessage=function(t){try{var n=e._config.deserializer;o.next(n(t))}catch(e){o.error(e)}}},t.prototype._subscribe=function(e){var t=this,n=this.source;return n?n.subscribe(e):(this._socket||this._connectSocket(),this._output.subscribe(e),e.add(function(){var e=t._socket;t._output.observers.length===0&&(e&&(e.readyState===1||e.readyState===0)&&e.close(),t._resetState())}),e)},t.prototype.unsubscribe=function(){var t=this._socket;t&&(t.readyState===1||t.readyState===0)&&t.close(),this._resetState(),e.prototype.unsubscribe.call(this)},t}(Jm);let W_=1e4,G_=6e4;var K_;(function(e){e.Linear=`linear`,e.Exponential=`exponential`})(K_||(K_={}));let q_=(e,t)=>new Bm(n=>{let r=0,i;function a(){n.next(r),clearTimeout(i),i=setTimeout(a,t(e,r)),r+=1}return a(),()=>{clearTimeout(i)}}),J_=(e,t)=>{let{reconnectInterval:n=W_}=e,r=n>G_?G_:n;return r*2**(t%Math.round(Math.log2(G_/r)))},Y_=e=>{let{reconnectInterval:t=W_}=e;return t>G_?G_:t};var X_=class{constructor(){this.isConfigured=!1,this.isConnecting=!1,this.isConnected=!1,this.isReconnecting=!1,this.reconnectionLimitReached=!1,this.isConnectedSubject=new Ym(this.isConnected)}get hasValidSession(){return this.user.isAuthenticated}get isDisconnected(){return!this.isConnected}get isDisconnectedByServer(){return this.closedClean!==void 0&&!this.closedClean}isConnectedChanged(){var e;this.isConnected&&this.resetClosedState(),this.isConnecting=!1,this.isReconnecting=!1,(e=this.isConnectedSubject)==null||e.next(this.isConnected)}isReconnectingChanged(){this.isReconnecting&&(this.reconnectionLimitReached=!1)}resetClosedState(){this.closedCode=void 0,this.closedReason=void 0,this.closedClean=void 0}serialize(){return{isConfigured:this.isConfigured,isConnecting:this.isConnecting,isConnected:this.isConnected,isDisconnected:this.isDisconnected,isDisconnectedByServer:this.isDisconnectedByServer,isReconnecting:this.isReconnecting,reconnectionLimitReached:this.reconnectionLimitReached,hasValidSession:this.hasValidSession,closedCode:this.closedCode,closedReason:this.closedReason,closedClean:this.closedClean}}onClose(e){this.isConnected=!1,this.closedCode=e.code,this.closedReason=e.reason,this.closedClean=e.wasClean}};q([C],X_.prototype,`isConfigured`,void 0),q([C],X_.prototype,`isConnecting`,void 0),q([C],X_.prototype,`isConnected`,void 0),q([C],X_.prototype,`isReconnecting`,void 0),q([C],X_.prototype,`reconnectionLimitReached`,void 0),q([C],X_.prototype,`closedCode`,void 0),q([C],X_.prototype,`closedReason`,void 0),q([C],X_.prototype,`closedClean`,void 0),q([gg],X_.prototype,`user`,void 0);let Z_=N.createInterface(e=>e.singleton(X_));var Q_=class{constructor(e){this.interval=e}get workerScript(){return`
238
238
  const startTime = Date.now();
239
239
  setInterval(function() {
240
240
  self.postMessage(Date.now() - startTime);
@@ -242,7 +242,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
242
242
  `}start(e){this.stop(),this.runWorker(e)}stop(){this.worker&&(this.worker.terminate(),delete this.worker)}runWorker(e){this.worker||(this.worker=new Worker(URL.createObjectURL(new Blob([this.workerScript],{type:`text/javascript`}))),this.worker.onmessage=t=>e(t.data))}},$_=class extends qm{constructor(){super()}},ev=class{constructor(e,t,n,r){this._message=e,this._onMessage=t,this._onError=n,this._isSubscription=r}get sentMessage(){return this._message}get onReceivedMessage(){return this._onMessage}get onReceivedError(){return this._onError}get isSubscription(){return this._isSubscription}};let tv=class{get isConfigured(){return this.status.isConfigured}get isConnecting(){return this.status.isConnecting}get isConnected(){return this.status.isConnected}get isConnectedSubject(){return this.status.isConnectedSubject}get isDisconnected(){return this.status.isDisconnected}get isDisconnectedByServer(){return this.status.isDisconnectedByServer}get isReconnecting(){return this.status.isReconnecting}get hasValidSession(){return Y.deprecated(`get hasValidSession`,"Use `User.isAuthenticated` from `@genesislcap/foundation-user` instead.",`15.0.0`),this.user.isAuthenticated}set hasValidSession(e){Y.deprecated(`set hasValidSession`,`Please refrain from calling this API as this state is managed internally.`,`15.0.0`)}get host(){return this.url??Lf}constructor(e,t,n,r,i,a,o){this.messageBuilder=e,this.session=t,this.serializer=n,this.uuid=r,this.status=i,this.user=a,this.config=o,this.defaultInterval=1e4,this.secondsMultiplier=1e3,this.heartbeatIsEnabled=!0,this.heartbeatInterval=this.defaultInterval,this.socketMessages=()=>this.wsMessages}get heartbeatLoggingIsEnabled(){return this.connectOptions?.enableHeartbeatLogging??!1}get messageLoggingIsEnabled(){return this.connectOptions?.enableMessageLogging??!1}connect(e=Lf,t,n){if(this.url=e,this.connectOptions=t??this.config.connect,this.reconnectOptions=n??this.config.reconnect,!this.config.isWebSocketExpression?.test(this.host)){Y.error(`Specified host (${this.host}) is not valid WebSocket url. Connection will not proceed.`),Y.warn(`Make sure the host url starts with wss:// or ws://`);return}return new Promise(e=>{var t;Y.info(`${this.isReconnecting?`Reconnecting`:`Connecting`} to ${this.url}`),this.status.isConnecting=!this.isReconnecting,(!this.isReconnecting||!this.reconnectOptions?.reconnectStreams)&&this.cleanMessages(),(t=this.socketSubscription)==null||t.unsubscribe(),this.websocket=new U_({url:this.url,openObserver:{next:()=>{this.session.setSessionStorageItem(`hostUrl`,this.url),this.status.isConnected=!0,this.prepareHeartbeat(),Y.info(`WebSocket connection is now open`),e(this.isConnected)}},closeObserver:{next:t=>{this.status.onClose(t),this.isDisconnectedByServer&&Y.info(`WebSocket connection was closed due an error - Code: ${t.code} ${t.reason?` | Reason: `+t.reason:``}`),e(this.isConnected)}},serializer:e=>this.serializer.serialize(e),deserializer:e=>this.serializer.deserialize(e)});let n=e=>J(this,void 0,void 0,function*(){let t=`Response Message received for SourceRef: ${e.SOURCE_REF} | MessageType: ${e.MESSAGE_TYPE}`;this.logMessageTypeFlow(e.MESSAGE_TYPE,Y.info,t);let{SOURCE_REF:n,MESSAGE_TYPE:r}=e,i=this.getMessageHandler(n,r);if(!i){e.MESSAGE_TYPE===Ng.MSG_NACK&&e.ERROR&&e.ERROR.forEach(t=>{Y.error(`MessageType: ${e.MESSAGE_TYPE} | Error Details:`,t)});return}let a=!1;switch(e.MESSAGE_TYPE){case Pg.EVENT_LOGIN_AUTH_ACK:{let t=e.DETAILS;t.HEARTBEAT_INTERVAL_SECS&&this.connectOptions?.heartbeatInterval===void 0&&(this.heartbeatInterval=t.HEARTBEAT_INTERVAL_SECS*this.secondsMultiplier,this.prepareHeartbeat());break}case Ng.LOGOUT_ACK:i.onReceivedMessage.call(this,e),this.cleanMessages();return;case Ng.LOGON_ACK:return;case Ng.LOGOFF_ACK:break;case Ng.QUERY_UPDATE:i.isSubscription||this.sendDataLogoff(n);break;case Ng.MSG_NACK:case Ng.LOGON_NACK:a=!0}a?i.onReceivedError.call(this,{receivedMessage:e,sentMessage:i.sentMessage}):i.onReceivedMessage.call(this,e),this.wsMessages.next(e),i.isSubscription||this.removeMessageHandler(n)}),r=e=>{Y.debug(`Error found: `,e),this.reconnect()},i=()=>{if(this.isDisconnectedByServer&&this.connectOptions?.alwaysOn){this.reconnect();return}Y.info(`Connection is now closed`)};this.socketSubscription=this.websocket.subscribe(this.connectOptions?.connectObserver??{next:n,error:r,complete:i}),this.status.isConfigured=!0})}handleExpiredSession(){return J(this,void 0,void 0,function*(){if(this.session.getSessionStorageItem(`refreshToken`)){let e=this.messageBuilder.createRefreshTokenMessage(),t=yield this.send(e);this.session.setAuthResult(t),this.updateSessionAndSubscriptions(t)}else yield this.handleCookieBasedReauth()})}handleCookieBasedReauth(){return J(this,void 0,void 0,function*(){let e=yield F_();if(e===k_.HANDLED_BY_OTHER_TAB){I_(()=>this.connect());return}e!==k_.FAILED&&(yield this.connect())})}updateSessionAndSubscriptions(e){e?.MESSAGE_TYPE===Pg.EVENT_LOGIN_AUTH_ACK&&this.wsMessageHandlers.forEach(t=>{t.isSubscription&&(t.sentMessage.SESSION_AUTH_TOKEN=e.SESSION_AUTH_TOKEN,this.websocket.next(t.sentMessage))})}prepareHeartbeat(){this.heartbeatTicker&&this.heartbeatTicker.stop();let e=()=>J(this,void 0,void 0,function*(){if(!this.isConnected)return;let e=this.messageBuilder.createHeartbeatPingMessage(this.connectOptions?.verboseHeartbeat);this.connectOptions?.heartbeatPingCallback&&this.connectOptions.heartbeatPingCallback(e);let t=yield this.send(e);this.user.isAuthenticated&&!t.IS_AUTHENTICATED&&this.handleExpiredSession(),this.connectOptions?.heartbeatPongCallback&&this.connectOptions.heartbeatPongCallback(t),this.heartbeatIsEnabled=t.MESSAGE_TYPE===Ng.HEARTBEAT_PONG&&t.SOURCE_REF===e.SOURCE_REF});if(this.connectOptions?.enableHeartbeat??this.heartbeatIsEnabled){let t=this.connectOptions?.heartbeatInterval??this.heartbeatInterval;this.heartbeatTicker=new Q_(t),this.heartbeatTicker.start(()=>{this.websocket&&this.isConnected&&(e(),this.heartbeatLoggingIsEnabled&&Y.debug(`Sending a heartbeat ping every ${t} ms`))})}}reconnect(){let e=!this.connectOptions?.alwaysOn&&this.connectOptions?.enableHeartbeat===!1;if(this.isReconnecting||e)return;this.status.isReconnecting=!0;let t=this.reconnectOptions?.reconnectStrategy===K_.Exponential?J_:Y_;this.isConnectedSubject.asObservable().pipe(Rh(e=>e?Dh(-1):q_(this.reconnectOptions,t).pipe(Mh(e=>{let t;return t=this.connectOptions?.alwaysOn?e+1:this.reconnectOptions?.reconnectAttempts??10,e<t?Dh(e):(this.status.reconnectionLimitReached=!0,Oh(()=>/* @__PURE__ */ Error(`Max reconnect attempts ${t} reached.`)))}))),zh(()=>this.websocket&&!this.isConnected)).subscribe(this.reconnectOptions?.reconnectObserver??{next:e=>{Y.debug(`Attempt no. ${e+1} to reconnect`),this.websocket.complete(),this.connect(this.url,this.connectOptions,this.reconnectOptions)},error:e=>{var t;Y.debug(e),(t=this.socketSubscription)==null||t.unsubscribe(),this.status.isReconnecting=!1},complete:()=>{Y.info(this.isConnected?`Reconnected`:`Disconnected`),this.status.isReconnecting=!1,this.wsMessageHandlers.forEach(e=>{e.isSubscription&&this.websocket.next(e.sentMessage)})}})}reset(){this.status.isConnected=!1,this.status.isConfigured=!1,this.websocket&&this.websocket.complete(),this.websocket=null,this.cleanMessages()}cleanMessages(){this.wsMessages&&this.wsMessages.complete(),this.wsMessages=new $_,this.wsMessageHandlers=/* @__PURE__ */ new Map}send(e,t=!0){if(!this.isConnected)return Promise.reject(/* @__PURE__ */ Error(`WebSocket connection is closed`));let n=`Sending Message for SourceRef: ${e.SOURCE_REF} | MessageType: ${e.MESSAGE_TYPE}`;return this.logMessageTypeFlow(e.MESSAGE_TYPE,Y.info,n),new Promise((n,r)=>{t&&this.setMessageHandler(e,e=>{n(e)},e=>{r(e)}),this.websocket.next(e)})}sendForStream(e,t,n,r){if(!this.isConnected)return Oh(()=>/* @__PURE__ */ Error(`WebSocket connection is closed`));let i=`Sending Message (stream) for SourceRef: ${e.SOURCE_REF} | MessageType: ${e.MESSAGE_TYPE}`;return this.logMessageTypeFlow(e.MESSAGE_TYPE,Y.info,i),this.setMessageHandler(e,t,n,!0),x.queueUpdate(()=>this.websocket.next(e)),new Bm(t=>{let n=this.wsMessages.pipe(Fh(t=>t.SOURCE_REF===e.SOURCE_REF)).subscribe({next:e=>{t.next(e)},error:e=>{t.error(e)},complete:()=>{t.complete()}});return()=>{n.unsubscribe(),this.sendDataLogoff(e.SOURCE_REF),this.removeMessageHandler(e.SOURCE_REF),r&&r()}})}sendForStreamWithoutTeardown(e,t,n){if(!this.isConnected)return Oh(()=>/* @__PURE__ */ Error(`WebSocket connection is closed`));let r=`Sending Message (stream) for SourceRef: ${e.SOURCE_REF} | MessageType: ${e.MESSAGE_TYPE}`;return this.logMessageTypeFlow(e.MESSAGE_TYPE,Y.info,r),this.setMessageHandler(e,t,n,!0),this.websocket.next(e),this.wsMessages.pipe(Fh(t=>t.SOURCE_REF===e.SOURCE_REF))}setMessageHandler(e,t,n,r=!1){let i=`Setting Message Handler for SourceRef: ${e.SOURCE_REF} | MessageType: ${e.MESSAGE_TYPE}`;this.logMessageTypeFlow(e.MESSAGE_TYPE,Y.debug,i),this.wsMessageHandlers.set(e.SOURCE_REF,new ev(e,t,n,r))}sendDataLogoff(e){this.send(this.messageBuilder.createDataLogoffMessage(e),!1)}removeMessageHandler(e){this.wsMessageHandlers.delete(e)}getMessageHandler(e,t){let n=`Getting Message Handler for SourceRef: ${e} | MessageType: ${t}`;return this.logMessageTypeFlow(t,Y.debug,n),this.wsMessageHandlers.get(e)}logMessageTypeFlow(e,t,n){switch(e){case Pg.DATA_LOGOFF:t(n);break;case Ng.HEARTBEAT_PING:case Ng.HEARTBEAT_PONG:this.heartbeatLoggingIsEnabled&&t(n);break;default:this.messageLoggingIsEnabled&&t(n)}}};q([C],tv.prototype,`websocket`,void 0),q([C],tv.prototype,`wsMessages`,void 0),q([C],tv.prototype,`wsMessageHandlers`,void 0),q([Ag],tv.prototype,`http`,void 0),q([C],tv.prototype,`heartbeatIsEnabled`,void 0),tv=q([_d(0,Bg),_d(1,Og),_d(2,_m),_d(3,fg),_d(4,Z_),_d(5,gg),_d(6,wg)],tv);let nv=N.createInterface(e=>e.singleton(tv));function rv(){return N.getOrCreateDOMContainer().get(nv)}let iv=class{get isConnected(){return this.socket.isConnected}get isConnectedSubject(){return this.socket.isConnectedSubject}get isConnected$(){return this.socket.isConnectedSubject?.asObservable()}get host(){return this.socket.host}constructor(e,t,n,r,i,a){this.socket=e,this.messageBuilder=t,this.metaCache=n,this.events=r,this.config=i,this.transport=a,this.isWorking=!1,this.inFlightRequests=/* @__PURE__ */ new Map}httpMode(){return!1}get useHttpReqRep(){return If===`true`||Mf(`forceHttpReqRep`)}get httpHost(){return this.transport.toHttpHost(this.socket.host)}sendReqRep(e){return this.useHttpReqRep?this.transport.post(this.httpHost,e):this.socket.send(e)}setValidSession(e){Y.deprecated(`setValidSession`,`Please refrain from calling this API as this state is managed internally.`,`15.0.0`)}send(e,t){return this.socket.send(e,t)}connect(){return J(this,arguments,void 0,function*(e=Lf){return this.socket.reset(),this.socket.connect(e,this.config.connect,this.config.reconnect)})}disconnect(){this.socket.reset()}snapshot(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createDataLogonMessage(e,t);return Y.debug(`${n.MESSAGE_TYPE} (snapshot) message created -> `,n),this.socket.send(n)})}stream(e,t,n,r){let i=this.messageBuilder.createDataLogonMessage(e,r);Y.debug(`${i.MESSAGE_TYPE} (stream) message created -> `,i);let a=performance.now(),o=null,s=this.socket.sendForStream(i,(...n)=>{o===null&&(o=performance.now(),Y.debug(`[stream:${e}] time to initial response: ${(o-a).toFixed(2)}ms`)),t(...n)},t=>{n(t),this.events.onStreamErrorEvent(e,s,t)},()=>{this.events.onStreamCompleteEvent(e,s)});return this.events.onStreamEvent(e,i,s,{onMessage:t,onError:n}),s}streamState(e,t=()=>{},n=()=>{},r,i=[]){return this.stream(e,t,n,r).pipe(Ih(L_,i))}streamWithoutAutoTeardown(e,t,n,r){Y.deprecated(`streamWithoutAutoTeardown`,`Please use 'stream' api instead.`,`15.0.0`);let i=this.messageBuilder.createDataLogonMessage(e,r);Y.debug(`${i.MESSAGE_TYPE} (stream without auto-teardown) message created -> `,i);let a=this.socket.sendForStreamWithoutTeardown(i,t,t=>{n(t),this.events.onStreamErrorEvent(e,a,t)});return this.events.onStreamEvent(e,i,a,{onMessage:t,onError:n}),a}getMoreRows(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createMoreRowsMessage(e,t);return Y.debug(`${n.MESSAGE_TYPE} message created -> `,n),this.socket.send(n,!1)})}getMoreColumns(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createMoreColumnsMessage(e);return this.socket.send(t)})}dataLogoff(e){return J(this,void 0,void 0,function*(){let t=this.messageBuilder.createDataLogoffMessage(e);return Y.debug(`${t.MESSAGE_TYPE} message created -> `,t),this.socket.send(t)})}getMetadata(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasMetadataFor(e))return Y.debug(`Cached metadata retrieved for ${e}`),this.metaCache.getMetadataFor(e);let n=this.messageBuilder.createMetaRequestMessage(e);Y.debug(`${n.MESSAGE_TYPE} (metadata) message created -> `,n);let r,i;try{this.isWorking=!0,r=(yield this.sendReqRep(n))?.DETAILS??{},Object.keys(r).length&&this.metaCache.setMetadataFor(e,r)}catch(e){throw i=e,Y.error(e),e instanceof Error?e:Error(String(e))}finally{this.events.onMetadataEvent(e,n,i),this.isWorking=!1}return r})}getJSONSchema(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasJsonSchemaFor(e))return Y.debug(`Cached JsonSchema retrieved for ${e}`),this.metaCache.getJsonSchemaFor(e);let n=this.messageBuilder.createMetaRequestMessage(e,Pg.JSON_SCHEMA_REQUEST);Y.debug(`${n.MESSAGE_TYPE} (json schema) message created -> `,n);let r;try{this.isWorking=!0,r=(yield this.sendReqRep(n))??{},Object.keys(r).length&&this.metaCache.setJsonSchemaFor(e,r)}catch(e){Y.error(e)}finally{this.isWorking=!1}return r})}request(e,t){return J(this,arguments,void 0,function*(e,t,n=!1){let r=Lg(e,t);if(n&&this.metaCache.hasRequestFor(r))return Y.debug(`Cached request response retrieved for ${r}`),this.metaCache.getRequestFor(r);let i=this.inFlightRequests.get(r);if(i)return Y.debug(`In-flight request collapsed for ${r}`),i;let a=this.messageBuilder.createRequestMessage(e,t);Y.debug(`${a.MESSAGE_TYPE} (request server) message created -> `,a);let o=(this.useHttpReqRep?this.transport.requestServer(this.httpHost,a):this.socket.send(a)).finally(()=>{this.inFlightRequests.delete(r)});this.inFlightRequests.set(r,o);let s=yield o;return n&&s&&this.metaCache.setRequestFor(r,s),s})}getAvailableResources(e){return J(this,arguments,void 0,function*(e,t=!0){if(t&&this.metaCache.hasResources())return Y.debug(`Cached resources retrieved`),this.metaCache.getResources();let n=this.messageBuilder.createResourcesMessage(e);Y.debug(`${n.MESSAGE_TYPE} (resources) message created -> `,n);let r=yield this.sendReqRep(n);return this.metaCache.setResources(r),r})}commitEvent(e,t){return J(this,void 0,void 0,function*(){let n=this.messageBuilder.createCommitMessage(e,t);Y.debug(`${n.MESSAGE_TYPE} (commit) message created -> `,n);let r=this.sendReqRep(n);return this.events.onCommitEvent(e,n),r.then(t=>(this.events.onCommitResponseEvent(e,t),t))})}};q([C],iv.prototype,`isWorking`,void 0),iv=q([_d(0,nv),_d(1,Bg),_d(2,_g),_d(3,bie),_d(4,wg),_d(5,Ug)],iv);let av=Ff===`true`||Mf(`forceHttp`),ov=N.createInterface(e=>e.singleton(iv)),sv=N.createInterface(e=>av?e.aliasTo(B_):e.aliasTo(ov));function cv(){return N.getOrCreateDOMContainer().get(sv)}var lv=class{serialize(e){return Y.deprecated(`serialize`,"Use `serialize` from `JSONSerializer` from `@genesislcap/foundation-utils` instead."),JSON.stringify(e)}deserialize(e){return Y.deprecated(`deserialize`,"Use `deserialize` from `JSONSerializer` from `@genesislcap/foundation-utils` instead."),e?typeof e==`string`?JSON.parse(e):e.data?JSON.parse(e.data):e.text().then(e=>JSON.parse(e)):Promise.resolve({})}};N.createInterface(e=>e.singleton(lv));
243
243
  /*! js-cookie v3.0.7 | MIT */
244
244
  function uv(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)r!==`__proto__`&&(e[r]=n[r])}return e}var dv={read:function(e){return e[0]===`"`&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function fv(e,t){function n(n,r,i){if(typeof document<`u`){i=uv({},t,i),typeof i.expires==`number`&&(i.expires=new Date(Date.now()+i.expires*864e5)),i.expires&&(i.expires=i.expires.toUTCString()),n=encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a=``;for(var o in i)i[o]&&(a+=`; `+o,i[o]!==!0&&(a+=`=`+i[o].split(`;`)[0]));return document.cookie=n+`=`+e.write(r,n)+a}}function r(t){if(!(typeof document>`u`||arguments.length&&!t)){for(var n=document.cookie?document.cookie.split(`; `):[],r={},i=0;i<n.length;i++){var a=n[i].split(`=`),o=a.slice(1).join(`=`);try{var s=decodeURIComponent(a[0]);if(s in r||(r[s]=e.read(o,s)),t===s)break}catch{}}return t?r[t]:r}}return Object.create({set:n,get:r,remove:function(e,t){n(e,``,uv({},t,{expires:-1}))},withAttributes:function(e){return fv(this.converter,uv({},this.attributes,e))},withConverter:function(e){return fv(uv({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var pv=fv(dv,{path:`/`});let mv=N.createInterface();function hv(){return navigator!=null&&navigator.credentials?`PasswordCredential`in window||(Y.warn(`PasswordCredential not available in this browser.`),!1):(Y.warn(`CredentialsContainer not available in this browser.`),!1)}function gv(e=``,t=`:`,n){return e.split(t,n).map(e=>e.trim()).filter(e=>e!==``)}function _v(e,t=`:`){let n=typeof e==`string`&&e.trim();return n?n.includes(t):!1}function vv(e,t=`:`){return typeof e==`string`&&e.trim()?(e.match(new RegExp(t,`g`))||[]).length:0}function yv(e,t=`:`){for(let n of e)if(_v(n,t))return n;return e.find(e=>typeof e==`string`&&e.trim()!==``)}function bv(e,t,n){let r=typeof e==`string`&&e.trim();return!r||n&&!r.includes(n)||vv(r)>1?n&&t&&n!==t?`${t}:${n}`:t||n:r}function xv(e=`credential`){Y.warn(`Unable to migrate legacy ${e} to latest format. Please remove from your browser.`)}let Sv={password:!0,mediation:`optional`},Cv={cookie:{path:`/`,name:`credentials`,expires:7300,storePasswords:!1}},wv=class{constructor(e,t=Cv){this.session=e,this.config=t}createBasicCredentials(e){return{type:jg.BASIC,username:e.username,password:e.password,mfaToken:this.getMFAToken()}}createRefreshCredentials(e){return{type:jg.REFRESH,username:e?.username??this.getUsername(),refreshToken:e?.refreshToken??this.getRefreshToken(),mfaToken:e?.mfaToken??this.getMFAToken()}}createSSOCredentials(e){return{type:jg.SSO,ssoToken:e?.ssoToken??this.getSSOToken()}}validateBasicCredentials(e){return e&&!!e.username&&!!e.password}validateRefreshCredentials(e){return e&&!!e.refreshToken&&!!e.username}validateSSOCredentials(e){return e&&!!e.ssoToken}validateUserCredentialData(e,t){let n=e&&!!e.id&&!!e.name&&!e.name.includes(`:`)&&vv(e.id)<=1;return t?n&&!!e.password:n}normaliseLegacyCredentialData(e,t){if(this.validateUserCredentialData(e,!0))return[e,!0];if(this.validateUserCredentialData(t))return[t,!1];if(e)try{let t=e,[n]=gv(t.name||t.id),[r,i]=gv(yv([t.id,t.name]));return[{id:bv(t.id||t.name,n,i),name:n,password:t.password||``},!0]}catch{xv(`PasswordCredential`)}if(t)try{let e=t,[n]=gv(e.name||e.username||e.organisation),[r,i]=gv(yv([e.organisation||e.username||e.name]));return[{id:bv(e.id||e.username||e.name,n,i),name:n,password:e.password||``},!1]}catch{xv(`cookie`)}return[void 0,!1]}storeCredentialsInContainer(e){return J(this,void 0,void 0,function*(){if(!hv())return;let t=new PasswordCredential(e);return Y.debug(`Storing credentials in CredentialsContainer`),navigator.credentials.store(t)})}getCredentialsFromContainer(){return J(this,arguments,void 0,function*(e=Sv){if(hv())return Y.debug(`Getting credentials from CredentialsContainer`),yield navigator.credentials.get(e)})}storeCredentialsInCookie(e){let{password:t}=e,n=gd(e,[`password`]),r=this.config.cookie.storePasswords?e:n;return Y.debug(`Storing credentials in cookie`),!!pv.set(this.config.cookie.name,JSON.stringify(r),{expires:this.config.cookie.expires,domain:location.hostname,path:this.config.cookie.path,secure:!0})}getCredentialsFromCookie(){Y.debug(`Getting credentials from cookie`);let e=pv.get(this.config.cookie.name);return e?JSON.parse(e):void 0}storeCredentials(e){return J(this,void 0,void 0,function*(){if(hv()){let t=yield this.storeCredentialsInContainer(e);return Promise.resolve(!!t)}return Promise.resolve(this.storeCredentialsInCookie(e))})}getCredentials(e){return J(this,void 0,void 0,function*(){return hv()?this.getCredentialsFromContainer(e):Promise.resolve(this.getCredentialsFromCookie())})}getSSOToken(){return this.session.getSessionStorageItem(`ssoToken`)}getUsername(){return this.session.getSessionStorageItem(`username`)||this.session.getLocalStorageItem(`username`)}getRefreshToken(){return this.session.getSessionStorageItem(`refreshToken`)||this.session.getLocalStorageItem(`refreshToken`)}getMFAToken(){return this.session.getSessionStorageItem(`mfaToken`)}removeCookie(){pv.remove(this.config.cookie.name,{domain:location.hostname,path:this.config.cookie.path})}removeSSOToken(){this.session.removeSessionStorageItem(`ssoToken`)}removeUsername(){this.session.removeSessionStorageItem(`username`),this.session.removeLocalStorageItem(`username`)}removeRefreshToken(){this.session.removeSessionStorageItem(`refreshToken`),this.session.removeLocalStorageItem(`refreshToken`)}removeMFAToken(){this.session.removeSessionStorageItem(`mfaToken`)}removeAll(){this.removeCookie(),this.removeSSOToken(),this.removeUsername(),this.removeRefreshToken(),this.removeMFAToken()}preventSilentAccess(){return hv()&&navigator.credentials.preventSilentAccess()}};wv=q([_d(0,Og),_d(1,Rt(mv))],wv);let Tv=N.createInterface(e=>e.singleton(wv)),Ev=e=>e?{date:e.DATE}:null,Dv=e=>e?e.map(e=>({name:e.NAME,version:e.VERSION})):[],Ov=e=>Array.isArray(e)?e.map(e=>e??``):[],kv=e=>{try{if(e?.MESSAGE_TYPE===`EVENT_LOGIN_AUTH_ACK`){let{DETAILS:t}=e;return{messageType:e.MESSAGE_TYPE,sourceRef:e.SOURCE_REF,userName:e.USER_NAME,updateQueue:e.UPDATE_QUEUE,zeroMqProxyModeEnabled:e.ZERO_MQ_PROXY_MODE_ENABLED,zeroMqProxyInboundPort:e.ZERO_MQ_PROXY_INBOUND_PORT,zeroMqProxyOutboundPort:e.ZERO_MQ_PROXY_OUTBOUND_PORT,userKVs:e.USER,details:t?{system:Ev(t.SYSTEM),heartbeatIntervalSecs:t.HEARTBEAT_INTERVAL_SECS,failedLoginAttempts:t.FAILED_LOGIN_ATTEMPTS,rejectedLoginAttempts:t.REJECTED_LOGIN_ATTEMPTS,lastLoginDatetime:t.LAST_LOGIN_DATETIME,daysToPasswordExpiry:t.DAYS_TO_PASSWORD_EXPIRY,product:Dv(t.PRODUCT)}:null,permission:Ov(e.PERMISSION),profile:Ov(e.PROFILE)}}throw Error(`No Entity mapping implementation for provided DTO`)}catch(e){throw Y.error(e),e}},Av=class{loggedUserResultChanged(){var e;(e=this.isLoggedInSubject)==null||e.next(this.isLoggedIn)}get isLoggedIn$(){return this.isLoggedInSubject.asObservable()}get isLoggedIn(){return this.currentUser.isAuthenticated}constructor(e,t,n,r,i){this.session=e,this.connect=t,this.messageBuilder=n,this.credentialManager=r,this.currentUser=i,this.isWorking=!1,this.isLoggedInSubject=new Ym(this.isLoggedIn),this.currentUser.addAuthenticationChangeListener(e=>{var t;(t=this.isLoggedInSubject)==null||t.next(e.detail)})}login(e){return J(this,void 0,void 0,function*(){this.isWorking=!0;try{let t=this.messageBuilder.createLoginMessage(e),n=yield this.connect.send(t);if(!n||n.ERROR||n.DETAILS?.ERROR)throw new Mg(t,n);this.applyAuthResults({authToken:n.SESSION_AUTH_TOKEN,refreshToken:n.REFRESH_AUTH_TOKEN,profiles:n.PROFILE,username:n.USER_NAME,permissions:n.PERMISSION,sessionId:n.SESSION_ID}),this.currentUser.set(kv(n)),this.session.setAuthResult(n),Y.debug(`Login Authentication Result:`,n)}catch(e){if(Y.error(`Login Authentication Error:`,e),e instanceof Mg&&e.isIgnorableError())Y.warn(`Ignoring authentication error as it is a known edge case.`);else throw this.removeAuthResults(),this.currentUser.unset(),e}finally{this.isWorking=!1}return this.loggedUserResult})}logout(){return J(this,void 0,void 0,function*(){this.isWorking=!0;let e={success:!1};try{let t=this.messageBuilder.createLogoutMessage(this.loggedUserResult);this.session.deleteUserFromSessionStorage();let{CODE:n,DETAILS:r,ERROR:i,MESSAGE_TYPE:a,OIDC_LOGOUT_URL:o}=yield this.connect.send(t),s=r?.ERROR??i,c=a===Ng.LOGOUT_NACK;c&&Y.warn(`Unexpected Logout NACK received during logout.`,s),e={success:a===Ng.LOGOUT_ACK||n===Fg.SESSION_NOT_FOUND||!c,error:s},o&&window.open(o,`_self`)}catch(t){let n=new Mg(t.sentMessage,t.receivedMessage);if(Y.error(`Logout Authentication Error:`,n),n.isIgnorableError())Y.warn(`Ignoring authentication error as it is a known edge case.`),e.success=!0;else throw t}finally{this.removeAuthResults(),this.currentUser.unset(),this.isWorking=!1}return e})}reAuthFromSession(){return J(this,void 0,void 0,function*(){let e=yield this.ensureConnection(),t=this.credentialManager.createRefreshCredentials();if(e&&this.credentialManager.validateRefreshCredentials(t)){let e=this.messageBuilder.createRefreshTokenMessage(),t=yield this.connect.send(e);if(t?.MESSAGE_TYPE===Pg.EVENT_LOGIN_AUTH_ACK)return this.session.setAuthResult(t),this.currentUser.set(kv(t)),this.applyAuthResults(this.getLoggedUserFromMessage(t)),!0}return this.session.deleteUserFromSessionStorage(),this.currentUser.unset(),!1})}ensureConnection(){return J(this,void 0,void 0,function*(){if(this.connect.isConnected)return!0;let e=this.session.getSessionStorageItem(`hostUrl`);return e?this.connect.connect(e):!1})}getLoggedUserFromMessage(e){let t=e.USER_NAME,n=e.SESSION_AUTH_TOKEN,r=e.REFRESH_AUTH_TOKEN;return!t||!n||!r?null:{username:t,authToken:n,refreshToken:r,profiles:e.PROFILE,permissions:e.PERMISSION,sessionId:e.SESSION_ID}}applyAuthResults(e){if(!e){this.removeAuthResults();return}this.loggedUserResult={authToken:e.authToken,refreshToken:e.refreshToken,profiles:e.profiles,username:e.username,permissions:e.permissions,sessionId:e.sessionId}}removeAuthResults(){this.loggedUserResult=null}};q([C],Av.prototype,`isWorking`,void 0),q([C],Av.prototype,`loggedUserResult`,void 0),Av=q([_d(0,Og),_d(1,sv),_d(2,Bg),_d(3,Tv),_d(4,gg)],Av);let jv=N.createInterface(e=>e.singleton(Av));function Mv(e,t){let n=new Date(e),r=n.getUTCFullYear(),i=String(n.getUTCMonth()+1).padStart(2,`0`),a=String(n.getUTCDate()).padStart(2,`0`);return t?`${r}${i}${a}`:`${r}${i}${a}-${String(n.getUTCHours()).padStart(2,`0`)}:${String(n.getUTCMinutes()).padStart(2,`0`)}`}function Nv(e,t){let n=e.match(/Expr\.(\w+)\(/);if(n)switch(n[1]){case`dateIsToday`:{let n=e.match(/Expr\.dateIsToday\((\w+)\)/);if(n){let[,e]=n,r=/* @__PURE__ */ new Date;t[`${e}_FROM`]=`${r.toISOString().replace(/-/g,``).split(`T`)[0]}-00:00`,r.setDate(r.getDate()+1),t[`${e}_TO`]=`${r.toISOString().replace(/-/g,``).split(`T`)[0]}-00:00`}break}case`dateTimeIsGreaterEqual`:{let n=e.match(/Expr\.dateTimeIsGreaterEqual\((\w+), ?['"](.+)['"]\)/);if(n){let[,e,r]=n;t[`${e}_FROM`]=r}break}case`dateTimeIsLessEqual`:{let n=e.match(/Expr\.dateTimeIsLessEqual\((\w+), ?['"](.+)['"]\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=r}break}case`dateIsGreaterEqual`:{let n=e.match(/Expr\.dateIsGreaterEqual\((\w+), ?['"](.+)['"]\)/);if(n){let[,e,r]=n;t[`${e}_FROM`]=r}break}case`dateIsLessEqual`:{let n=e.match(/Expr\.dateIsLessEqual\((\w+), ?['"](.+)['"]\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=r}break}case`containsIgnoreCase`:{let n=e.match(/Expr\.containsIgnoreCase\((\w+), ?['"](.+)['"]\)/);if(n){let[,e,r]=n;t[e]=`*${r}*`}break}}}function Pv(e,t){let n=e.substr(0,e.indexOf(`=`)).trim().replace(/["']/g,``);t[n]=e.substr(e.lastIndexOf(`=`)+1,e.length).trim().replace(/["']/g,``)}function Fv(e){if(!e)return{};let t=e.split(`&&`).map(e=>e.trim()),n={};return t.forEach(e=>{if(e){if(e.startsWith(`Expr`))Nv(e,n);else if(/[A-Z_]+\s*(>=|<=)\s*\d+/.test(e)){let t=e.match(/([A-Z_]+)\s*>=\s*(\d+)/);if(t){let[,e,r]=t,i=parseInt(r,10),a=e.toUpperCase(),o=a.includes(`DATE`)&&!a.includes(`DATETIME`);n[`${e}_FROM`]=Mv(i,o)}let r=e.match(/([A-Z_]+)\s*<=\s*(\d+)/);if(r){let[,e,t]=r,i=parseInt(t,10),a=e.toUpperCase(),o=a.includes(`DATE`)&&!a.includes(`DATETIME`);n[`${e}_TO`]=Mv(i,o)}}else Pv(e,n)}}),n}function Iv(e,t=`ROW_REF`){let n=e=>{let n=e.DETAILS[t]??e[t],r=Object.assign(Object.assign({},e),{[t]:n});return delete r.DETAILS,r},r=[],i=[],a=[];for(let t of e.ROW)if(t.DETAILS)switch(t.DETAILS.OPERATION){case`INSERT`:r.push(n(t));break;case`MODIFY`:a.push(n(t));break;case`DELETE`:i.push(n(t));break;default:Y.error(`Unsupported operation type: '${t.DETAILS.OPERATION}'`)}return{inserts:r,deletes:i,updates:a,SOURCE_REF:e.SOURCE_REF}}var Lv=class{};Lv.MAX_ROWS_250=250,Lv.MAX_VIEW_1000=1e3,Lv.REQ_REP_POLLING_INTERVAL_MS=1e4,Lv.DATASERVER_ROW_ID=`ROW_REF`,Lv.REQUEST_SERVER_ROW_ID=`RECORD_ID`,Lv.DEFAULT_PAGINATION_PAGE_SIZE=25,Lv.DEFAULT_REQ_REP_OFFSET=0;let Rv={options:{criteria:``,isSnapshot:!1,maxRows:Lv.MAX_ROWS_250,maxView:Lv.MAX_VIEW_1000,pollingInterval:Lv.REQ_REP_POLLING_INTERVAL_MS,movingView:!1,orderBy:``,resourceName:``,reverse:!1,pollTriggerEvents:[]},criteriaToFields:Fv,dataServerResultFilter:Iv},zv=N.createInterface(e=>e.instance(Rv));function Bv(e){let t=e==null?NaN:Number(e);return Number.isFinite(t)?t===0?1/0:t:Lv.MAX_VIEW_1000}function Vv(e){return e.moreRows===!1?`end`:e.rowsHeld>=Bv(e.maxView)?e.movingView?`more`:`view-full`:e.emptyReply?`stalled`:`more`}function Hv(e){let t=Bv(e.maxView),n=Uv(e.maxView)?`${t}, the server default`:`${t}`,r=e.totalRows;if(e.status===`stalled`)return`${e.resourceName} stopped at ${e.rowsHeld} rows: the server answered MORE_ROWS with an empty page while still reporting more rows, with room left in the view (MAX_VIEW ${n}). This is not the MAX_VIEW cap; check the data server log for "Problem building client message".`;if(!e.emptyReply&&r!==void 0&&r<=e.rowsHeld)return;let i=r!==void 0&&r>e.rowsHeld,a=i?` of ${r}`:``,o=e.emptyReply||i?` and the server holds more rows past it`:`, so any rows past it are not loaded`;return`${e.resourceName} stopped at ${e.rowsHeld}${a} rows: the DATASERVER view is full at MAX_VIEW (${n})${o}. Raise ${e.attribute} past the row count to reach the rest.`}function Uv(e){return e==null||!Number.isFinite(Number(e))}let Wv=e=>{class t extends e{constructor(){super(),this.hasOwnProperty(`onDatasourceStatusChanged`)||(this.onDatasourceStatusChanged=e=>{let t=this.data!==void 0;!this.resourceName&&!t&&Y.warn(`Target classes must have a resourceName or data property to use the DatasourceEventHandler mixin.`);let n=e.detail;if(n.name===this.resourceName){let e=this.datasourceStatus??{isInitialized:!1,hasMetadata:!1};(e.isInitialized!==n.isInitialized||n.metadataRequired&&e.hasMetadata!==n.hasMetadata)&&(this.datasourceStatus=n)}})}datasourceStatusChanged(e,t){Y.debug(`Target classes should override the datasourceStatusChanged method of the DatasourceEventHandler mixin to respond to changes in the target datasource.`)}connectedCallback(){super.connectedCallback(),document.addEventListener(bg,this.onDatasourceStatusChanged,{passive:!0,capture:!0})}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(bg,this.onDatasourceStatusChanged,{capture:!0})}}return q([C],t.prototype,`datasourceStatus`,void 0),t},Gv={throwWhenUnavailable:!0,throwWhenUnknown:!1},Kv=N.createInterface(e=>e.instance(Gv)),qv=Xd(`genesis-resources`);function Jv(){return N.getOrCreateDOMContainer().get(qv)}let Yv=class{constructor(e,t){this.connect=e,this.config=t}isValidResource(e){return J(this,void 0,void 0,function*(){return e=e?.trim(),e?(yield this.fetchResources(),!!this.resources.find(t=>t.RESOURCE_NAME===e)):!1})}getResourceTypeFor(e){return J(this,void 0,void 0,function*(){yield this.fetchResources();let t=this.resources.find(t=>t.RESOURCE_NAME===e);if(t)return t.RESOURCE_TYPE;let n=`${e} resource does not exist.`;if(Y.error(n),this.config.throwWhenUnknown)throw Error(n)})}getAllResources(){return J(this,void 0,void 0,function*(){return this.resources||(yield this.fetchResources()),this.resources})}destroy(){this.resources=void 0,this.resourcesPromise=void 0}fetchResources(){return J(this,void 0,void 0,function*(){if(this.resources)return Promise.resolve();if(this.resourcesPromise)yield this.resourcesPromise;else{this.resourcesPromise=this.connect.getAvailableResources();let e=yield this.resourcesPromise;if(this.resources=e?.RESOURCES,!this.resources?.length){let e=`Genesis resources unavailable.`;if(Y.error(e),this.config.throwWhenUnavailable)throw Error(e)}this.postLoadedMessage(),this.resourcesPromise=void 0}})}postLoadedMessage(){let e=Jv();e.postMessage(`resources-loaded`,this.resources),e.close()}};Yv=q([_d(0,sv),_d(1,Kv)],Yv);let Xv=N.createInterface(e=>e.singleton(Yv)),Zv=class{get initialized(){return!!this.status?.isInitialized}constructor(e,t,n,r,i){this.connect=e,this.auth=t,this.resources=n,this.config=r,this.connectEvents=i,this.fetchMetadataRequired=!0,this.startStreamRequired=!0,this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.customRequestFields=[],this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.criteriaOnlyRequest=!1,this.loadMoreCount=0,this.readOnly=!0,this._allParams=null,this.pollTrigger$=new qm}triggerPoll(){this.pollTrigger$.next()}validResourceName(e){return Y.deprecated(`Datasource.validResourceName`,"Use `GenesisResources.isValidResource` instead."),!(!e||!e.trim().length)}init(e){return J(this,arguments,void 0,function*(e,t=this.fetchMetadataRequired,n=this.startStreamRequired){this.fetchMetadataRequired=t,this.options=Object.assign(Object.assign({},this.config.options),e),this.invalidateCache();let r=this.options.resourceName;return this.connect.isConnected||(yield this.connect.connect())?(yield this.resources.isValidResource(r))?(this.resourceType=yield this.resources.getResourceTypeFor(r),this.resourceType?(this.fetchMetadataRequired&&(yield this.fetchAndApplyMetadata(this.options.resourceName),this._allParams=null),Y.debug(`Initializing ${r} datasource from ${this.connect.host}`),!this.options.isSnapshot&&n&&(this.pollTrigger$=new qm,this.stream=yield this.createStream()),Y.debug(`${r} datasource initialization ${this.initialized?`was successful.`:`has failed.`}`),this.reportStatus(),this.initialized):(Y.error(`Unable to get the resource type for ${r} datasource from ${this.connect.host}`),this.reportStatus(),!1)):(Y.error(`${r} datasource does not exist on ${this.connect.host}`),this.reportStatus(),!1):(Y.error(`Unable to connect to ${this.connect.host} to get ${r} datasource`),this.reportStatus(),!1)})}startStream(){return J(this,void 0,void 0,function*(){!this.options.isSnapshot&&this.stream===void 0&&(this.stream=yield this.createStream())})}destroy(){var e;Y.debug(`Datasource.destroy`,this.options?.resourceName),this.commitResponseUnsubscribe&&(this.commitResponseUnsubscribe(),this.commitResponseUnsubscribe=void 0),(e=this.pollTrigger$)==null||e.complete(),this.status=void 0,this.fetchMetadataRequired=!0,this.options={},this.resourceType=void 0,this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.criteriaOnlyRequest=!1,this.loadMoreCount=0,this.stream=void 0}get allResourceParams(){if(this._allParams)return this._allParams;let e;if(this.options.orderBy){if(this.criteriaOnlyRequest||this.availableIndexes?.findIndex(e=>e.NAME===this.options.orderBy)>-1)e=this.options.orderBy;else{let e=this.availableIndexes.map(e=>e.NAME);Y.warn(`Specified [orderBy] index is not valid and will not be used. See https://learn.genesis.global/docs/database/data-types/index-entities/ - Available indexes:`,e)}}return this._allParams={CRITERIA_MATCH:this.options.criteria,MAX_ROWS:this.options.maxRows,ORDER_BY:e,VIEW_NUMBER:this.options.viewNumber,FIELDS:this.options.fields,MAX_VIEW:this.options.maxView,MOVING_VIEW:this.options.movingView,REVERSE:this.options.reverse,DISABLE_POLLING:this.options.disablePolling,OFFSET:this.options.offset,POLLING_INTERVAL:this.options.pollingInterval,REQUEST:this.options.request},Y.debug(`Getting configured params:`,this._allParams),this._allParams}get dataserverOnlyParams(){return{CRITERIA_MATCH:this.allResourceParams.CRITERIA_MATCH,MAX_ROWS:this.allResourceParams.MAX_ROWS,VIEW_NUMBER:this.allResourceParams.VIEW_NUMBER,FIELDS:this.allResourceParams.FIELDS,MAX_VIEW:this.allResourceParams.MAX_VIEW,MOVING_VIEW:this.allResourceParams.MOVING_VIEW,ORDER_BY:this.allResourceParams.ORDER_BY,REVERSE:this.allResourceParams.REVERSE}}get requestOnlyParams(){let e=this.allResourceParams,{REQUEST:t}=e,n=gd(e,[`REQUEST`]);return{DETAILS:{CRITERIA_MATCH:this.options.requestAutoSetup?void 0:n.CRITERIA_MATCH,MAX_ROWS:n.MAX_ROWS,OFFSET:n.OFFSET,ORDER_BY:n.ORDER_BY,VIEW_NUMBER:n.VIEW_NUMBER},REQUEST:this.criteriaOnlyRequest?{}:t??this.buildRequestFields()}}buildRequestFields(){if(!this.options.requestAutoSetup)return{};let e=Object.fromEntries(this.requestFields.map(e=>[e.NAME,`*`])),t=this.options.criteria?this.config.criteriaToFields(this.options.criteria):{};return Object.assign(Object.assign({},e),t)}updateLoadMoreCount(e){this.loadMoreCount=e}snapshot(e){return J(this,void 0,void 0,function*(){switch(Y.debug(`Requesting snapshot for ${this.options.resourceName} (${this.resourceType}).`),this.resourceType){case yg.DATASERVER:return this.connect.snapshot(this.options.resourceName,Object.assign(Object.assign({},this.dataserverOnlyParams),e));case yg.REQUEST_SERVER:return this.connect.request(this.options.resourceName,Object.assign(Object.assign({},this.requestOnlyParams),e));default:throw Error(`Snapshot not supported for selected resource type: ${this.resourceType}`)}})}snapshotFiltered(){return J(this,arguments,void 0,function*(e=`ROW_REF`){let t=yield this.snapshot();if(Array.isArray(t))return t;if(t.REPLY)return t.REPLY;if(t.ROW)return this.config.dataServerResultFilter(t,e).inserts})}createStream(){return J(this,void 0,void 0,function*(){if(![yg.DATASERVER,yg.REQUEST_SERVER].includes(this.resourceType))throw Error(`Streaming not supported for selected resource type: ${this.resourceType}`);return this.resourceType===yg.DATASERVER?this.createDataserverStream():(Y.debug(`Creating fake stream by polling ${this.options.resourceName} REQUEST_SERVER`),this.createReqRepStream())})}createDataserverStream(){return J(this,void 0,void 0,function*(){return this.connect.stream(this.options.resourceName,e=>{},e=>Y.error(e),this.dataserverOnlyParams)})}createReqRepStream(){this.commitResponseUnsubscribe=this.connectEvents.addCommitResponseListener(e=>{let{eventName:t,response:n}=e.detail;this.options.pollTriggerEvents&&this.options.pollTriggerEvents.includes(t)&&n.MESSAGE_TYPE?.endsWith(`_ACK`)&&(Y.debug(`Received commit response for ${t}, triggering poll.`),this.triggerPoll())});let e=this.allResourceParams.DISABLE_POLLING?void 0:this.allResourceParams.POLLING_INTERVAL,t=()=>{let e=this.requestOnlyParams;if(this.resourceType===yg.REQUEST_SERVER&&this.loadMoreCount>0){let t=(this.options.maxRows||25)*(this.loadMoreCount+1);e.DETAILS.MAX_ROWS=t}return Hre([this.connect.isConnected$,this.auth.isLoggedIn$]).pipe(zh(()=>this.connect.isConnected&&this.auth.isLoggedIn),Rh(()=>Eh(this.snapshot(e))))};return e?this.pollTrigger$.pipe(Lh(0),Rh(()=>Ph(0,e).pipe(Rh(t)))):this.pollTrigger$.pipe(Lh(0),Rh(t))}fetchAndApplyMetadata(e){return J(this,void 0,void 0,function*(){try{Y.debug(`Requesting metadata for ${this.options.resourceName} Datasource`);let e=yield this.connect.getMetadata(this.options.resourceName);e&&(this.availableIndexes=e.INDEXES??[],this.availableSortableFields=e.SORTABLE_FIELDS??[],this.availableCriteriaFields=e.CRITERIA_FIELDS??[],this.originalFieldDef=Sg(e),this.fieldMetadata=xg(this.originalFieldDef),this.requestFields=e.REQUEST_FIELD||[],this.customRequestFields=e.FIELD||[],this.criteriaOnlyRequest=e.CRITERIA_ONLY_REQUEST||!1,this.fetchMetadataRequired=!1),this.status=this.normaliseStatus({isInitialized:!0,metadataRequired:!0,hasMetadata:this.fieldMetadata?.length>0})}catch(t){Y.error(`Metadata Fetch failed for ${e}:`,t),this.status=this.normaliseStatus({isInitialized:!1,metadataRequired:!0,hasMetadata:!1})}})}reportStatus(e={}){let t=this.config.eventEmitter??document;this.status=this.normaliseStatus(e),Y.debug(`Dispatching '${bg}'`,this.status),t?.dispatchEvent(new CustomEvent(`datasource-status-changed`,{detail:this.status,bubbles:t!==document,composed:!0}))}normaliseStatus(e){let t=e.isInitialized??this.initialized,n=e.metadataRequired??this.fetchMetadataRequired,r=e.hasMetadata??this.fieldMetadata?.length>0;return{name:this.options?.resourceName,type:this.resourceType,isInitialized:t,metadataRequired:n,hasMetadata:r}}invalidateCache(){this._allParams=null}};q([C],Zv.prototype,`status`,void 0),q([C],Zv.prototype,`fetchMetadataRequired`,void 0),q([C],Zv.prototype,`startStreamRequired`,void 0),q([C],Zv.prototype,`originalFieldDef`,void 0),q([C],Zv.prototype,`fieldMetadata`,void 0),q([C],Zv.prototype,`requestFields`,void 0),q([C],Zv.prototype,`customRequestFields`,void 0),q([C],Zv.prototype,`availableIndexes`,void 0),q([C],Zv.prototype,`availableSortableFields`,void 0),q([C],Zv.prototype,`availableCriteriaFields`,void 0),q([C],Zv.prototype,`criteriaOnlyRequest`,void 0),q([C],Zv.prototype,`loadMoreCount`,void 0),q([C],Zv.prototype,`readOnly`,void 0),q([C],Zv.prototype,`stream`,void 0),Zv=q([_d(0,sv),_d(1,jv),_d(2,Xv),_d(3,zv),_d(4,Cg)],Zv);let Qv=N.createInterface(e=>e.transient(Zv));var $v=class extends Zv{constructor(){super(...arguments),this.entityCache=[],this.entityMap=/* @__PURE__ */ new Map,this.rowId=`ROW_REF`,this.initialize=e=>J(this,void 0,void 0,function*(){return this.disconnect(),this.options=Object.assign({},e.options),this.mapper=e.mapper,this.initialized=yield this.init(this.options,e.fetchMeta),this.initialized?(this.subscription=this.stream.subscribe(e=>{this.sourceRef=e.SOURCE_REF,this.subscriptionLoggedOff=e.MESSAGE_TYPE===Ng.LOGOFF_ACK;let t=e.ROW;!this.subscriptionLoggedOff&&t&&this.updateCache(this.config.dataServerResultFilter(e,this.rowId))}),!0):(Y.debug(`EntityDatasource init failed for ${this.options.resourceName}`),!1)}),this.disconnect=()=>{var e;(e=this.subscription)==null||e.unsubscribe(),this.entityCache=[]}}get initialized(){return this._initialized}set initialized(e){this._initialized=e}get cache(){if(!this.initialized)throw Error(`Please initialize EntityDatasource before querying.`);return this.entityCache}get isEmpty(){return this.entityCache.length===0}updateCache(e){var t;this.isEmpty,(t=e.deletes)==null||t.forEach(e=>{let t=e[this.rowId];this.entityMap.delete(t)}),this.processRowDataUpdate(e.inserts,!0),this.processRowDataUpdate(e.updates);let n=[{}];this.entityCache=n.map(e=>this.mapper.fromDTO(e))}processRowDataUpdate(e,t=!1){e.forEach(e=>{let n=e[this.rowId],r=this.entityMap.get(n);if(r&&t)throw Error(`Existing entity found in map while inserting.`);let i=this.mapper.fromDTO(e),a=r?Object.assign(Object.assign({},r),i):i;this.entityMap.set(n,a)})}};N.createInterface(e=>e.transient($v));function ey(e,t=`;`){return e&&e.split(t).map(e=>e.trim()).sort((e,t)=>e.localeCompare(t)).join(t)}let ty=`system-health-changed`,ny={windowEvents:[`online`,`offline`,`pageshow`],documentEvents:[`visibilitychange`],genesisConnectEvents:[`stream`,`commit`],ignoredGenesisResources:[],startDelay:5e3,checkInterval:1e4,checkTimeout:3e3,resourceChecks:e=>J(void 0,void 0,void 0,function*(){let t=yield cv().getMoreColumns(e),n=Date.now(),r=t;return{isConnected:t.MESSAGE_TYPE===Ng.MORE_COLUMNS_ACK,lastUpdated:n,lastMessage:r}}),resourceDataLogon:({message:e,functions:t})=>{let{onMessage:n,onError:r}=t;rv().sendForStream(e,n,r)}},ry=N.createInterface(e=>e.instance(ny));var iy=/* @__PURE__ */ s(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.bowser=r():n.bowser=r()})(e,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=90)}({17:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r=n(18);t.default=function(){function e(){}return e.getFirstMatch=function(e,t){var n=t.match(e);return n&&n.length>0&&n[1]||``},e.getSecondMatch=function(e,t){var n=t.match(e);return n&&n.length>1&&n[2]||``},e.matchAndReturnConst=function(e,t,n){if(e.test(t))return n},e.getWindowsVersionName=function(e){switch(e){case`NT`:return`NT`;case`XP`:return`XP`;case`NT 5.0`:return`2000`;case`NT 5.1`:return`XP`;case`NT 5.2`:return`2003`;case`NT 6.0`:return`Vista`;case`NT 6.1`:return`7`;case`NT 6.2`:return`8`;case`NT 6.3`:return`8.1`;case`NT 10.0`:return`10`;default:return}},e.getMacOSVersionName=function(e){var t=e.split(`.`).splice(0,2).map((function(e){return parseInt(e,10)||0}));t.push(0);var n=t[0],r=t[1];if(n===10)switch(r){case 5:return`Leopard`;case 6:return`Snow Leopard`;case 7:return`Lion`;case 8:return`Mountain Lion`;case 9:return`Mavericks`;case 10:return`Yosemite`;case 11:return`El Capitan`;case 12:return`Sierra`;case 13:return`High Sierra`;case 14:return`Mojave`;case 15:return`Catalina`;default:return}switch(n){case 11:return`Big Sur`;case 12:return`Monterey`;case 13:return`Ventura`;case 14:return`Sonoma`;case 15:return`Sequoia`;default:return}},e.getAndroidVersionName=function(e){var t=e.split(`.`).splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(t[0]===1&&t[1]<5))return t[0]===1&&t[1]<6?`Cupcake`:t[0]===1&&t[1]>=6?`Donut`:t[0]===2&&t[1]<2?`Eclair`:t[0]===2&&t[1]===2?`Froyo`:t[0]===2&&t[1]>2?`Gingerbread`:t[0]===3?`Honeycomb`:t[0]===4&&t[1]<1?`Ice Cream Sandwich`:t[0]===4&&t[1]<4?`Jelly Bean`:t[0]===4&&t[1]>=4?`KitKat`:t[0]===5?`Lollipop`:t[0]===6?`Marshmallow`:t[0]===7?`Nougat`:t[0]===8?`Oreo`:t[0]===9?`Pie`:void 0},e.getVersionPrecision=function(e){return e.split(`.`).length},e.compareVersions=function(t,n,r){r===void 0&&(r=!1);var i=e.getVersionPrecision(t),a=e.getVersionPrecision(n),o=Math.max(i,a),s=0,c=e.map([t,n],(function(t){var n=o-e.getVersionPrecision(t),r=t+Array(n+1).join(`.0`);return e.map(r.split(`.`),(function(e){return Array(20-e.length).join(`0`)+e})).reverse()}));for(r&&(s=o-Math.min(i,a)),--o;o>=s;){if(c[0][o]>c[1][o])return 1;if(c[0][o]===c[1][o]){if(o===s)return 0;--o}else if(c[0][o]<c[1][o])return-1}},e.map=function(e,t){var n,r=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(n=0;n<e.length;n+=1)r.push(t(e[n]));return r},e.find=function(e,t){var n,r;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(n=0,r=e.length;n<r;n+=1){var i=e[n];if(t(i,n))return i}},e.assign=function(e){for(var t,n,r=e,i=arguments.length,a=Array(i>1?i-1:0),o=1;o<i;o++)a[o-1]=arguments[o];if(Object.assign)return Object.assign.apply(Object,[e].concat(a));var s=function(){var e=a[t];typeof e==`object`&&e&&Object.keys(e).forEach((function(t){r[t]=e[t]}))};for(t=0,n=a.length;t<n;t+=1)s();return e},e.getBrowserAlias=function(e){return r.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return r.BROWSER_MAP[e]||``},e}(),e.exports=t.default},18:function(e,t,n){"use strict";t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={AmazonBot:`amazonbot`,"Amazon Silk":`amazon_silk`,"Android Browser":`android`,BaiduSpider:`baiduspider`,Bada:`bada`,BingCrawler:`bingcrawler`,Brave:`brave`,BlackBerry:`blackberry`,"ChatGPT-User":`chatgpt_user`,Chrome:`chrome`,ClaudeBot:`claudebot`,Chromium:`chromium`,Diffbot:`diffbot`,DuckDuckBot:`duckduckbot`,DuckDuckGo:`duckduckgo`,Electron:`electron`,Epiphany:`epiphany`,FacebookExternalHit:`facebookexternalhit`,Firefox:`firefox`,Focus:`focus`,Generic:`generic`,"Google Search":`google_search`,Googlebot:`googlebot`,GPTBot:`gptbot`,"Internet Explorer":`ie`,InternetArchiveCrawler:`internetarchivecrawler`,"K-Meleon":`k_meleon`,LibreWolf:`librewolf`,Linespider:`linespider`,Maxthon:`maxthon`,"Meta-ExternalAds":`meta_externalads`,"Meta-ExternalAgent":`meta_externalagent`,"Meta-ExternalFetcher":`meta_externalfetcher`,"Meta-WebIndexer":`meta_webindexer`,"Microsoft Edge":`edge`,"MZ Browser":`mz`,"NAVER Whale Browser":`naver`,"OAI-SearchBot":`oai_searchbot`,Omgilibot:`omgilibot`,Opera:`opera`,"Opera Coast":`opera_coast`,"Pale Moon":`pale_moon`,PerplexityBot:`perplexitybot`,"Perplexity-User":`perplexity_user`,PhantomJS:`phantomjs`,PingdomBot:`pingdombot`,Puffin:`puffin`,QQ:`qq`,QQLite:`qqlite`,QupZilla:`qupzilla`,Roku:`roku`,Safari:`safari`,Sailfish:`sailfish`,"Samsung Internet for Android":`samsung_internet`,SlackBot:`slackbot`,SeaMonkey:`seamonkey`,Sleipnir:`sleipnir`,"Sogou Browser":`sogou`,Swing:`swing`,Tizen:`tizen`,"UC Browser":`uc`,Vivaldi:`vivaldi`,"WebOS Browser":`webos`,WeChat:`wechat`,YahooSlurp:`yahooslurp`,"Yandex Browser":`yandex`,YandexBot:`yandexbot`,YouBot:`youbot`},t.BROWSER_MAP={amazonbot:`AmazonBot`,amazon_silk:`Amazon Silk`,android:`Android Browser`,baiduspider:`BaiduSpider`,bada:`Bada`,bingcrawler:`BingCrawler`,blackberry:`BlackBerry`,brave:`Brave`,chatgpt_user:`ChatGPT-User`,chrome:`Chrome`,claudebot:`ClaudeBot`,chromium:`Chromium`,diffbot:`Diffbot`,duckduckbot:`DuckDuckBot`,duckduckgo:`DuckDuckGo`,edge:`Microsoft Edge`,electron:`Electron`,epiphany:`Epiphany`,facebookexternalhit:`FacebookExternalHit`,firefox:`Firefox`,focus:`Focus`,generic:`Generic`,google_search:`Google Search`,googlebot:`Googlebot`,gptbot:`GPTBot`,ie:`Internet Explorer`,internetarchivecrawler:`InternetArchiveCrawler`,k_meleon:`K-Meleon`,librewolf:`LibreWolf`,linespider:`Linespider`,maxthon:`Maxthon`,meta_externalads:`Meta-ExternalAds`,meta_externalagent:`Meta-ExternalAgent`,meta_externalfetcher:`Meta-ExternalFetcher`,meta_webindexer:`Meta-WebIndexer`,mz:`MZ Browser`,naver:`NAVER Whale Browser`,oai_searchbot:`OAI-SearchBot`,omgilibot:`Omgilibot`,opera:`Opera`,opera_coast:`Opera Coast`,pale_moon:`Pale Moon`,perplexitybot:`PerplexityBot`,perplexity_user:`Perplexity-User`,phantomjs:`PhantomJS`,pingdombot:`PingdomBot`,puffin:`Puffin`,qq:`QQ Browser`,qqlite:`QQ Browser Lite`,qupzilla:`QupZilla`,roku:`Roku`,safari:`Safari`,sailfish:`Sailfish`,samsung_internet:`Samsung Internet for Android`,seamonkey:`SeaMonkey`,slackbot:`SlackBot`,sleipnir:`Sleipnir`,sogou:`Sogou Browser`,swing:`Swing`,tizen:`Tizen`,uc:`UC Browser`,vivaldi:`Vivaldi`,webos:`WebOS Browser`,wechat:`WeChat`,yahooslurp:`YahooSlurp`,yandex:`Yandex Browser`,yandexbot:`YandexBot`,youbot:`YouBot`},t.PLATFORMS_MAP={bot:`bot`,desktop:`desktop`,mobile:`mobile`,tablet:`tablet`,tv:`tv`},t.OS_MAP={Android:`Android`,Bada:`Bada`,BlackBerry:`BlackBerry`,ChromeOS:`Chrome OS`,HarmonyOS:`HarmonyOS`,iOS:`iOS`,Linux:`Linux`,MacOS:`macOS`,PlayStation4:`PlayStation 4`,Roku:`Roku`,Tizen:`Tizen`,WebOS:`WebOS`,Windows:`Windows`,WindowsPhone:`Windows Phone`},t.ENGINE_MAP={Blink:`Blink`,EdgeHTML:`EdgeHTML`,Gecko:`Gecko`,Presto:`Presto`,Trident:`Trident`,WebKit:`WebKit`}},90:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r,i=(r=n(91))&&r.__esModule?r:{default:r},a=n(18);function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}t.default=function(){function e(){}var t,n,r;return e.getParser=function(e,t,n){if(t===void 0&&(t=!1),n===void 0&&(n=null),typeof e!=`string`)throw Error(`UserAgent should be a string`);return new i.default(e,t,n)},e.parse=function(e,t){return t===void 0&&(t=null),new i.default(e,t).getResult()},t=e,r=[{key:`BROWSER_MAP`,get:function(){return a.BROWSER_MAP}},{key:`ENGINE_MAP`,get:function(){return a.ENGINE_MAP}},{key:`OS_MAP`,get:function(){return a.OS_MAP}},{key:`PLATFORMS_MAP`,get:function(){return a.PLATFORMS_MAP}}],(n=null)&&o(t.prototype,n),r&&o(t,r),e}(),e.exports=t.default},91:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r=c(n(92)),i=c(n(93)),a=c(n(94)),o=c(n(95)),s=c(n(17));function c(e){return e&&e.__esModule?e:{default:e}}t.default=function(){function e(e,t,n){if(t===void 0&&(t=!1),n===void 0&&(n=null),e==null||e===``)throw Error(`UserAgent parameter can't be empty`);this._ua=e;var r=!1;typeof t==`boolean`?(r=t,this._hints=n):this._hints=typeof t==`object`&&t?t:null,this.parsedResult={},!0!==r&&this.parse()}var t=e.prototype;return t.getHints=function(){return this._hints},t.hasBrand=function(e){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var t=e.toLowerCase();return this._hints.brands.some((function(e){return e.brand&&e.brand.toLowerCase()===t}))},t.getBrandVersion=function(e){if(this._hints&&Array.isArray(this._hints.brands)){var t=e.toLowerCase(),n=this._hints.brands.find((function(e){return e.brand&&e.brand.toLowerCase()===t}));return n?n.version:void 0}},t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=s.default.find(r.default,(function(t){if(typeof t.test==`function`)return t.test(e);if(Array.isArray(t.test))return t.test.some((function(t){return e.test(t)}));throw Error(`Browser's test function is not valid`)}));return t&&(this.parsedResult.browser=t.describe(this.getUA(),this)),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||``:this.getBrowser().name||``},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=s.default.find(i.default,(function(t){if(typeof t.test==`function`)return t.test(e);if(Array.isArray(t.test))return t.test.some((function(t){return e.test(t)}));throw Error(`Browser's test function is not valid`)}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||``:t||``},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){e===void 0&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||``:t||``},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=s.default.find(a.default,(function(t){if(typeof t.test==`function`)return t.test(e);if(Array.isArray(t.test))return t.test.some((function(t){return e.test(t)}));throw Error(`Browser's test function is not valid`)}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||``:this.getEngine().name||``},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=s.default.find(o.default,(function(t){if(typeof t.test==`function`)return t.test(e);if(Array.isArray(t.test))return t.test.some((function(t){return e.test(t)}));throw Error(`Browser's test function is not valid`)}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return s.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,n={},r=0,i={},a=0;if(Object.keys(e).forEach((function(t){var o=e[t];typeof o==`string`?(i[t]=o,a+=1):typeof o==`object`&&(n[t]=o,r+=1)})),r>0){var o=Object.keys(n),c=s.default.find(o,(function(e){return t.isOS(e)}));if(c){var l=this.satisfies(n[c]);if(l!==void 0)return l}var u=s.default.find(o,(function(e){return t.isPlatform(e)}));if(u){var d=this.satisfies(n[u]);if(d!==void 0)return d}}if(a>0){var f=Object.keys(i),p=s.default.find(f,(function(e){return t.isBrowser(e,!0)}));if(p!==void 0)return this.compareVersion(i[p])}},t.isBrowser=function(e,t){t===void 0&&(t=!1);var n=this.getBrowserName().toLowerCase(),r=e.toLowerCase(),i=s.default.getBrowserTypeByAlias(r);return t&&i&&(r=i.toLowerCase()),r===n},t.compareVersion=function(e){var t=[0],n=e,r=!1,i=this.getBrowserVersion();if(typeof i==`string`)return e[0]===`>`||e[0]===`<`?(n=e.substr(1),e[1]===`=`?(r=!0,n=e.substr(2)):t=[],e[0]===`>`?t.push(1):t.push(-1)):e[0]===`=`?n=e.substr(1):e[0]===`~`&&(r=!0,n=e.substr(1)),t.indexOf(s.default.compareVersions(i,n,r))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return t===void 0&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return e===void 0&&(e=[]),e.some((function(e){return t.is(e)}))},e}(),e.exports=t.default},92:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},a=/version\/(\d+(\.?_?\d+)+)/i;t.default=[{test:[/gptbot/i],describe:function(e){var t={name:`GPTBot`},n=i.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/chatgpt-user/i],describe:function(e){var t={name:`ChatGPT-User`},n=i.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/oai-searchbot/i],describe:function(e){var t={name:`OAI-SearchBot`},n=i.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(e){var t={name:`ClaudeBot`},n=i.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(e){var t={name:`Omgilibot`},n=i.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/diffbot/i],describe:function(e){var t={name:`Diffbot`},n=i.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/perplexitybot/i],describe:function(e){var t={name:`PerplexityBot`},n=i.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/perplexity-user/i],describe:function(e){var t={name:`Perplexity-User`},n=i.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/youbot/i],describe:function(e){var t={name:`YouBot`},n=i.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/meta-webindexer/i],describe:function(e){var t={name:`Meta-WebIndexer`},n=i.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/meta-externalads/i],describe:function(e){var t={name:`Meta-ExternalAds`},n=i.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/meta-externalagent/i],describe:function(e){var t={name:`Meta-ExternalAgent`},n=i.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/meta-externalfetcher/i],describe:function(e){var t={name:`Meta-ExternalFetcher`},n=i.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/googlebot/i],describe:function(e){var t={name:`Googlebot`},n=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/linespider/i],describe:function(e){var t={name:`Linespider`},n=i.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/amazonbot/i],describe:function(e){var t={name:`AmazonBot`},n=i.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/bingbot/i],describe:function(e){var t={name:`BingCrawler`},n=i.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/baiduspider/i],describe:function(e){var t={name:`BaiduSpider`},n=i.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/duckduckbot/i],describe:function(e){var t={name:`DuckDuckBot`},n=i.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/ia_archiver/i],describe:function(e){var t={name:`InternetArchiveCrawler`},n=i.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:`FacebookExternalHit`}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(e){var t={name:`SlackBot`},n=i.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:`YahooSlurp`}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:`YandexBot`}}},{test:[/pingdom/i],describe:function(){return{name:`PingdomBot`}}},{test:[/opera/i],describe:function(e){var t={name:`Opera`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:`Opera`},n=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:`Samsung Internet for Android`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Whale/i],describe:function(e){var t={name:`NAVER Whale Browser`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/PaleMoon/i],describe:function(e){var t={name:`Pale Moon`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:`MZ Browser`},n=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/focus/i],describe:function(e){var t={name:`Focus`},n=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/swing/i],describe:function(e){var t={name:`Swing`},n=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/coast/i],describe:function(e){var t={name:`Opera Coast`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:`Opera Touch`},n=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/yabrowser/i],describe:function(e){var t={name:`Yandex Browser`},n=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:`UC Browser`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:`Maxthon`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/epiphany/i],describe:function(e){var t={name:`Epiphany`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/puffin/i],describe:function(e){var t={name:`Puffin`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sleipnir/i],describe:function(e){var t={name:`Sleipnir`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/k-meleon/i],describe:function(e){var t={name:`K-Meleon`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/micromessenger/i],describe:function(e){var t={name:`WeChat`},n=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?`QQ Browser Lite`:`QQ Browser`},n=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/msie|trident/i],describe:function(e){var t={name:`Internet Explorer`},n=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/\sedg\//i],describe:function(e){var t={name:`Microsoft Edge`},n=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:`Microsoft Edge`},n=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/vivaldi/i],describe:function(e){var t={name:`Vivaldi`},n=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/seamonkey/i],describe:function(e){var t={name:`SeaMonkey`},n=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sailfish/i],describe:function(e){var t={name:`Sailfish`},n=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return n&&(t.version=n),t}},{test:[/silk/i],describe:function(e){var t={name:`Amazon Silk`},n=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/phantom/i],describe:function(e){var t={name:`PhantomJS`},n=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/slimerjs/i],describe:function(e){var t={name:`SlimerJS`},n=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:`BlackBerry`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:`WebOS Browser`},n=i.default.getFirstMatch(a,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/bada/i],describe:function(e){var t={name:`Bada`},n=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/tizen/i],describe:function(e){var t={name:`Tizen`},n=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/qupzilla/i],describe:function(e){var t={name:`QupZilla`},n=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/librewolf/i],describe:function(e){var t={name:`LibreWolf`},n=i.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:`Firefox`},n=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/electron/i],describe:function(e){var t={name:`Electron`},n=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(e){var t={name:`Sogou Browser`},n=i.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,e),r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),a=i.default.getFirstMatch(/se ([\d.]+)x/i,e),o=n||r||a;return o&&(t.version=o),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:`Miui`},n=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){return!!e.hasBrand(`DuckDuckGo`)||e.test(/\sDdg\/[\d.]+$/i)},describe:function(e,t){var n={name:`DuckDuckGo`};if(t){var r=t.getBrandVersion(`DuckDuckGo`);if(r)return n.version=r,n}var a=i.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,e);return a&&(n.version=a),n}},{test:function(e){return e.hasBrand(`Brave`)},describe:function(e,t){var n={name:`Brave`};if(t){var r=t.getBrandVersion(`Brave`);if(r)return n.version=r,n}return n}},{test:[/chromium/i],describe:function(e){var t={name:`Chromium`},n=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:`Chrome`},n=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/GSA/i],describe:function(e){var t={name:`Google Search`},n=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){var t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe:function(e){var t={name:`Android Browser`},n=i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/playstation 4/i],describe:function(e){var t={name:`PlayStation 4`},n=i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:`Safari`},n=i.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/.*/i],describe:function(e){var t=e.search(`\\(`)===-1?/^(.*)\/(.*) /:/^(.*)\/(.*)[ \t]\((.*)/;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}],e.exports=t.default},93:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},a=n(18);t.default=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:a.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),n=i.default.getWindowsVersionName(t);return{name:a.OS_MAP.Windows,version:t,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:a.OS_MAP.iOS},n=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return n&&(t.version=n),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,`.`),n=i.default.getMacOSVersionName(t),r={name:a.OS_MAP.MacOS,version:t};return n&&(r.versionName=n),r}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,`.`);return{name:a.OS_MAP.iOS,version:t}}},{test:[/OpenHarmony/i],describe:function(e){var t=i.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.HarmonyOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),n=i.default.getAndroidVersionName(t),r={name:a.OS_MAP.Android,version:t};return n&&(r.versionName=n),r}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),n={name:a.OS_MAP.WebOS};return t&&t.length&&(n.version=t),n}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:a.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:a.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:a.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.PlayStation4,version:t}}}],e.exports=t.default},94:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},a=n(18);t.default=[{test:[/googlebot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Google`}}},{test:[/linespider/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Line`}}},{test:[/amazonbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Amazon`}}},{test:[/gptbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`OpenAI`}}},{test:[/chatgpt-user/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`OpenAI`}}},{test:[/oai-searchbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`OpenAI`}}},{test:[/baiduspider/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Baidu`}}},{test:[/bingbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Bing`}}},{test:[/duckduckbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`DuckDuckGo`}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Anthropic`}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Webz.io`}}},{test:[/diffbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Diffbot`}}},{test:[/perplexitybot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Perplexity AI`}}},{test:[/perplexity-user/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Perplexity AI`}}},{test:[/youbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`You.com`}}},{test:[/ia_archiver/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Internet Archive`}}},{test:[/meta-webindexer/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Meta`}}},{test:[/meta-externalads/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Meta`}}},{test:[/meta-externalagent/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Meta`}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Meta`}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Meta`}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Slack`}}},{test:[/yahoo/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Yahoo`}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Yandex`}}},{test:[/pingdom/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:`Pingdom`}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&`Nova`,n={type:a.PLATFORMS_MAP.mobile,vendor:`Huawei`};return t&&(n.model=t),n}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:`Nexus`}}},{test:[/ipad/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:`Apple`,model:`iPad`}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:`Apple`,model:`iPad`}}},{test:[/kftt build/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:`Amazon`,model:`Kindle Fire HD 7`}}},{test:[/silk/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:`Amazon`}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),n=e.test(/like (ipod|iphone)/i);return t&&!n},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:a.PLATFORMS_MAP.mobile,vendor:`Apple`,model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:`Nexus`}}},{test:[/Nokia/i],describe:function(e){var t=i.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,e),n={type:a.PLATFORMS_MAP.mobile,vendor:`Nokia`};return t&&(n.model=t),n}},{test:[/[^-]mobi/i],describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return e.getBrowserName(!0)===`blackberry`},describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:`BlackBerry`}}},{test:function(e){return e.getBrowserName(!0)===`bada`},describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return e.getBrowserName()===`windows phone`},describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:`Microsoft`}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(`.`)[0]);return e.getOSName(!0)===`android`&&t>=3},describe:function(){return{type:a.PLATFORMS_MAP.tablet}}},{test:function(e){return e.getOSName(!0)===`android`},describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:function(e){return e.getOSName(!0)===`macos`},describe:function(){return{type:a.PLATFORMS_MAP.desktop,vendor:`Apple`}}},{test:function(e){return e.getOSName(!0)===`windows`},describe:function(){return{type:a.PLATFORMS_MAP.desktop}}},{test:function(e){return e.getOSName(!0)===`linux`},describe:function(){return{type:a.PLATFORMS_MAP.desktop}}},{test:function(e){return e.getOSName(!0)===`playstation 4`},describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:function(e){return e.getOSName(!0)===`roku`},describe:function(){return{type:a.PLATFORMS_MAP.tv}}}],e.exports=t.default},95:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},a=n(18);t.default=[{test:function(e){return e.getBrowserName(!0)===`microsoft edge`},describe:function(e){if(/\sedg\//i.test(e))return{name:a.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:a.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:a.ENGINE_MAP.Trident},n=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:a.ENGINE_MAP.Presto},n=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){var t=e.test(/gecko/i),n=e.test(/like gecko/i);return t&&!n},describe:function(e){var t={name:a.ENGINE_MAP.Gecko},n=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:a.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:a.ENGINE_MAP.WebKit},n=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}}],e.exports=t.default}})}))})),ay=/* @__PURE__ */ s(((e,t)=>{t.exports=s,s.default=s,s.stable=d,s.stableStringify=d;var n=`[...]`,r=`[Circular]`,i=[],a=[];function o(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function s(e,t,n,r){r===void 0&&(r=o()),l(e,``,0,[],void 0,0,r);var s;try{s=a.length===0?JSON.stringify(e,t,n):JSON.stringify(e,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var c=i.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return s}function c(e,t,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get===void 0?(r[n]=e,i.push([r,n,t])):o.configurable?(Object.defineProperty(r,n,{value:e}),i.push([r,n,t,o])):a.push([t,n,e])}function l(e,t,i,a,o,s,u){s+=1;var d;if(typeof e==`object`&&e){for(d=0;d<a.length;d++)if(a[d]===e){c(r,e,t,o);return}if(u.depthLimit!==void 0&&s>u.depthLimit){c(n,e,t,o);return}if(u.edgesLimit!==void 0&&i+1>u.edgesLimit){c(n,e,t,o);return}if(a.push(e),Array.isArray(e))for(d=0;d<e.length;d++)l(e[d],d,d,a,e,s,u);else{var f=Object.keys(e);for(d=0;d<f.length;d++){var p=f[d];l(e[p],p,d,a,e,s,u)}}a.pop()}}function u(e,t){return e<t?-1:+(e>t)}function d(e,t,n,r){r===void 0&&(r=o());var s=f(e,``,0,[],void 0,0,r)||e,c;try{c=a.length===0?JSON.stringify(s,t,n):JSON.stringify(s,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var l=i.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return c}function f(e,t,a,o,s,l,d){l+=1;var p;if(typeof e==`object`&&e){for(p=0;p<o.length;p++)if(o[p]===e){c(r,e,t,s);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(d.depthLimit!==void 0&&l>d.depthLimit){c(n,e,t,s);return}if(d.edgesLimit!==void 0&&a+1>d.edgesLimit){c(n,e,t,s);return}if(o.push(e),Array.isArray(e))for(p=0;p<e.length;p++)f(e[p],p,p,o,e,l,d);else{var m={},h=Object.keys(e).sort(u);for(p=0;p<h.length;p++){var g=h[p];f(e[g],g,p,o,e,l,d),m[g]=e[g]}if(s!==void 0)i.push([s,t,e]),s[t]=m;else return m}o.pop()}}function p(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(a.length>0)for(var r=0;r<a.length;r++){var i=a[r];if(i[1]===t&&i[0]===n){n=i[2],a.splice(r,1);break}}return e.call(this,t,n)}}})),oy=/* @__PURE__ */ u(iy()),sy=/* @__PURE__ */ u(ay());let cy=Wd(`network-monitor`,{level:Dd.info}),ly=Date.now(),uy=window.navigator?.userAgent?oy.default.parse(window.navigator.userAgent):void 0,dy=(e,t={depthLimit:10,edgesLimit:10})=>e instanceof Event?`'${e.type}' Event`:typeof e==`string`?e:(0,sy.default)(e,void 0,2,t);var fy=class{constructor(){this.unsubscribableObservers=[],this.runAllChecks=(e,t)=>J(this,void 0,void 0,function*(){if(!this.isReady||this.isRunningChecks&&!t)return;cy.info(`Run health checks, triggered by`,dy(e),`| Active resources`,this.resources.size),this.isRunningChecks=!0,this.synchroniseCheckInterval();let n=this.getFormattedTimestamp(this.getNowTimestamp()),r=yield this.isOnlineCheck();r?cy.debug(`Network connected at ${n}`):cy.warn(`Network disconnected at ${n}`);let i=this.normaliseSerializedSocketStatus(this.socketStatus.serialize(),r),a=this.preFlightSocketChecks(i);if(a||cy.debug(`Socket pre-flight checks failed`),!r||!a){cy.debug(`Aborting remaining health checks`);let e=[...this.resources].reduce((e,[t,n])=>{let i=e[n.resourceName];return i?(i.sourceRef=[...i.sourceRef,n.message.SOURCE_REF],e):Object.assign(Object.assign({},e),{[n.resourceName]:this.normaliseResourceHealth({name:n.resourceName,sourceRef:[n.message.SOURCE_REF],isConnected:n.isConnected,lastUpdated:n.lastUpdated},r)})},{});this.reportSystemHealth({isAuthenticated:this.user.isAuthenticated,isOnline:r,resources:e,resourcesAllConnected:!1,socket:i}),this.isRunningChecks=!1;return}let o=!0,s=[];this.resources.forEach((e,t)=>{let{resourceName:r,message:i,functions:a}=e,{resourceChecks:c=this.config.resourceChecks,resourceDataLogon:l=this.config.resourceDataLogon}=a,{SOURCE_REF:u}=i,d=!1,f,p,m,h,g;s.push(J(this,void 0,void 0,function*(){try{cy.debug(`Running health check against ${r}`);let e=yield Promise.race([c(u,t),ep(this.config.checkTimeout,()=>({isConnected:!1,lastUpdated:this.getNowTimestamp(),timeout:!0}))]);d=e.isConnected,f=e.lastUpdated,p=e.lastMessage,h=e.timeout}catch(e){d=!1,f=this.getNowTimestamp(),m=e,p=e?.receivedMessage??e}return g=p?.MESSAGE_TYPE===Ng.MSG_NACK||Rg(p,Tg.NOT_FOUND),n=this.getFormattedTimestamp(f??this.getNowTimestamp()),d?cy.debug(`${r} is healthy at ${n}`):cy.warn(`${r} is not healthy at ${n}`),p&&cy.debug(`${r} messaged at ${n}`,dy(p)),m&&cy.error(`${r} errored at ${n}`,dy(m)),h&&cy.warn(`${r} timed out at ${n}`),g&&(cy.error(`${r} issue, re-attempting data logon at ${n}`),l(e)),o&&(o=d),{name:r,sourceRef:[u],isConnected:d,lastUpdated:f,lastError:m}}))});let c=(yield Promise.allSettled(s)).reduce((e,t)=>{if(t.status===`fulfilled`){let n=e[t.value.name];return n?(n.sourceRef=[...n.sourceRef,...t.value.sourceRef],e):Object.assign(Object.assign({},e),{[t.value.name]:this.normaliseResourceHealth(t.value)})}return cy.warn(`Unexpected promise rejection occurred. Please check any custom resourceChecks return MonitoredResourceChecksResult.`),e},{});cy.debug(`Health checks complete`),this.reportSystemHealth({isAuthenticated:this.user.isAuthenticated,isOnline:r,resources:c,resourcesAllConnected:o,socket:i}),this.isRunningChecks=!1}),this.config.logLevel!==void 0&&(cy.level=this.config.logLevel)}create(){if(this.resources){cy.warn(`NetworkMonitor already created. If this is intentional, please call NetworkMonitor.destroy first.`);return}this.addListeners(),this.resources=/* @__PURE__ */ new Map,setTimeout(()=>{this.isReady=!0,this.synchroniseCheckInterval(),this.runAllChecks(`NetworkMonitor.create()`)},this.config.startDelay)}destroy(){this.removeListeners(),clearInterval(this.internalId),this.resources.clear(),this.resources=void 0,this.status=void 0,this.isReady=void 0}isOnlineCheck(){return Promise.resolve(navigator.onLine)}addResource(e,t){this.resources||this.create(),this.resources.set(e,t)}removeResource(e){this.resources.delete(e)}addListeners(){var e,t;(e=this.config.windowEvents)==null||e.forEach(e=>window.addEventListener(e,this.runAllChecks)),(t=this.config.documentEvents)==null||t.forEach(e=>document.addEventListener(e,this.runAllChecks)),this.config.genesisConnectEvents.includes(`stream`)&&this.unsubscribableObservers.push(this.connectEvents.addStreamListener(({detail:e})=>{let{functions:t,message:n,resourceName:r,stream:i}=e;this.config.ignoredGenesisResources.includes(r)||this.addResource(i,{functions:t,message:n,resourceName:r})},({detail:e})=>{let{resourceName:t,stream:n}=e;this.config.ignoredGenesisResources.includes(t)||this.removeResource(n)},({detail:e})=>{let{resourceName:t,stream:n,error:r}=e,i=r.receivedMessage??r,a=``;Rg(i,Tg.NOT_FOUND)?a=`Please check the resource is running.`:Rg(i,Tg.FORBIDDEN)&&(a=`You are not authorised to access this resource, removing it from monitoring.`,this.removeResource(n)),cy.error(`${t} errored at ${this.getFormattedTimestamp(this.getNowTimestamp())}.`,a,r)})),this.config.genesisConnectEvents.includes(`commit`)&&this.unsubscribableObservers.push(this.connectEvents.addCommitListener(e=>{this.config.ignoredGenesisResources.includes(e.detail.eventName)||this.runAllChecks(e)})),this.unsubscribableObservers.push(this.connectEvents.addMetadataListener(({detail:e})=>{let{resourceName:t,error:n}=e;if(n){cy.error(`${t} had an unrecoverable error at ${this.getFormattedTimestamp(this.getNowTimestamp())}.`,`Please check the resource is running.`,n);return}}))}removeListeners(){var e,t;(e=this.config.windowEvents)==null||e.forEach(e=>window.removeEventListener(e,this.runAllChecks)),(t=this.config.documentEvents)==null||t.forEach(e=>document.removeEventListener(e,this.runAllChecks)),this.unsubscribableObservers.forEach(e=>e()),this.unsubscribableObservers.length=0}reportSystemHealth(e){let t=this.config.eventEmitter??document;this.status=this.normaliseEventDetail(e),(this.status.isHealthy?cy.debug:cy.warn)(`Emitting 'system-health-changed' event`,dy(this.status)),t?.dispatchEvent(new CustomEvent(`system-health-changed`,{detail:this.status,bubbles:t!==document,composed:!0})),this.status.socket.reconnectionLimitReached&&(cy.debug(`Network monitoring no longer required. Please check your network and reload your application.`),this.destroy())}reportStabilityToGenesis(e){return J(this,void 0,void 0,function*(){return cy.debug(`User requested report stability to Genesis.`),cy.info(`Please attach this data to your Genesis Support request:
245
- `,JSON.stringify(e,null,2)),!0})}normaliseResourceHealth(e,t=!0){let n=t?e.isConnected:!1,r=e.lastUpdated??this.getNowTimestamp();return Object.assign(Object.assign({},e),{isConnected:n,lastUpdated:r})}normaliseSerializedSocketStatus(e,t=!0){let n=t?e.isConnected:!1,r=!n;return Object.assign(Object.assign({},e),{isConnected:n,isDisconnected:r})}normaliseEventDetail(e){let t=!!(e.socket?.isConfigured?e.isOnline&&e.socket?.isConnected&&e.resourcesAllConnected:e.isOnline),n=e.lastUpdated??this.getNowTimestamp(),r=e.nextUpdate??this.getNextTimestamp(),i=e.isAuthenticated&&this.user?this.user.username:void 0,a=Object.assign(Object.assign({},e),{browserInformation:uy,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:ly,runAllChecks:()=>{cy.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return cy.debug(`Socket not configured`),!1;if(e.isReconnecting)return cy.debug(`Socket reconnecting`),!1;if(e.isConnecting)return cy.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return cy.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&cy.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return cy.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return Wf(e)}getNowTimestamp(){return Date.now()}getNextTimestamp(){return new Date(Date.now()+this.config.checkInterval).getTime()}synchroniseCheckInterval(){clearInterval(this.internalId),this.internalId=setInterval(()=>this.runAllChecks(`check interval`),this.config.checkInterval)}};q([ry],fy.prototype,`config`,void 0),q([Z_],fy.prototype,`socketStatus`,void 0),q([Cg],fy.prototype,`connectEvents`,void 0),q([gg],fy.prototype,`user`,void 0),q([C],fy.prototype,`status`,void 0);let py=N.createInterface(e=>e.singleton(fy)),my={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},hy=N.createInterface();var gy;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(gy||(gy={}));var _y;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(_y||(_y={}));let vy=class{constructor(e,t,n=my){this.connect=e,this.user=t,this.kvStorageConfig=n}delete(e){return J(this,void 0,void 0,function*(){let t={DETAILS:{KEYS:e}},n=yield this.connect.commitEvent(_y.EVENT_KEY_VALUE_DELETE,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}get(e){return J(this,void 0,void 0,function*(){let t={REQUEST:{USER_NAME:this.kvStorageConfig.authEmail??this.user.userName,KEY:e}},n=yield this.connect.request(gy.REQ_KEY_VALUE_READ,t);if(n&&n.REPLY&&n.REPLY.length>0){let t=n.REPLY.map(e=>{let t=this.getDecodedValue(e.VALUE);return{kv:{key:e.KEY,value:t}}});return e?t[0]:t}return e?void 0:[]})}getDecodedValue(e){!e.startsWith(`str:`)&&!e.startsWith(`bin:`)&&(e=`str:${e}`);let t=Of(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=Of(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=Of(t)),t}list(){return J(this,void 0,void 0,function*(){let e={REQUEST:{USER_NAME:this.kvStorageConfig.authEmail??this.user.userName}},t=yield this.connect.request(gy.REQ_KEY_VALUE_LIST,e);return t&&t.REPLY&&t.REPLY.length>0?t.REPLY.map(e=>e.KEY):[]})}put(e){return J(this,void 0,void 0,function*(){let t={DETAILS:{RECORDS:e.map(e=>({KEY:e.key,VALUE:e.base64?Af(e.value):e.value}))}},n=yield this.connect.commitEvent(_y.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};vy=q([_d(0,sv),_d(1,gg),_d(2,Rt(hy))],vy),N.createInterface(e=>e.singleton(vy));var yy=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Ym(!1)}get isLoggedIn$(){return this.isLoggedInSubject.asObservable()}login(e){return J(this,void 0,void 0,function*(){return Promise.resolve(this.nextLoginResult)})}logout(){return J(this,void 0,void 0,function*(){return Promise.resolve(this.nextLogoutResult)})}reAuthFromSession(){return J(this,void 0,void 0,function*(){return Promise.resolve(this.nextReAuthResult)})}setTestUser(e={}){this.currentUser=new hg,this.currentUser.set(Object.assign({userName:`JaneDee`,profile:[`USER`],permission:[`CreateRules`]},e)),this.isLoggedIn=!0,this.isLoggedInSubject.next(!0)}resetTestUser(){this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject.next(!1)}};q([C],yy.prototype,`isWorking`,void 0),q([C],yy.prototype,`loggedUserResult`,void 0),q([C],yy.prototype,`currentUser`,void 0),q([C],yy.prototype,`isLoggedIn`,void 0);var by=class{constructor(){this.fetchMetadataRequired=!0,this.fetchingMetadata=!1,this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.customRequestFields=[],this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.criteriaOnlyRequest=!1}init(e,t){return Promise.resolve(this.initialized)}startStream(){return Promise.resolve()}setMetadata(e){this.availableIndexes=e.INDEXES??[],this.availableSortableFields=e.SORTABLE_FIELDS??[],this.availableCriteriaFields=e.CRITERIA_FIELDS??[],this.originalFieldDef=Sg(e),this.fieldMetadata=xg(this.originalFieldDef),this.requestFields=e.REQUEST_FIELD||[],this.customRequestFields=e.FIELD||[],this.fetchMetadataRequired=!1}unsetMedata(){this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.fetchMetadataRequired=!0}setStream(e){this.stream=Eh(Promise.resolve(e))}unsetStream(){this.stream=void 0}deinit(){}destroy(){}validResourceName(e){return!(!e||!e.trim().length)}getMetadata(e){return Promise.resolve(this.fieldMetadata)}snapshot(e){return Promise.resolve(null)}snapshotFiltered(e){return Promise.resolve(null)}updateData(e){return Promise.resolve()}dataHandler(e){return[]}addView(e){}dropView(e){}setFilter(e,t,n){return Promise.resolve()}clearFilter(e){return Promise.resolve()}createItem(e){return Promise.resolve(``)}deleteItem(e){return Promise.resolve()}updateItem(e,t){return Promise.resolve()}get dataserverOnlyParams(){return{}}get requestOnlyParams(){return{}}updateLoadMoreCount(e){}};q([C],by.prototype,`status`,void 0),q([C],by.prototype,`fetchMetadataRequired`,void 0),q([C],by.prototype,`originalFieldDef`,void 0),q([C],by.prototype,`fieldMetadata`,void 0),q([C],by.prototype,`requestFields`,void 0),q([C],by.prototype,`customRequestFields`,void 0),q([C],by.prototype,`availableIndexes`,void 0),q([C],by.prototype,`availableSortableFields`,void 0),q([C],by.prototype,`availableCriteriaFields`,void 0),q([C],by.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(gg));let xy=Wd(`foundation-ui`);var Sy=class extends Wv(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Lv.MAX_ROWS_250,this.maxView=Lv.MAX_VIEW_1000,this.resourceName=``,this.reverse=!1,this.withTimestampFormatting=!0,this.requiresFullDataRefresh=!0,this.moreRowsAvailable=!1,this.pendingMoreRows=0,this.viewRowCount=0,this.nextRequestOffset=0,this.rowsSyncedWithStream=/* @__PURE__ */ new Map,this.dataSubWasLoggedOff=!1,this.criteriaFromFilters=/* @__PURE__ */ new Map,this.update=new Ym(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==ey(t,`;`);this.refetchIfInitializedAndChanged(n)}dataChanged(e){e&&(this.clearData(),this.reset())}requestChanged(e,t){let n=JSON.stringify(e)!==JSON.stringify(t);this.refetchIfInitializedAndChanged(n)}refetchIfInitializedAndChanged(e){this.datasource.initialized&&e&&this.fetchGenesisData(null)}set datasourceConfig(e){e&&Object.keys(e).forEach(t=>{e[t]!==void 0&&(this[t]=e[t])})}disconnectedCallback(){var e,t;super.disconnectedCallback(),this.clearData(),(e=this.dataSub)==null||e.unsubscribe(),(t=this.update)==null||t.unsubscribe(),delete this.dataSub,delete this.update,this.datasource.destroy(),delete this.datasource}get effectiveRowId(){return this.rowId?this.rowId:this.datasource?.resourceType===yg.REQUEST_SERVER?Lv.REQUEST_SERVER_ROW_ID:Lv.DATASERVER_ROW_ID}reset(){this.requiresFullDataRefresh=!0,this.fetchGenesisData()}fetchGenesisData(){return J(this,arguments,void 0,function*(e=!0){var t;(t=this.dataSub)==null||t.unsubscribe(),this.dataSub=void 0,this.moreRowsAvailable=!1,this.pendingMoreRows=0,this.serverMoreRows=void 0,this.viewRowCount=0,this.pagingStopped=void 0,this.nextRequestOffset=0,this.fetchGeneration+=1;let n=this.fetchGeneration,r=()=>n!==this.fetchGeneration;if(this.data){this.syncComponentData(this.data);return}let i=e||!this.datasource.initialized;i||(this.connect.dataLogoff(this.sourceRef),this.clearData()),this.sourceRef=void 0;let a=yield this.datasource.init(this.datasourceOptions(),i);if(!r()){if(!a){this.handleError({message:`Genesis Datasource init failed for ${this.resourceName}`,loggerType:`error`});return}if(this.isSnapshot){let e=yield this.datasource.snapshot();if(r())return;let t=this.filterSnapshotResult(e);this.updateRequestPagingState(e,t?.length??0,this.initialRequestOffset()),this.syncComponentData(t);return}xy.debug(`requesting stream for ${this.resourceName}`),this.dataSub=this.datasource.stream.subscribe(e=>{if(r())return;e.DISCONNECTED&&this.handleError({message:`Genesis Datasource disconnected for ${this.resourceName}`,loggerType:`error`}),this.sourceRef=e.SOURCE_REF;let t=e.ROW?Iv(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Ng.LOGOFF_ACK){this.dataSubWasLoggedOff=!0;return}this.dataSubWasLoggedOff=!1,t?this.handleStreamUpdate(t):this.handleStreamUpdate(e)})}})}initDatasource(){return J(this,void 0,void 0,function*(){yield this.datasource.init(this.datasourceOptions(),!0)})}canRequestMoreRows(){if(!this.isConnected||!this.datasource||!this.moreRowsAvailable)return!1;switch(this.datasource.resourceType){case yg.REQUEST_SERVER:return!0;case yg.DATASERVER:return!!this.sourceRef&&!this.dataSubWasLoggedOff;default:return!1}}requestMoreRows(){return J(this,void 0,void 0,function*(){if(this.canRequestMoreRows())try{if(this.datasource.resourceType===yg.DATASERVER){this.pendingMoreRows+=1,yield this.connect.getMoreRows(this.sourceRef);return}let e=this.fetchGeneration,t=this.nextRequestOffset;this.moreRowsAvailable=!1;let n=yield this.datasource.snapshot({DETAILS:Object.assign(Object.assign({},this.datasource.requestOnlyParams?.DETAILS),{OFFSET:t})});if(e!==this.fetchGeneration)return;let r=Array.isArray(n?.REPLY)?n.REPLY:[];this.updateRequestPagingState(n,r.length,t),r.length>0&&this.handleStreamInserts(r)}catch(e){throw this.moreRowsAvailable=!0,this.pendingMoreRows=Math.max(0,this.pendingMoreRows-1),this.handleError({message:`Failed to request more rows for ${this.resourceName}`,loggerType:`error`,loggerArgs:[e]}),e}})}filterSnapshotResult(e){if(e){if(Array.isArray(e))return e;if(e.REPLY)return e.REPLY;if(e.ROW)return Iv(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==yg.DATASERVER){n&&(this.moreRowsAvailable=e.MORE_ROWS);return}this.viewRowCount=Math.max(0,this.viewRowCount+(t?.inserts?.length??0)-(t?.deletes?.length??0));let r=!1;if(n&&(r=this.pendingMoreRows>0,this.pendingMoreRows=Math.max(0,this.pendingMoreRows-1),this.serverMoreRows=e.MORE_ROWS),this.serverMoreRows===void 0)return;let i=r&&e.MORE_ROWS===!0&&!e.ROW?.length,a=Vv({moreRows:this.serverMoreRows,emptyReply:i,rowsHeld:this.viewRowCount,maxView:this.maxView});if(a===`more`&&this.pagingStopped===`view-full`)this.pagingStopped=void 0;else if((a===`view-full`||a===`stalled`)&&!this.pagingStopped){this.pagingStopped=a;let e=Hv({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&xy.warn(e)}this.moreRowsAvailable=a===`more`&&!this.pagingStopped}updateRequestPagingState(e,t,n){if(Array.isArray(e)||!e){this.moreRowsAvailable=!1;return}let r=e,i=r.NEXT_OFFSET,a=typeof i==`number`&&i>n,o=Number(this.maxRows)||0,s=t>0&&o>0&&t>=o;this.moreRowsAvailable=typeof r.MORE_ROWS==`boolean`?r.MORE_ROWS:i!==-1&&(a||s),this.nextRequestOffset=a?i:n+t}initialRequestOffset(){return Number(this.datasource.requestOnlyParams?.DETAILS?.OFFSET)||0}datasourceOptions(){return{criteria:this.buildCriteria(),fields:this.fields,isSnapshot:this.isSnapshot,orderBy:this.orderBy,resourceName:this.resourceName,request:this.request,reverse:this.reverse,maxRows:this.maxRows,maxView:this.maxView}}handleStreamUpdate(e){e&&(e.hasOwnProperty(`REPLY`)?this.applyRequestServerData(e):this.applyDataserverData(e))}applyRequestServerData(e){var t;if(!Array.isArray(e.REPLY)||!e.MESSAGE_TYPE?.startsWith(`REP_`)){this.handleError({message:`received invalid RequestServerResult`,loggerType:`error`,loggerArgs:[e]});return}if(this.requiresFullDataRefresh){(t=e.REPLY)==null||t.forEach(e=>{this.rowsSyncedWithStream.set(e[this.effectiveRowId],e)}),this.syncComponentData(Array.from(this.rowsSyncedWithStream.values()));return}this.handleStreamInserts(e.REPLY);let n=Array.from(this.rowsSyncedWithStream.values()).filter(t=>!e.REPLY.includes(t));this.handleStreamDeletes(n)}applyDataserverData(e){var t;if(this.requiresFullDataRefresh){(t=e.inserts)==null||t.forEach(e=>{this.rowsSyncedWithStream.set(e[this.effectiveRowId],e)});let n=Array.from(this.rowsSyncedWithStream.values());this.syncComponentData(n);return}e.inserts?.length>0&&this.handleStreamInserts(e.inserts),e.deletes?.length>0&&this.handleStreamDeletes(e.deletes),e.updates?.length>0&&this.handleStreamUpdates(e.updates)}buildCriteria(){return ey((this.criteria?.split(`;`)||[]).join(` && `),`;`)}setFilter(e,t){this.criteriaFromFilters.set(e,t),this.update.next(this.criteriaFromFilters)}removeFilter(e){this.criteriaFromFilters.delete(e),this.update.next(this.criteriaFromFilters)}handleError(e={}){let{message:t,loggerType:n,loggerArgs:r=[]}=e;t&&xy[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===vg.DATE||t===vg.DATETIME?Gf(e,t===vg.DATETIME):e}};q([sv],Sy.prototype,`connect`,void 0),q([Qv],Sy.prototype,`datasource`,void 0),q([D({mode:`boolean`})],Sy.prototype,`withGridInit`,void 0),q([D],Sy.prototype,`criteria`,void 0),q([C],Sy.prototype,`data`,void 0),q([D],Sy.prototype,`fields`,void 0),q([D({mode:`boolean`})],Sy.prototype,`isSnapshot`,void 0),q([D],Sy.prototype,`maxRows`,void 0),q([D],Sy.prototype,`maxView`,void 0),q([D],Sy.prototype,`orderBy`,void 0),q([D],Sy.prototype,`request`,void 0),q([D],Sy.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],Sy.prototype,`reverse`,void 0),q([D],Sy.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],Sy.prototype,`withTimestampFormatting`,void 0);let Cy=(e,t)=>!e.composedPath().includes(t),wy=(e,t)=>e.composedPath().includes(t),Ty=e=>e.tagName.toLowerCase().split(`-`)[0];function Ey(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let Dy=Wd(`foundation-criteria`);var Oy;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(Oy||(Oy={}));var ky=class e{constructor(e){this.$$operator=e}static And(){return new e(Oy.AND)}static Or(){return new e(Oy.OR)}static Not(){return new e(Oy.NOT)}static GreaterThan(){return new e(Oy.GT)}static GreaterThanOrEqual(){return new e(Oy.GE)}static LessThan(){return new e(Oy.LT)}static LessThanOrEqual(){return new e(Oy.LE)}static NotEqual(){return new e(Oy.NE)}static Equal(){return new e(Oy.EQ)}get operator(){return this.$$operator}};let Ay=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?`"${t}"`:t},jy=e=>t=>`${t.field} ${e} ${Ay(t)}`,My={AND:e=>jy(Oy.AND)(e),OR:e=>jy(Oy.OR)(e),NOT:e=>jy(Oy.NOT)(e),GT:e=>jy(Oy.GT)(e),GE:e=>jy(Oy.GE)(e),LT:e=>jy(Oy.LT)(e),LE:e=>jy(Oy.LE)(e),NE:e=>jy(Oy.NE)(e),EQ:e=>jy(Oy.EQ)(e),equals:e=>`${e.field}.equals(${Ay(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Ay(e)})`,contains:e=>`Expr.contains(${e.field}, ${Ay(e)})`,fieldContains:e=>`${e.field}.contains(${Ay(e)})`,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Ay(e)})`,startsWith:e=>`${e.field}.startsWith(${Ay(e)})`,endsWith:e=>`${e.field}.endsWith(${Ay(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Ay(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Ay(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Ay(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Ay(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Ay(e)})`},Ny=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),Py=e=>Array.isArray(e)?e:[e],Fy=`default`;var Iy=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,ky.And()),this.Or=(e,t={})=>this.withExpression(e,t,ky.Or()),this.Not=(e,t={})=>this.withExpression(e,t,ky.Not())}withExpression(e,t={},n=ky.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=Fy)=>{let a=this.expressions[t]??[];this.expressions[t]=[...a,{join:n||i,condition:r,expression:e}]};if(Array.isArray(e)){if(i){let t=e.filter(e=>{let t=e instanceof ky;return t&&Dy.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Ny(t,i),Fy)}else o(e,Fy)}else typeof e==`string`?o(e,Fy):o(e,e.group);return this}build(e){let t=Object.entries(this.expressions).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:`(${n.filter(({condition:e})=>!e||e()).map(({expression:e,join:t},n,r)=>this.parseExpression(e,r[n-1],t)).join(``)})`}),{});return e?e(t):`(${Object.values(t).join(` && `)})`}reset(){this.expressions={}}parseExpression(e,t,n){let r=[];return n&&t&&r.push(` ${n.operator} `),typeof e==`string`?r.push(e):Array.isArray(e)?(e.forEach((e,t,n)=>{if(e instanceof ky&&n[t-1]instanceof ky)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof ky?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Ly=class{constructor(e){this.serialiser=My.EQ,this.build=()=>{if(!this.field)throw Error(`Missing required param 'field'`);if(this.value===void 0)throw Error(`Missing required param 'value'`);if(!this.serialiser)throw Error(`Missing required param 'serialise'`);return{field:this.field,value:this.value,serialiser:this.serialiser,params:this.params,valueGetter:this.valueGetter,group:this.group}},e&&(this.field=e.field,this.value=e.value,this.serialiser=e.serialiser,this.params=e.params,this.valueGetter=e.valueGetter,this.group=e.group)}withField(e){return this.field=e,this}withValue(e){return this.value=e,this}withSerialiser(e){return this.serialiser=e,this}withParams(e){return this.params=e,this}withValueGetter(e){return this.valueGetter=e,this}withGroup(e){return this.group=e,this}};let Ry=(e=`rapid`)=>T`<${e}-segmented-control :value="${wf(e=>e.selectedLabel)}"><slot name="label" slot='label'></slot>${j(e=>e.criteriaOptions,T`<${e}-segmented-item @click=${(e,t)=>t.parent.itemClickHandler(e.label)}value=${e=>e.label}>${e=>e.label}</${e}-segmented-item>`)}</${e}-segmented-control>`,zy=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Iy,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(Py(i).map(e=>Py(n).map(t=>new Ly().withField(t).withValue(e).withSerialiser(r).build())),{join:ky.Or()}):t.And(new Ly().withField(n).withValue(i).withSerialiser(r).build()),t}}valueChanged(){this.dispatchEvent(new Event(`change`,{bubbles:!0,composed:!0}))}selectedLabelChanged(){let e=this.criteriaOptions.find(e=>e.label===this.selectedLabel);this.value=e?this.createCriteria(e).build():``}itemClickHandler(e){this.selectedLabel===e&&(this.selectedLabel=void 0)}};q([C],zy.prototype,`criteriaOptions`,void 0),q([C],zy.prototype,`prefix`,void 0),q([C],zy.prototype,`value`,void 0),q([C],zy.prototype,`selectedLabel`,void 0),zy=q([$e({name:`criteria-segmented-control`,template:Ry(),styles:O``})],zy);function By(e,t){let n=new Iy;n.withExpression(new Ly().withField(e.labelField??e.valueField).withValue(t).withSerialiser(My.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Vy(e,t){let n=new Iy;n.withExpression(new Ly().withField(e.valueField).withValue(t).withSerialiser(My.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let Hy=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,Uy=e=>T`<${e}-button ${k(`actionsOpener`)}id="actiosnMenuTrigger" class="actions-opener${e=>e.open?` opened`:``}" appearance="${e=>e.buttonAppearance}" part="actions-opener" @click=${e=>e.toggleActionsMenuVisibility()}>${e=>e.open?`✖`:T` ${e.name} `}</${e}-button><${e}-menu ${k(`actionsMenu`)}popover="manual" class="actions-menu ${e=>e.classNames}" part="actions-menu">${j(e=>e.allActions,T` ${A((e,t)=>e.isDisabled&&e.isDisabled(t.parent.rowData),T`<${e}-menu-item class="menu-item" tabindex="${(e,t)=>t.index}" disabled style=${(e,t)=>t.parent.hideDisabled?`display:none`:``}>${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} ${A((e,t)=>!e.isDisabled||!e.isDisabled(t.parent.rowData),T`<${e}-menu-item class="menu-item" tabindex="${(e,t)=>t.index}" @click=${(e,t)=>t.parent.onActionMenuItemClick(e.callback)}style="${e=>e.color?`color: ${e.color};`:``}">${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} `,{positioning:!0})}</${e}-menu>`,Wy=e=>T`<${e}-button appearance="${e=>e.buttonAppearance}" part="actions-opener" class="actions-opener" @click=${e=>e?.singleOption.callback(e.rowData)}?disabled=${e=>e?.singleOption.isDisabled&&e?.singleOption.isDisabled(e.rowData)}>${e=>e.getLabel(e?.singleOption.name)}</${e}-button>`,Gy=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Ty(e))}</div>`;var Ky=class extends P{constructor(){super(...arguments),this.isVertical=!1,this.addDefaultActions=!0,this.autoCloseOnAction=!0,this.name=`Actions`,this.open=!1,this.hideDisabled=!1,this.hideMenuSingleOption=!1}disconnectedCallback(){this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover(),super.disconnectedCallback()}updateMenuPosition(){let e=this.actionsOpener.getBoundingClientRect();this.actionsMenu.style.position=`fixed`,this.actionsMenu.style.top=`${e.top}px`,this.actionsMenu.style.left=`auto`,this.actionsMenu.style.right=`${window.innerWidth-e.right}px`}definitionChanged(e,t){this.actions=t?.actions??[],delete this.definition.actions,t.buttonText&&(this.name=t.buttonText,delete this.definition.customButtonText),t.isVertical&&(this.isVertical=t.isVertical,delete this.definition.isVertical),t.buttonAppearance&&(this.buttonAppearance=t.buttonAppearance,delete this.definition.buttonAppearance),t.hideMenuSingleOption&&(this.hideMenuSingleOption=t.hideMenuSingleOption,delete this.definition.hideMenuSingleOption)}openChanged(){this.classNames=mn([`visible`,this.open],[`hidden`,!this.open]),this.open?(this.updateMenuPosition(),this.actionsMenu.showPopover()):this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover()}toggleActionsMenuVisibility(){this.open=!this.open}onActionMenuItemClick(e){this.autoCloseOnAction&&(this.open=!1),e(this.rowData)}get allActions(){let e=[{name:`✖`,callback:()=>this.open=!1}];return this.addDefaultActions?[...this.actions??[],...e]:this.actions}get rowData(){if(!this.definition)return;let{node:e,data:t}=this.definition;return e?.data||t}getLabel(e){return typeof e==`function`?e(this.rowData):e}getTemplate(e){if(!this.hideMenuSingleOption)return Uy(e);let t=this.actions.filter(e=>!e.isDisabled||!e.isDisabled(this.rowData));if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],Wy(e)):Uy(e)}};q([C],Ky.prototype,`actions`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],Ky.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],Ky.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],Ky.prototype,`autoCloseOnAction`,void 0),q([C],Ky.prototype,`classNames`,void 0),q([C],Ky.prototype,`definition`,void 0),q([D],Ky.prototype,`name`,void 0),q([D({attribute:`open`,mode:`boolean`})],Ky.prototype,`open`,void 0),q([D],Ky.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],Ky.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],Ky.prototype,`hideMenuSingleOption`,void 0),q([C],Ky.prototype,`singleOption`,void 0),Ky.compose({baseName:`actions-menu`,styles:Nne,template:Gy});let qy=()=>{};function Jy(e){let t=new AbortController,n=e.filter(e=>e!=null),r=n.find(e=>e.aborted);if(r)return t.abort(r.reason),{signal:t.signal,dispose:qy};function i(){for(let e of n)e.removeEventListener(`abort`,a)}function a(){t.abort(this.reason),i()}for(let e of n)e.addEventListener(`abort`,a);return{signal:t.signal,dispose:i}}let Yy=!1;try{typeof GENX_ENABLE_AI<`u`&&(Yy=GENX_ENABLE_AI===`true`)}catch{}let Xy=()=>Yy||Mf(`ai`),Zy=Wd(`foundation-ai`);function Qy(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function $y(e,t){if(!Qy())return null;let n=new(window.SpeechRecognition||window.webkitSpeechRecognition);n.continuous=!0,n.interimResults=!0,n.lang=`en-US`;let r=``;return n.onresult=t=>{let n=``,i=``;for(let e=t.resultIndex;e<t.results.length;e+=1){let r=t.results[e][0].transcript;t.results[e].isFinal?i+=r:n+=r}i?(r+=i,e(r,!0)):n&&e(r+n,!1)},n.onerror=e=>{e.error!==`aborted`&&t?.(e.error||`Speech recognition error`)},n.start(),()=>{try{n.stop()}catch{}}}var eb=class{getStatus(){return J(this,void 0,void 0,function*(){return{provider:`none`,model:``}})}interpretCriteria(e,t){return J(this,void 0,void 0,function*(){return null})}};let tb=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`]),new Map(Object.entries(tb).map(([e,t])=>[t.toLowerCase(),e]));var nb=class extends Error{constructor(e,t,n,r,i){super(`${e} request refused: the AI usage budget is exhausted`+(t==null?``:` (spent ${n==null?`an unknown amount`:`$${n}`} of a $${t} budget)`)+(r?`: ${r}`:``)+`. Retrying will not clear this — the budget must be raised.`),this.vendorLabel=e,this.budgetUsd=t,this.spentUsd=n,this.detail=r,this.name=`BudgetExhaustedError`,this.otherVendorAvailable=i?.otherVendorAvailable,this.serverVendor=i?.serverVendor}};let rb=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,ib=e=>{try{return JSON.parse(e)}catch{return}},ab=e=>{let t=e?.code;return typeof t==`string`?t:void 0},ob=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,sb=e=>typeof e==`boolean`?e:void 0,cb=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function lb(e,t,n){let r=typeof t==`object`&&t?t:{},i=typeof r.details==`object`&&r.details!==null?r.details:{},a=typeof r.error==`string`?r.error:n;return new nb(e,ob(r.budgetUsd)??ob(i.budgetUsd),ob(r.spentUsd)??ob(i.spentUsd),a,{otherVendorAvailable:sb(r.otherVendorAvailable)??sb(i.otherVendorAvailable),serverVendor:cb(r.vendor)??cb(i.vendor)})}var ub=class extends Error{constructor(e,t,n,r,i){super(`${e} refused the request (${t})`+(n==null?``:` — HTTP ${n}`)+(r?` ${r}`:``)+(i?`: ${i}`:``)+`. Retrying will not clear this — the provider account must be fixed.`),this.vendorLabel=e,this.kind=t,this.upstreamStatus=n,this.upstreamType=r,this.detail=i,this.name=`ProviderRefusedError`}};let db=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),fb=Object.freeze([`authentication_error`,`permission_error`]);function pb(e){let t=typeof e==`object`&&e?e:{};for(let e of[t.error,t.details?.error])if(typeof e==`object`&&e){let{type:t,message:n}=e;return{type:typeof t==`string`?t:void 0,message:typeof n==`string`?n:void 0}}}function mb(e){let t=typeof e==`object`&&e?e:{},n=typeof t.details==`object`&&t.details!==null?t.details:{};for(let e of[t.kind,n.kind])if(e===`auth`||e===`spend`)return e}function hb(e){let t=pb(e);if(t?.type){if(fb.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function gb(e,t,n){if(t===`PROVIDER_REFUSED`)return mb(n)??hb(n)??`spend`;if(e!==`anthropic`)return;let r=hb(n);if(r)return r;let i=pb(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(db.some(t=>t.test(e)))return`spend`}}function _b(e,t,n,r,i){let a=pb(r);return new ub(e,t,n,a?.type,a?.message??i)}function vb(e){return Object.entries(tb).find(([,t])=>t===e)?.[0]}let yb=[`gemini-2.5-pro`,`gemini-2.5-flash`,`gemini-2.5-flash-lite`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],bb=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`];function xb(e){return e===`image/jpg`?`image/jpeg`:e}function Sb(e){return e.replace(/^data:[^,]*;base64,/,``)}let Cb=.5;function wb(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=Cb?r/Cb*t:t+(r-Cb)/.5*(n-t)}let Tb=1e6,Eb={"claude-haiku-4-5-20251001":{promptPerMillion:1,candidatePerMillion:5},"claude-fable-5":{promptPerMillion:10,candidatePerMillion:50},"claude-opus-4-8":{promptPerMillion:5,candidatePerMillion:25},"claude-opus-4-7":{promptPerMillion:5,candidatePerMillion:25},"claude-sonnet-5":{promptPerMillion:2,candidatePerMillion:10},"claude-sonnet-4-6":{promptPerMillion:3,candidatePerMillion:15}};function Db(e){return Eb[e]}function Ob(e,t){let{promptPerMillion:n,candidatePerMillion:r}=Db(e),i=Tb,a=Math.max(0,t.cacheWriteTokens-t.cacheWrite1hTokens),o=t.uncachedInputTokens/i*n,s=t.cacheReadTokens/i*n*.1,c=a/i*n*1.25+t.cacheWrite1hTokens/i*n*2,l=t.outputTokens/i*r,u=t.cacheReadTokens/i*n,d=t.cacheWriteTokens/i*n;return{costUsd:o+s+c+l,savedUsd:u-s+(d-c),breakdown:{promptUsd:o,cacheReadUsd:s,cacheWriteUsd:c,candidateUsd:l}}}let kb={"gemini-2.5-flash-lite":{kind:`flat`,rate:{promptPerMillion:.1,candidatePerMillion:.4}},"gemini-2.5-flash":{kind:`flat`,rate:{promptPerMillion:.3,candidatePerMillion:2.5}},"gemini-2.5-pro":{kind:`tiered`,standard:{promptPerMillion:1.25,candidatePerMillion:10},longContext:{promptPerMillion:2.5,candidatePerMillion:15}},"gemini-3.1-flash-lite":{kind:`flat`,rate:{promptPerMillion:.25,candidatePerMillion:1.5}},"gemini-3.5-flash":{kind:`flat`,rate:{promptPerMillion:1.5,candidatePerMillion:9}},"gemini-3.8-flash":{kind:`flat`,rate:{promptPerMillion:.75,candidatePerMillion:3.75}},"gemini-3.1-pro-preview":{kind:`tiered`,standard:{promptPerMillion:2,candidatePerMillion:12},longContext:{promptPerMillion:4,candidatePerMillion:18}}};function Ab(e,t){let n=kb[e];return n.kind===`flat`?n.rate:t>2e5?n.longContext:n.standard}function jb(e,t){let{promptPerMillion:n,candidatePerMillion:r}=Ab(e,t.promptTokens),i=Tb,a=Math.max(0,t.promptTokens-t.cachedTokens)/i*n,o=t.cachedTokens/i*n*.1,s=(t.candidateTokens+t.thoughtTokens)/i*r;return{costUsd:a+o+s,savedUsd:t.cachedTokens/i*n-o,breakdown:{promptUsd:a,cacheReadUsd:o,cacheWriteUsd:0,candidateUsd:s}}}let Mb=[`properties`,`patternProperties`,`$defs`,`definitions`],Nb=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],Pb=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Fb=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ib(e){if(Array.isArray(e))return e.map(Ib);if(Fb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ib(r);return t}return e}function Lb(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=Mb.includes(i)&&Fb(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Fb(r)?t(r,`${e}/${n}`):Ib(r)])):Nb.includes(i)&&Array.isArray(a)?a.map((n,r)=>Fb(n)?t(n,`${e}/${r}`):Ib(n)):Pb.includes(i)?Fb(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Fb(n)?t(n,`${e}/${r}`):Ib(n)):Ib(a):Ib(a)}return r}function Rb(e,t,n=``){return t(Lb(e,(e,n)=>Rb(e,t,n),n),n)}let zb=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Bb=[`oneOf`,`not`];function Vb(e){let t=[],n=[],r=[];return{schema:Rb(e,(e,i)=>{for(let n of zb)n in e&&(delete e[n],t.push(`${i}/${n}`));typeof e.minItems==`number`&&e.minItems>1&&(delete e.minItems,t.push(`${i}/minItems`));for(let t of Bb)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Fb(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function Hb(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Vb(e);return r.length&&Zy.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&Zy.warn(`AnthropicTransport: tool "${t}" requested schema enforcement, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}. The tool now accepts fewer inputs than its schema declared.`),a.length&&Zy.warn(`AnthropicTransport: tool "${t}" uses schema keywords enforcement cannot express (${a.join(`, `)}). They cannot be removed without changing the schema's meaning, so the request will be rejected. Rewrite them or drop enforceSchema for this tool.`),n}let Ub=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Wb(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Fb(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Fb(n)?n:void 0}function Gb(e,t,n,r){let i=t,a=n,o=typeof i.$ref==`string`?i.$ref:void 0;for(;o&&!a.has(o);){let t=Wb(e,o);if(!t)break;let{$ref:n}=i,r=gd(i,[`$ref`]);i=Object.assign(Object.assign({},Ib(t)),r),a=/* @__PURE__ */ new Set([...a,o]),o=typeof i.$ref==`string`?i.$ref:void 0}return typeof i.$ref==`string`&&r.push(i.$ref),Lb(i,t=>Gb(e,t,a,r),``)}function Kb(e){let t=[],n=Gb(e,e,/* @__PURE__ */ new Set,t);return t.length&&Zy.warn(`GeminiTransport: these \`$ref\` pointers could not be inlined — a cycle, a typo, or an external ref: ${[...new Set(t)].join(`, `)}. They are left in the schema, so Gemini will reject this declaration; that is deliberate, because dropping them would send a node that constrains nothing.`),Rb(n,e=>{if(Array.isArray(e.type)){let t=e.type.filter(e=>e!==`null`);t.length===1&&e.type.length!==t.length&&(e.type=t[0],e.nullable=!0)}if(Array.isArray(e.anyOf)){let t=e.anyOf.filter(Fb),n=t.filter(e=>e.type!==`null`);if(t.length===2&&n.length===1){let{anyOf:t}=e,r=gd(e,[`anyOf`]);return Object.assign(Object.assign(Object.assign({},n[0]),r),{nullable:!0})}}`const`in e&&(e.enum=[e.const],delete e.const);for(let t of Ub)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}function qb(e,t,n){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)?n?.aborted?n.reason:t.aborted?t.reason:e:e}function Jb(e,t){return new Promise((n,r)=>{let i=()=>t?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(t?.aborted){r(i());return}let a=()=>{clearTimeout(o),r(i())},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e);t?.addEventListener(`abort`,a,{once:!0})})}let Yb=Object.freeze({NO_API_KEY:`NO_API_KEY`,BAD_API_KEY:`BAD_API_KEY`,KEY_UNREADABLE:`KEY_UNREADABLE`,MODEL_NOT_ALLOWED:`MODEL_NOT_ALLOWED`,BAD_REQUEST:`BAD_REQUEST`,FALLBACKS_NOT_SUPPORTED:`FALLBACKS_NOT_SUPPORTED`,REQUEST_TOO_LARGE:`REQUEST_TOO_LARGE`,VENDOR_UNREACHABLE:`VENDOR_UNREACHABLE`}),Xb=new Set(Object.values(Yb));function Zb(e){return typeof e==`string`&&Xb.has(e)?e:void 0}let Qb=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),$b=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},ex=e=>e?.code!==void 0;function tx(e,t,n){if(e!==401&&e!==403||ex(t))return;let r=typeof n==`string`&&n.trim()===``;if($b(t)||r)return e===401?Qb.SIGNED_OUT:Qb.ACCESS_DENIED}function nx(e,t){return e===413&&t===void 0}function rx(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let ix=`The AI service refused the assistant's request. An administrator can find the details in the browser console.`;Object.freeze({NO_API_KEY:`The assistant isn't set up yet. An administrator needs to add an API key for its AI service.`,BAD_API_KEY:`The assistant can't use its AI service key. An administrator needs to check the key.`,KEY_UNREADABLE:`The assistant can't read its AI service key. An administrator needs to check how the key is stored.`,MODEL_NOT_ALLOWED:`The assistant asked for an AI model this app doesn't allow. An administrator needs to check the app's allowed models.`,BAD_REQUEST:ix,FALLBACKS_NOT_SUPPORTED:ix,REQUEST_TOO_LARGE:`This request is too large to send. Start a new conversation or send a shorter message, and if you attached a file, try a smaller one.`,VENDOR_UNREACHABLE:`The AI service can't be reached right now. Please try again in a few minutes. If it keeps happening, tell an administrator.`,SIGNED_OUT:`Your session has ended. Sign in again to use the assistant.`,ACCESS_DENIED:`You don't have access to the assistant. An administrator can give you access.`});let ax=e=>e!==Yb.VENDOR_UNREACHABLE;var ox=class extends Error{constructor(e,t,n,r){super(`${e} AI service refused the request (${n} ${t})`),this.vendorLabel=e,this.code=t,this.status=n,this.detail=r,this.name=`AIServiceError`}get terminal(){return ax(this.code)}};function sx(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let cx=Object.freeze([/prompt is too long/i,/input token count .* exceeds/i,/maximum context length/i,/context[_ ]length[_ ]exceeded/i,/too many (input )?tokens/i]),lx=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var ux=class extends Error{constructor(e,t,n,r){super(`${e} rejected the request — the prompt exceeds the model context window`+(t!=null&&n!=null?` (${t} > ${n})`:``)+(r?`: ${r}`:``)+`. Retrying will not clear this — the conversation must be compacted.`),this.vendorLabel=e,this.promptTokens=t,this.limitTokens=n,this.detail=r,this.name=`ContextOverflowError`}};function dx(e){if(!e||typeof e!=`object`)return[];let t=[],n=(e,r)=>{if(!(r>4||!e||typeof e!=`object`))for(let i of Object.values(e))typeof i==`string`?t.push(i):typeof i==`object`&&n(i,r+1)};return n(e,0),t}function fx(e,t,n){if(t===400)for(let e of dx(n)){if(!cx.some(t=>t.test(e)))continue;let t=lx.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function px(e,t,n,r){return J(this,void 0,void 0,function*(){let i=e.getReader(),a=new TextDecoder,o=``,s=e=>/* @__PURE__ */ Error(`${n} proxy sent a malformed frame: ${e.slice(0,120)}`),c=e=>{if(!e)return;let t;try{t=JSON.parse(e)}catch{throw s(e)}if(typeof t!=`object`||!t||Array.isArray(t))throw s(e);let i=t;if(i.t===`ok`){if(i.body==null)throw Error(`${n} proxy sent an ok frame without a body`);return i}if(i.t===`err`){if(typeof i.status!=`number`)throw Error(`${n} proxy sent an err frame without a numeric status`);return i}if(i.t===`ping`){if(r>0&&typeof i.sinceLastEventMs==`number`&&i.sinceLastEventMs>r)throw new DOMException(`${n} request stalled: proxy reported ${i.sinceLastEventMs}ms since the last upstream event (exceeds ${r}ms)`,`TimeoutError`);return}};try{for(;;){let{done:e,value:n}=yield i.read();if(e)break;t(),o+=a.decode(n,{stream:!0});let r=o.indexOf(`
245
+ `,JSON.stringify(e,null,2)),!0})}normaliseResourceHealth(e,t=!0){let n=t?e.isConnected:!1,r=e.lastUpdated??this.getNowTimestamp();return Object.assign(Object.assign({},e),{isConnected:n,lastUpdated:r})}normaliseSerializedSocketStatus(e,t=!0){let n=t?e.isConnected:!1,r=!n;return Object.assign(Object.assign({},e),{isConnected:n,isDisconnected:r})}normaliseEventDetail(e){let t=!!(e.socket?.isConfigured?e.isOnline&&e.socket?.isConnected&&e.resourcesAllConnected:e.isOnline),n=e.lastUpdated??this.getNowTimestamp(),r=e.nextUpdate??this.getNextTimestamp(),i=e.isAuthenticated&&this.user?this.user.username:void 0,a=Object.assign(Object.assign({},e),{browserInformation:uy,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:ly,runAllChecks:()=>{cy.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return cy.debug(`Socket not configured`),!1;if(e.isReconnecting)return cy.debug(`Socket reconnecting`),!1;if(e.isConnecting)return cy.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return cy.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&cy.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return cy.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return Wf(e)}getNowTimestamp(){return Date.now()}getNextTimestamp(){return new Date(Date.now()+this.config.checkInterval).getTime()}synchroniseCheckInterval(){clearInterval(this.internalId),this.internalId=setInterval(()=>this.runAllChecks(`check interval`),this.config.checkInterval)}};q([ry],fy.prototype,`config`,void 0),q([Z_],fy.prototype,`socketStatus`,void 0),q([Cg],fy.prototype,`connectEvents`,void 0),q([gg],fy.prototype,`user`,void 0),q([C],fy.prototype,`status`,void 0);let py=N.createInterface(e=>e.singleton(fy)),my={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},hy=N.createInterface();var gy;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(gy||(gy={}));var _y;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(_y||(_y={}));let vy=class{constructor(e,t,n=my){this.connect=e,this.user=t,this.kvStorageConfig=n}delete(e){return J(this,void 0,void 0,function*(){let t={DETAILS:{KEYS:e}},n=yield this.connect.commitEvent(_y.EVENT_KEY_VALUE_DELETE,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}get(e){return J(this,void 0,void 0,function*(){let t={REQUEST:{USER_NAME:this.kvStorageConfig.authEmail??this.user.userName,KEY:e}},n=yield this.connect.request(gy.REQ_KEY_VALUE_READ,t);if(n&&n.REPLY&&n.REPLY.length>0){let t=n.REPLY.map(e=>{let t=this.getDecodedValue(e.VALUE);return{kv:{key:e.KEY,value:t}}});return e?t[0]:t}return e?void 0:[]})}getDecodedValue(e){!e.startsWith(`str:`)&&!e.startsWith(`bin:`)&&(e=`str:${e}`);let t=Of(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=Of(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=Of(t)),t}list(){return J(this,void 0,void 0,function*(){let e={REQUEST:{USER_NAME:this.kvStorageConfig.authEmail??this.user.userName}},t=yield this.connect.request(gy.REQ_KEY_VALUE_LIST,e);return t&&t.REPLY&&t.REPLY.length>0?t.REPLY.map(e=>e.KEY):[]})}put(e){return J(this,void 0,void 0,function*(){let t={DETAILS:{RECORDS:e.map(e=>({KEY:e.key,VALUE:e.base64?Af(e.value):e.value}))}},n=yield this.connect.commitEvent(_y.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};vy=q([_d(0,sv),_d(1,gg),_d(2,Rt(hy))],vy),N.createInterface(e=>e.singleton(vy));var yy=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Ym(!1)}get isLoggedIn$(){return this.isLoggedInSubject.asObservable()}login(e){return J(this,void 0,void 0,function*(){return Promise.resolve(this.nextLoginResult)})}logout(){return J(this,void 0,void 0,function*(){return Promise.resolve(this.nextLogoutResult)})}reAuthFromSession(){return J(this,void 0,void 0,function*(){return Promise.resolve(this.nextReAuthResult)})}setTestUser(e={}){this.currentUser=new hg,this.currentUser.set(Object.assign({userName:`JaneDee`,profile:[`USER`],permission:[`CreateRules`]},e)),this.isLoggedIn=!0,this.isLoggedInSubject.next(!0)}resetTestUser(){this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject.next(!1)}};q([C],yy.prototype,`isWorking`,void 0),q([C],yy.prototype,`loggedUserResult`,void 0),q([C],yy.prototype,`currentUser`,void 0),q([C],yy.prototype,`isLoggedIn`,void 0);var by=class{constructor(){this.fetchMetadataRequired=!0,this.fetchingMetadata=!1,this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.customRequestFields=[],this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.criteriaOnlyRequest=!1}init(e,t){return Promise.resolve(this.initialized)}startStream(){return Promise.resolve()}setMetadata(e){this.availableIndexes=e.INDEXES??[],this.availableSortableFields=e.SORTABLE_FIELDS??[],this.availableCriteriaFields=e.CRITERIA_FIELDS??[],this.originalFieldDef=Sg(e),this.fieldMetadata=xg(this.originalFieldDef),this.requestFields=e.REQUEST_FIELD||[],this.customRequestFields=e.FIELD||[],this.fetchMetadataRequired=!1}unsetMedata(){this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.fetchMetadataRequired=!0}setStream(e){this.stream=Eh(Promise.resolve(e))}unsetStream(){this.stream=void 0}deinit(){}destroy(){}validResourceName(e){return!(!e||!e.trim().length)}getMetadata(e){return Promise.resolve(this.fieldMetadata)}snapshot(e){return Promise.resolve(null)}snapshotFiltered(e){return Promise.resolve(null)}updateData(e){return Promise.resolve()}dataHandler(e){return[]}addView(e){}dropView(e){}setFilter(e,t,n){return Promise.resolve()}clearFilter(e){return Promise.resolve()}createItem(e){return Promise.resolve(``)}deleteItem(e){return Promise.resolve()}updateItem(e,t){return Promise.resolve()}get dataserverOnlyParams(){return{}}get requestOnlyParams(){return{}}updateLoadMoreCount(e){}};q([C],by.prototype,`status`,void 0),q([C],by.prototype,`fetchMetadataRequired`,void 0),q([C],by.prototype,`originalFieldDef`,void 0),q([C],by.prototype,`fieldMetadata`,void 0),q([C],by.prototype,`requestFields`,void 0),q([C],by.prototype,`customRequestFields`,void 0),q([C],by.prototype,`availableIndexes`,void 0),q([C],by.prototype,`availableSortableFields`,void 0),q([C],by.prototype,`availableCriteriaFields`,void 0),q([C],by.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(gg));let xy=Wd(`foundation-ui`);var Sy=class extends Wv(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Lv.MAX_ROWS_250,this.maxView=Lv.MAX_VIEW_1000,this.resourceName=``,this.reverse=!1,this.withTimestampFormatting=!0,this.appliedDatasourceConfig={},this.requiresFullDataRefresh=!0,this.moreRowsAvailable=!1,this.pendingMoreRows=0,this.viewRowCount=0,this.nextRequestOffset=0,this.rowsSyncedWithStream=/* @__PURE__ */ new Map,this.dataSubWasLoggedOff=!1,this.criteriaFromFilters=/* @__PURE__ */ new Map,this.update=new Ym(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==ey(t,`;`);this.refetchIfInitializedAndChanged(n)}dataChanged(e){e&&(this.clearData(),this.reset())}requestChanged(e,t){let n=JSON.stringify(e)!==JSON.stringify(t);this.refetchIfInitializedAndChanged(n)}refetchIfInitializedAndChanged(e){this.datasource.initialized&&e&&this.fetchGenesisData(null)}set datasourceConfig(e){e&&Object.keys(e).forEach(t=>{let n=e[t];n!==void 0&&n!==this.appliedDatasourceConfig[t]&&(this.appliedDatasourceConfig[t]=n,this[t]=n)})}disconnectedCallback(){var e,t;super.disconnectedCallback(),this.clearData(),(e=this.dataSub)==null||e.unsubscribe(),(t=this.update)==null||t.unsubscribe(),delete this.dataSub,delete this.update,this.datasource.destroy(),delete this.datasource}get effectiveRowId(){return this.rowId?this.rowId:this.datasource?.resourceType===yg.REQUEST_SERVER?Lv.REQUEST_SERVER_ROW_ID:Lv.DATASERVER_ROW_ID}reset(){this.requiresFullDataRefresh=!0,this.fetchGenesisData()}fetchGenesisData(){return J(this,arguments,void 0,function*(e=!0){var t;(t=this.dataSub)==null||t.unsubscribe(),this.dataSub=void 0,this.moreRowsAvailable=!1,this.pendingMoreRows=0,this.serverMoreRows=void 0,this.viewRowCount=0,this.pagingStopped=void 0,this.nextRequestOffset=0,this.fetchGeneration+=1;let n=this.fetchGeneration,r=()=>n!==this.fetchGeneration;if(this.data){this.syncComponentData(this.data);return}let i=e||!this.datasource.initialized;i||(this.connect.dataLogoff(this.sourceRef),this.clearData()),this.sourceRef=void 0;let a=yield this.datasource.init(this.datasourceOptions(),i);if(!r()){if(!a){this.handleError({message:`Genesis Datasource init failed for ${this.resourceName}`,loggerType:`error`});return}if(this.isSnapshot){let e=yield this.datasource.snapshot();if(r())return;let t=this.filterSnapshotResult(e);this.updateRequestPagingState(e,t?.length??0,this.initialRequestOffset()),this.syncComponentData(t);return}xy.debug(`requesting stream for ${this.resourceName}`),this.dataSub=this.datasource.stream.subscribe(e=>{if(r())return;e.DISCONNECTED&&this.handleError({message:`Genesis Datasource disconnected for ${this.resourceName}`,loggerType:`error`}),this.sourceRef=e.SOURCE_REF;let t=e.ROW?Iv(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Ng.LOGOFF_ACK){this.dataSubWasLoggedOff=!0;return}this.dataSubWasLoggedOff=!1,t?this.handleStreamUpdate(t):this.handleStreamUpdate(e)})}})}initDatasource(){return J(this,void 0,void 0,function*(){yield this.datasource.init(this.datasourceOptions(),!0)})}canRequestMoreRows(){if(!this.isConnected||!this.datasource||!this.moreRowsAvailable)return!1;switch(this.datasource.resourceType){case yg.REQUEST_SERVER:return!0;case yg.DATASERVER:return!!this.sourceRef&&!this.dataSubWasLoggedOff;default:return!1}}requestMoreRows(){return J(this,void 0,void 0,function*(){if(this.canRequestMoreRows())try{if(this.datasource.resourceType===yg.DATASERVER){this.pendingMoreRows+=1,yield this.connect.getMoreRows(this.sourceRef);return}let e=this.fetchGeneration,t=this.nextRequestOffset;this.moreRowsAvailable=!1;let n=yield this.datasource.snapshot({DETAILS:Object.assign(Object.assign({},this.datasource.requestOnlyParams?.DETAILS),{OFFSET:t})});if(e!==this.fetchGeneration)return;let r=Array.isArray(n?.REPLY)?n.REPLY:[];this.updateRequestPagingState(n,r.length,t),r.length>0&&this.handleStreamInserts(r)}catch(e){throw this.moreRowsAvailable=!0,this.pendingMoreRows=Math.max(0,this.pendingMoreRows-1),this.handleError({message:`Failed to request more rows for ${this.resourceName}`,loggerType:`error`,loggerArgs:[e]}),e}})}filterSnapshotResult(e){if(e){if(Array.isArray(e))return e;if(e.REPLY)return e.REPLY;if(e.ROW)return Iv(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==yg.DATASERVER){n&&(this.moreRowsAvailable=e.MORE_ROWS);return}this.viewRowCount=Math.max(0,this.viewRowCount+(t?.inserts?.length??0)-(t?.deletes?.length??0));let r=!1;if(n&&(r=this.pendingMoreRows>0,this.pendingMoreRows=Math.max(0,this.pendingMoreRows-1),this.serverMoreRows=e.MORE_ROWS),this.serverMoreRows===void 0)return;let i=r&&e.MORE_ROWS===!0&&!e.ROW?.length,a=Vv({moreRows:this.serverMoreRows,emptyReply:i,rowsHeld:this.viewRowCount,maxView:this.maxView});if(a===`more`&&this.pagingStopped===`view-full`)this.pagingStopped=void 0;else if((a===`view-full`||a===`stalled`)&&!this.pagingStopped){this.pagingStopped=a;let e=Hv({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&xy.warn(e)}this.moreRowsAvailable=a===`more`&&!this.pagingStopped}updateRequestPagingState(e,t,n){if(Array.isArray(e)||!e){this.moreRowsAvailable=!1;return}let r=e,i=r.NEXT_OFFSET,a=typeof i==`number`&&i>n,o=Number(this.maxRows)||0,s=t>0&&o>0&&t>=o;this.moreRowsAvailable=typeof r.MORE_ROWS==`boolean`?r.MORE_ROWS:i!==-1&&(a||s),this.nextRequestOffset=a?i:n+t}initialRequestOffset(){return Number(this.datasource.requestOnlyParams?.DETAILS?.OFFSET)||0}datasourceOptions(){return{criteria:this.buildCriteria(),fields:this.fields,isSnapshot:this.isSnapshot,orderBy:this.orderBy,resourceName:this.resourceName,request:this.request,reverse:this.reverse,maxRows:this.maxRows,maxView:this.maxView}}handleStreamUpdate(e){e&&(e.hasOwnProperty(`REPLY`)?this.applyRequestServerData(e):this.applyDataserverData(e))}applyRequestServerData(e){var t;if(!Array.isArray(e.REPLY)||!e.MESSAGE_TYPE?.startsWith(`REP_`)){this.handleError({message:`received invalid RequestServerResult`,loggerType:`error`,loggerArgs:[e]});return}if(this.requiresFullDataRefresh){(t=e.REPLY)==null||t.forEach(e=>{this.rowsSyncedWithStream.set(e[this.effectiveRowId],e)}),this.syncComponentData(Array.from(this.rowsSyncedWithStream.values()));return}this.handleStreamInserts(e.REPLY);let n=Array.from(this.rowsSyncedWithStream.values()).filter(t=>!e.REPLY.includes(t));this.handleStreamDeletes(n)}applyDataserverData(e){var t;if(this.requiresFullDataRefresh){(t=e.inserts)==null||t.forEach(e=>{this.rowsSyncedWithStream.set(e[this.effectiveRowId],e)});let n=Array.from(this.rowsSyncedWithStream.values());this.syncComponentData(n);return}e.inserts?.length>0&&this.handleStreamInserts(e.inserts),e.deletes?.length>0&&this.handleStreamDeletes(e.deletes),e.updates?.length>0&&this.handleStreamUpdates(e.updates)}buildCriteria(){return ey((this.criteria?.split(`;`)||[]).join(` && `),`;`)}setFilter(e,t){this.criteriaFromFilters.set(e,t),this.update.next(this.criteriaFromFilters)}removeFilter(e){this.criteriaFromFilters.delete(e),this.update.next(this.criteriaFromFilters)}handleError(e={}){let{message:t,loggerType:n,loggerArgs:r=[]}=e;t&&xy[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===vg.DATE||t===vg.DATETIME?Gf(e,t===vg.DATETIME):e}};q([sv],Sy.prototype,`connect`,void 0),q([Qv],Sy.prototype,`datasource`,void 0),q([D({mode:`boolean`})],Sy.prototype,`withGridInit`,void 0),q([D],Sy.prototype,`criteria`,void 0),q([C],Sy.prototype,`data`,void 0),q([D],Sy.prototype,`fields`,void 0),q([D({mode:`boolean`})],Sy.prototype,`isSnapshot`,void 0),q([D],Sy.prototype,`maxRows`,void 0),q([D],Sy.prototype,`maxView`,void 0),q([D],Sy.prototype,`orderBy`,void 0),q([D],Sy.prototype,`request`,void 0),q([D],Sy.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],Sy.prototype,`reverse`,void 0),q([D],Sy.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],Sy.prototype,`withTimestampFormatting`,void 0);let Cy=(e,t)=>!e.composedPath().includes(t),wy=(e,t)=>e.composedPath().includes(t),Ty=e=>e.tagName.toLowerCase().split(`-`)[0];function Ey(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let Dy=Wd(`foundation-criteria`);var Oy;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(Oy||(Oy={}));var ky=class e{constructor(e){this.$$operator=e}static And(){return new e(Oy.AND)}static Or(){return new e(Oy.OR)}static Not(){return new e(Oy.NOT)}static GreaterThan(){return new e(Oy.GT)}static GreaterThanOrEqual(){return new e(Oy.GE)}static LessThan(){return new e(Oy.LT)}static LessThanOrEqual(){return new e(Oy.LE)}static NotEqual(){return new e(Oy.NE)}static Equal(){return new e(Oy.EQ)}get operator(){return this.$$operator}};let Ay=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?`"${t}"`:t},jy=e=>t=>`${t.field} ${e} ${Ay(t)}`,My={AND:e=>jy(Oy.AND)(e),OR:e=>jy(Oy.OR)(e),NOT:e=>jy(Oy.NOT)(e),GT:e=>jy(Oy.GT)(e),GE:e=>jy(Oy.GE)(e),LT:e=>jy(Oy.LT)(e),LE:e=>jy(Oy.LE)(e),NE:e=>jy(Oy.NE)(e),EQ:e=>jy(Oy.EQ)(e),equals:e=>`${e.field}.equals(${Ay(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Ay(e)})`,contains:e=>`Expr.contains(${e.field}, ${Ay(e)})`,fieldContains:e=>`${e.field}.contains(${Ay(e)})`,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Ay(e)})`,startsWith:e=>`${e.field}.startsWith(${Ay(e)})`,endsWith:e=>`${e.field}.endsWith(${Ay(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Ay(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Ay(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Ay(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Ay(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Ay(e)})`},Ny=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),Py=e=>Array.isArray(e)?e:[e],Fy=`default`;var Iy=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,ky.And()),this.Or=(e,t={})=>this.withExpression(e,t,ky.Or()),this.Not=(e,t={})=>this.withExpression(e,t,ky.Not())}withExpression(e,t={},n=ky.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=Fy)=>{let a=this.expressions[t]??[];this.expressions[t]=[...a,{join:n||i,condition:r,expression:e}]};if(Array.isArray(e)){if(i){let t=e.filter(e=>{let t=e instanceof ky;return t&&Dy.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Ny(t,i),Fy)}else o(e,Fy)}else typeof e==`string`?o(e,Fy):o(e,e.group);return this}build(e){let t=Object.entries(this.expressions).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:`(${n.filter(({condition:e})=>!e||e()).map(({expression:e,join:t},n,r)=>this.parseExpression(e,r[n-1],t)).join(``)})`}),{});return e?e(t):`(${Object.values(t).join(` && `)})`}reset(){this.expressions={}}parseExpression(e,t,n){let r=[];return n&&t&&r.push(` ${n.operator} `),typeof e==`string`?r.push(e):Array.isArray(e)?(e.forEach((e,t,n)=>{if(e instanceof ky&&n[t-1]instanceof ky)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof ky?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Ly=class{constructor(e){this.serialiser=My.EQ,this.build=()=>{if(!this.field)throw Error(`Missing required param 'field'`);if(this.value===void 0)throw Error(`Missing required param 'value'`);if(!this.serialiser)throw Error(`Missing required param 'serialise'`);return{field:this.field,value:this.value,serialiser:this.serialiser,params:this.params,valueGetter:this.valueGetter,group:this.group}},e&&(this.field=e.field,this.value=e.value,this.serialiser=e.serialiser,this.params=e.params,this.valueGetter=e.valueGetter,this.group=e.group)}withField(e){return this.field=e,this}withValue(e){return this.value=e,this}withSerialiser(e){return this.serialiser=e,this}withParams(e){return this.params=e,this}withValueGetter(e){return this.valueGetter=e,this}withGroup(e){return this.group=e,this}};let Ry=(e=`rapid`)=>T`<${e}-segmented-control :value="${wf(e=>e.selectedLabel)}"><slot name="label" slot='label'></slot>${j(e=>e.criteriaOptions,T`<${e}-segmented-item @click=${(e,t)=>t.parent.itemClickHandler(e.label)}value=${e=>e.label}>${e=>e.label}</${e}-segmented-item>`)}</${e}-segmented-control>`,zy=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Iy,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(Py(i).map(e=>Py(n).map(t=>new Ly().withField(t).withValue(e).withSerialiser(r).build())),{join:ky.Or()}):t.And(new Ly().withField(n).withValue(i).withSerialiser(r).build()),t}}valueChanged(){this.dispatchEvent(new Event(`change`,{bubbles:!0,composed:!0}))}selectedLabelChanged(){let e=this.criteriaOptions.find(e=>e.label===this.selectedLabel);this.value=e?this.createCriteria(e).build():``}itemClickHandler(e){this.selectedLabel===e&&(this.selectedLabel=void 0)}};q([C],zy.prototype,`criteriaOptions`,void 0),q([C],zy.prototype,`prefix`,void 0),q([C],zy.prototype,`value`,void 0),q([C],zy.prototype,`selectedLabel`,void 0),zy=q([$e({name:`criteria-segmented-control`,template:Ry(),styles:O``})],zy);function By(e,t){let n=new Iy;n.withExpression(new Ly().withField(e.labelField??e.valueField).withValue(t).withSerialiser(My.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Vy(e,t){let n=new Iy;n.withExpression(new Ly().withField(e.valueField).withValue(t).withSerialiser(My.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let Hy=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,Uy=e=>T`<${e}-button ${k(`actionsOpener`)}id="actiosnMenuTrigger" class="actions-opener${e=>e.open?` opened`:``}" appearance="${e=>e.buttonAppearance}" part="actions-opener" @click=${e=>e.toggleActionsMenuVisibility()}>${e=>e.open?`✖`:T` ${e.name} `}</${e}-button><${e}-menu ${k(`actionsMenu`)}popover="manual" class="actions-menu ${e=>e.classNames}" part="actions-menu">${j(e=>e.allActions,T` ${A((e,t)=>e.isDisabled&&e.isDisabled(t.parent.rowData),T`<${e}-menu-item class="menu-item" tabindex="${(e,t)=>t.index}" disabled style=${(e,t)=>t.parent.hideDisabled?`display:none`:``}>${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} ${A((e,t)=>!e.isDisabled||!e.isDisabled(t.parent.rowData),T`<${e}-menu-item class="menu-item" tabindex="${(e,t)=>t.index}" @click=${(e,t)=>t.parent.onActionMenuItemClick(e.callback)}style="${e=>e.color?`color: ${e.color};`:``}">${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} `,{positioning:!0})}</${e}-menu>`,Wy=e=>T`<${e}-button appearance="${e=>e.buttonAppearance}" part="actions-opener" class="actions-opener" @click=${e=>e?.singleOption.callback(e.rowData)}?disabled=${e=>e?.singleOption.isDisabled&&e?.singleOption.isDisabled(e.rowData)}>${e=>e.getLabel(e?.singleOption.name)}</${e}-button>`,Gy=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Ty(e))}</div>`;var Ky=class extends P{constructor(){super(...arguments),this.isVertical=!1,this.addDefaultActions=!0,this.autoCloseOnAction=!0,this.name=`Actions`,this.open=!1,this.hideDisabled=!1,this.hideMenuSingleOption=!1}disconnectedCallback(){this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover(),super.disconnectedCallback()}updateMenuPosition(){let e=this.actionsOpener.getBoundingClientRect();this.actionsMenu.style.position=`fixed`,this.actionsMenu.style.top=`${e.top}px`,this.actionsMenu.style.left=`auto`,this.actionsMenu.style.right=`${window.innerWidth-e.right}px`}definitionChanged(e,t){this.actions=t?.actions??[],delete this.definition.actions,t.buttonText&&(this.name=t.buttonText,delete this.definition.customButtonText),t.isVertical&&(this.isVertical=t.isVertical,delete this.definition.isVertical),t.buttonAppearance&&(this.buttonAppearance=t.buttonAppearance,delete this.definition.buttonAppearance),t.hideMenuSingleOption&&(this.hideMenuSingleOption=t.hideMenuSingleOption,delete this.definition.hideMenuSingleOption)}openChanged(){this.classNames=mn([`visible`,this.open],[`hidden`,!this.open]),this.open?(this.updateMenuPosition(),this.actionsMenu.showPopover()):this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover()}toggleActionsMenuVisibility(){this.open=!this.open}onActionMenuItemClick(e){this.autoCloseOnAction&&(this.open=!1),e(this.rowData)}get allActions(){let e=[{name:`✖`,callback:()=>this.open=!1}];return this.addDefaultActions?[...this.actions??[],...e]:this.actions}get rowData(){if(!this.definition)return;let{node:e,data:t}=this.definition;return e?.data||t}getLabel(e){return typeof e==`function`?e(this.rowData):e}getTemplate(e){if(!this.hideMenuSingleOption)return Uy(e);let t=this.actions.filter(e=>!e.isDisabled||!e.isDisabled(this.rowData));if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],Wy(e)):Uy(e)}};q([C],Ky.prototype,`actions`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],Ky.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],Ky.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],Ky.prototype,`autoCloseOnAction`,void 0),q([C],Ky.prototype,`classNames`,void 0),q([C],Ky.prototype,`definition`,void 0),q([D],Ky.prototype,`name`,void 0),q([D({attribute:`open`,mode:`boolean`})],Ky.prototype,`open`,void 0),q([D],Ky.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],Ky.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],Ky.prototype,`hideMenuSingleOption`,void 0),q([C],Ky.prototype,`singleOption`,void 0),Ky.compose({baseName:`actions-menu`,styles:Nne,template:Gy});let qy=()=>{};function Jy(e){let t=new AbortController,n=e.filter(e=>e!=null),r=n.find(e=>e.aborted);if(r)return t.abort(r.reason),{signal:t.signal,dispose:qy};function i(){for(let e of n)e.removeEventListener(`abort`,a)}function a(){t.abort(this.reason),i()}for(let e of n)e.addEventListener(`abort`,a);return{signal:t.signal,dispose:i}}let Yy=!1;try{typeof GENX_ENABLE_AI<`u`&&(Yy=GENX_ENABLE_AI===`true`)}catch{}let Xy=()=>Yy||Mf(`ai`),Zy=Wd(`foundation-ai`);function Qy(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function $y(e,t){if(!Qy())return null;let n=new(window.SpeechRecognition||window.webkitSpeechRecognition);n.continuous=!0,n.interimResults=!0,n.lang=`en-US`;let r=``;return n.onresult=t=>{let n=``,i=``;for(let e=t.resultIndex;e<t.results.length;e+=1){let r=t.results[e][0].transcript;t.results[e].isFinal?i+=r:n+=r}i?(r+=i,e(r,!0)):n&&e(r+n,!1)},n.onerror=e=>{e.error!==`aborted`&&t?.(e.error||`Speech recognition error`)},n.start(),()=>{try{n.stop()}catch{}}}var eb=class{getStatus(){return J(this,void 0,void 0,function*(){return{provider:`none`,model:``}})}interpretCriteria(e,t){return J(this,void 0,void 0,function*(){return null})}};let tb=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`]),new Map(Object.entries(tb).map(([e,t])=>[t.toLowerCase(),e]));var nb=class extends Error{constructor(e,t,n,r,i){super(`${e} request refused: the AI usage budget is exhausted`+(t==null?``:` (spent ${n==null?`an unknown amount`:`$${n}`} of a $${t} budget)`)+(r?`: ${r}`:``)+`. Retrying will not clear this — the budget must be raised.`),this.vendorLabel=e,this.budgetUsd=t,this.spentUsd=n,this.detail=r,this.name=`BudgetExhaustedError`,this.otherVendorAvailable=i?.otherVendorAvailable,this.serverVendor=i?.serverVendor}};let rb=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,ib=e=>{try{return JSON.parse(e)}catch{return}},ab=e=>{let t=e?.code;return typeof t==`string`?t:void 0},ob=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,sb=e=>typeof e==`boolean`?e:void 0,cb=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function lb(e,t,n){let r=typeof t==`object`&&t?t:{},i=typeof r.details==`object`&&r.details!==null?r.details:{},a=typeof r.error==`string`?r.error:n;return new nb(e,ob(r.budgetUsd)??ob(i.budgetUsd),ob(r.spentUsd)??ob(i.spentUsd),a,{otherVendorAvailable:sb(r.otherVendorAvailable)??sb(i.otherVendorAvailable),serverVendor:cb(r.vendor)??cb(i.vendor)})}var ub=class extends Error{constructor(e,t,n,r,i){super(`${e} refused the request (${t})`+(n==null?``:` — HTTP ${n}`)+(r?` ${r}`:``)+(i?`: ${i}`:``)+`. Retrying will not clear this — the provider account must be fixed.`),this.vendorLabel=e,this.kind=t,this.upstreamStatus=n,this.upstreamType=r,this.detail=i,this.name=`ProviderRefusedError`}};let db=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),fb=Object.freeze([`authentication_error`,`permission_error`]);function pb(e){let t=typeof e==`object`&&e?e:{};for(let e of[t.error,t.details?.error])if(typeof e==`object`&&e){let{type:t,message:n}=e;return{type:typeof t==`string`?t:void 0,message:typeof n==`string`?n:void 0}}}function mb(e){let t=typeof e==`object`&&e?e:{},n=typeof t.details==`object`&&t.details!==null?t.details:{};for(let e of[t.kind,n.kind])if(e===`auth`||e===`spend`)return e}function hb(e){let t=pb(e);if(t?.type){if(fb.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function gb(e,t,n){if(t===`PROVIDER_REFUSED`)return mb(n)??hb(n)??`spend`;if(e!==`anthropic`)return;let r=hb(n);if(r)return r;let i=pb(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(db.some(t=>t.test(e)))return`spend`}}function _b(e,t,n,r,i){let a=pb(r);return new ub(e,t,n,a?.type,a?.message??i)}function vb(e){return Object.entries(tb).find(([,t])=>t===e)?.[0]}let yb=[`gemini-2.5-pro`,`gemini-2.5-flash`,`gemini-2.5-flash-lite`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],bb=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`];function xb(e){return e===`image/jpg`?`image/jpeg`:e}function Sb(e){return e.replace(/^data:[^,]*;base64,/,``)}let Cb=.5;function wb(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=Cb?r/Cb*t:t+(r-Cb)/.5*(n-t)}let Tb=1e6,Eb={"claude-haiku-4-5-20251001":{promptPerMillion:1,candidatePerMillion:5},"claude-fable-5":{promptPerMillion:10,candidatePerMillion:50},"claude-opus-4-8":{promptPerMillion:5,candidatePerMillion:25},"claude-opus-4-7":{promptPerMillion:5,candidatePerMillion:25},"claude-sonnet-5":{promptPerMillion:2,candidatePerMillion:10},"claude-sonnet-4-6":{promptPerMillion:3,candidatePerMillion:15}};function Db(e){return Eb[e]}function Ob(e,t){let{promptPerMillion:n,candidatePerMillion:r}=Db(e),i=Tb,a=Math.max(0,t.cacheWriteTokens-t.cacheWrite1hTokens),o=t.uncachedInputTokens/i*n,s=t.cacheReadTokens/i*n*.1,c=a/i*n*1.25+t.cacheWrite1hTokens/i*n*2,l=t.outputTokens/i*r,u=t.cacheReadTokens/i*n,d=t.cacheWriteTokens/i*n;return{costUsd:o+s+c+l,savedUsd:u-s+(d-c),breakdown:{promptUsd:o,cacheReadUsd:s,cacheWriteUsd:c,candidateUsd:l}}}let kb={"gemini-2.5-flash-lite":{kind:`flat`,rate:{promptPerMillion:.1,candidatePerMillion:.4}},"gemini-2.5-flash":{kind:`flat`,rate:{promptPerMillion:.3,candidatePerMillion:2.5}},"gemini-2.5-pro":{kind:`tiered`,standard:{promptPerMillion:1.25,candidatePerMillion:10},longContext:{promptPerMillion:2.5,candidatePerMillion:15}},"gemini-3.1-flash-lite":{kind:`flat`,rate:{promptPerMillion:.25,candidatePerMillion:1.5}},"gemini-3.5-flash":{kind:`flat`,rate:{promptPerMillion:1.5,candidatePerMillion:9}},"gemini-3.8-flash":{kind:`flat`,rate:{promptPerMillion:.75,candidatePerMillion:3.75}},"gemini-3.1-pro-preview":{kind:`tiered`,standard:{promptPerMillion:2,candidatePerMillion:12},longContext:{promptPerMillion:4,candidatePerMillion:18}}};function Ab(e,t){let n=kb[e];return n.kind===`flat`?n.rate:t>2e5?n.longContext:n.standard}function jb(e,t){let{promptPerMillion:n,candidatePerMillion:r}=Ab(e,t.promptTokens),i=Tb,a=Math.max(0,t.promptTokens-t.cachedTokens)/i*n,o=t.cachedTokens/i*n*.1,s=(t.candidateTokens+t.thoughtTokens)/i*r;return{costUsd:a+o+s,savedUsd:t.cachedTokens/i*n-o,breakdown:{promptUsd:a,cacheReadUsd:o,cacheWriteUsd:0,candidateUsd:s}}}let Mb=[`properties`,`patternProperties`,`$defs`,`definitions`],Nb=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],Pb=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Fb=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ib(e){if(Array.isArray(e))return e.map(Ib);if(Fb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ib(r);return t}return e}function Lb(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=Mb.includes(i)&&Fb(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Fb(r)?t(r,`${e}/${n}`):Ib(r)])):Nb.includes(i)&&Array.isArray(a)?a.map((n,r)=>Fb(n)?t(n,`${e}/${r}`):Ib(n)):Pb.includes(i)?Fb(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Fb(n)?t(n,`${e}/${r}`):Ib(n)):Ib(a):Ib(a)}return r}function Rb(e,t,n=``){return t(Lb(e,(e,n)=>Rb(e,t,n),n),n)}let zb=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Bb=[`oneOf`,`not`];function Vb(e){let t=[],n=[],r=[];return{schema:Rb(e,(e,i)=>{for(let n of zb)n in e&&(delete e[n],t.push(`${i}/${n}`));typeof e.minItems==`number`&&e.minItems>1&&(delete e.minItems,t.push(`${i}/minItems`));for(let t of Bb)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Fb(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function Hb(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Vb(e);return r.length&&Zy.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&Zy.warn(`AnthropicTransport: tool "${t}" requested schema enforcement, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}. The tool now accepts fewer inputs than its schema declared.`),a.length&&Zy.warn(`AnthropicTransport: tool "${t}" uses schema keywords enforcement cannot express (${a.join(`, `)}). They cannot be removed without changing the schema's meaning, so the request will be rejected. Rewrite them or drop enforceSchema for this tool.`),n}let Ub=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Wb(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Fb(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Fb(n)?n:void 0}function Gb(e,t,n,r){let i=t,a=n,o=typeof i.$ref==`string`?i.$ref:void 0;for(;o&&!a.has(o);){let t=Wb(e,o);if(!t)break;let{$ref:n}=i,r=gd(i,[`$ref`]);i=Object.assign(Object.assign({},Ib(t)),r),a=/* @__PURE__ */ new Set([...a,o]),o=typeof i.$ref==`string`?i.$ref:void 0}return typeof i.$ref==`string`&&r.push(i.$ref),Lb(i,t=>Gb(e,t,a,r),``)}function Kb(e){let t=[],n=Gb(e,e,/* @__PURE__ */ new Set,t);return t.length&&Zy.warn(`GeminiTransport: these \`$ref\` pointers could not be inlined — a cycle, a typo, or an external ref: ${[...new Set(t)].join(`, `)}. They are left in the schema, so Gemini will reject this declaration; that is deliberate, because dropping them would send a node that constrains nothing.`),Rb(n,e=>{if(Array.isArray(e.type)){let t=e.type.filter(e=>e!==`null`);t.length===1&&e.type.length!==t.length&&(e.type=t[0],e.nullable=!0)}if(Array.isArray(e.anyOf)){let t=e.anyOf.filter(Fb),n=t.filter(e=>e.type!==`null`);if(t.length===2&&n.length===1){let{anyOf:t}=e,r=gd(e,[`anyOf`]);return Object.assign(Object.assign(Object.assign({},n[0]),r),{nullable:!0})}}`const`in e&&(e.enum=[e.const],delete e.const);for(let t of Ub)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}function qb(e,t,n){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)?n?.aborted?n.reason:t.aborted?t.reason:e:e}function Jb(e,t){return new Promise((n,r)=>{let i=()=>t?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(t?.aborted){r(i());return}let a=()=>{clearTimeout(o),r(i())},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e);t?.addEventListener(`abort`,a,{once:!0})})}let Yb=Object.freeze({NO_API_KEY:`NO_API_KEY`,BAD_API_KEY:`BAD_API_KEY`,KEY_UNREADABLE:`KEY_UNREADABLE`,MODEL_NOT_ALLOWED:`MODEL_NOT_ALLOWED`,BAD_REQUEST:`BAD_REQUEST`,FALLBACKS_NOT_SUPPORTED:`FALLBACKS_NOT_SUPPORTED`,REQUEST_TOO_LARGE:`REQUEST_TOO_LARGE`,VENDOR_UNREACHABLE:`VENDOR_UNREACHABLE`}),Xb=new Set(Object.values(Yb));function Zb(e){return typeof e==`string`&&Xb.has(e)?e:void 0}let Qb=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),$b=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},ex=e=>e?.code!==void 0;function tx(e,t,n){if(e!==401&&e!==403||ex(t))return;let r=typeof n==`string`&&n.trim()===``;if($b(t)||r)return e===401?Qb.SIGNED_OUT:Qb.ACCESS_DENIED}function nx(e,t){return e===413&&t===void 0}function rx(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let ix=`The AI service refused the assistant's request. An administrator can find the details in the browser console.`;Object.freeze({NO_API_KEY:`The assistant isn't set up yet. An administrator needs to add an API key for its AI service.`,BAD_API_KEY:`The assistant can't use its AI service key. An administrator needs to check the key.`,KEY_UNREADABLE:`The assistant can't read its AI service key. An administrator needs to check how the key is stored.`,MODEL_NOT_ALLOWED:`The assistant asked for an AI model this app doesn't allow. An administrator needs to check the app's allowed models.`,BAD_REQUEST:ix,FALLBACKS_NOT_SUPPORTED:ix,REQUEST_TOO_LARGE:`This request is too large to send. Start a new conversation or send a shorter message, and if you attached a file, try a smaller one.`,VENDOR_UNREACHABLE:`The AI service can't be reached right now. Please try again in a few minutes. If it keeps happening, tell an administrator.`,SIGNED_OUT:`Your session has ended. Sign in again to use the assistant.`,ACCESS_DENIED:`You don't have access to the assistant. An administrator can give you access.`});let ax=e=>e!==Yb.VENDOR_UNREACHABLE;var ox=class extends Error{constructor(e,t,n,r){super(`${e} AI service refused the request (${n} ${t})`),this.vendorLabel=e,this.code=t,this.status=n,this.detail=r,this.name=`AIServiceError`}get terminal(){return ax(this.code)}};function sx(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let cx=Object.freeze([/prompt is too long/i,/input token count .* exceeds/i,/maximum context length/i,/context[_ ]length[_ ]exceeded/i,/too many (input )?tokens/i]),lx=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var ux=class extends Error{constructor(e,t,n,r){super(`${e} rejected the request — the prompt exceeds the model context window`+(t!=null&&n!=null?` (${t} > ${n})`:``)+(r?`: ${r}`:``)+`. Retrying will not clear this — the conversation must be compacted.`),this.vendorLabel=e,this.promptTokens=t,this.limitTokens=n,this.detail=r,this.name=`ContextOverflowError`}};function dx(e){if(!e||typeof e!=`object`)return[];let t=[],n=(e,r)=>{if(!(r>4||!e||typeof e!=`object`))for(let i of Object.values(e))typeof i==`string`?t.push(i):typeof i==`object`&&n(i,r+1)};return n(e,0),t}function fx(e,t,n){if(t===400)for(let e of dx(n)){if(!cx.some(t=>t.test(e)))continue;let t=lx.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function px(e,t,n,r){return J(this,void 0,void 0,function*(){let i=e.getReader(),a=new TextDecoder,o=``,s=e=>/* @__PURE__ */ Error(`${n} proxy sent a malformed frame: ${e.slice(0,120)}`),c=e=>{if(!e)return;let t;try{t=JSON.parse(e)}catch{throw s(e)}if(typeof t!=`object`||!t||Array.isArray(t))throw s(e);let i=t;if(i.t===`ok`){if(i.body==null)throw Error(`${n} proxy sent an ok frame without a body`);return i}if(i.t===`err`){if(typeof i.status!=`number`)throw Error(`${n} proxy sent an err frame without a numeric status`);return i}if(i.t===`ping`){if(r>0&&typeof i.sinceLastEventMs==`number`&&i.sinceLastEventMs>r)throw new DOMException(`${n} request stalled: proxy reported ${i.sinceLastEventMs}ms since the last upstream event (exceeds ${r}ms)`,`TimeoutError`);return}};try{for(;;){let{done:e,value:n}=yield i.read();if(e)break;t(),o+=a.decode(n,{stream:!0});let r=o.indexOf(`
246
246
  `);for(;r!==-1;){let e=o.slice(0,r).trim();o=o.slice(r+1);let t=c(e);if(t)return t;r=o.indexOf(`
247
247
  `)}}let e=c((o+a.decode()).trim());if(e)return e;throw Error(`${n} proxy stream ended without a terminal frame`)}finally{i.cancel().catch(()=>{})}})}let mx=12e4,hx=1e3;function gx(e){let t=(e?.get)?.call(e,`x-should-retry`);return typeof t==`string`&&t.trim().toLowerCase()===`false`}function _x(e){let t=(e?.get)?.call(e,`retry-after`);if(typeof t!=`string`||t.trim()===``)return;let n=Number(t.trim());if(Number.isFinite(n))return Math.max(0,n*hx);let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function vx(e){let t=typeof e==`object`&&e?e:{},n=typeof t.details==`object`&&t.details!==null?t.details:void 0;for(let e of[t.error,n?.error]){let t=e?.details;if(Array.isArray(t))for(let e of t){let t=e?.[`@type`];if(typeof t!=`string`||!t.endsWith(`google.rpc.RetryInfo`))continue;let n=e?.retryDelay;if(typeof n!=`string`)continue;let r=Number(n.replace(/s$/,``));if(Number.isFinite(r)&&r>=0)return r*hx}}}function yx(e,t,n,r=1/0){let i=t*2**e;return n==null||!Number.isFinite(n)?i:Math.max(i,Math.min(n,6e4,Math.max(0,r)))}function bx(e,t){return Math.max(0,e-t)}function xx(e){return J(this,void 0,void 0,function*(){var t;let{url:n,headers:r,body:i,credentials:a,vendorLabel:o,retryableStatuses:s,timeout:c,stallTimeout:l,backoffBaseMs:u,signal:d}=e,f=vb(o),p=(e,t,n)=>(Zy.error(`${o}Transport: the AI service refused the request (${t} ${e})${n?`: ${n}`:``}`),new ox(o,e,t,n)),m=0,h=(e,t)=>{let n=u*2**e,r=mx-m,i=yx(e,u,t,r);return m+=bx(i,n),t!=null&&i>n?Zy.warn(`${o}Transport: honouring the server's requested retry delay (${Math.round(i)}ms, asked ${Math.round(t)}ms)`):t!=null&&t>n&&Zy.warn(`${o}Transport: declining the server's requested retry delay (asked ${Math.round(t)}ms; the ${mx}ms sequence allowance is spent) — using the ladder's ${Math.round(i)}ms`),Jb(i,d)};for(let e=0;e<=5;e+=1){let u=new AbortController,m=performance.now(),g,_,v=()=>{let e=Math.round(performance.now()-m);return g===void 0?`${o} request timed out after ${e}ms — no response headers (the service never answered; nothing was received to stall on)`:`${o} request timed out after ${e}ms — headers arrived in ${Math.round(g-m)}ms (content-type: ${_??`unknown`}) but no body followed`},y=setTimeout(()=>u.abort(new DOMException(v(),`TimeoutError`)),c),b=()=>{l<=0||(clearTimeout(y),y=setTimeout(()=>u.abort(new DOMException(`${o} request stalled (no data for ${l}ms)`,`TimeoutError`)),l))},{signal:ee,dispose:x}=Jy([d,u.signal]);try{let c=yield fetch(n,{method:`POST`,headers:r,body:JSON.stringify(i),signal:ee,credentials:a});if(g=performance.now(),_=((t=c.headers)?.get)?.call(t,`content-type`)??void 0,!c.ok){let t=yield c.text(),n=ib(t),r=gb(f,ab(n),n);if(r)throw _b(o,r,c.status,n,t||void 0);let i=fx(f,c.status,n);if(i)throw new ux(o,i.promptTokens,i.limitTokens,i.message??(t||void 0));if(rb(c.status,ab(n)))throw lb(o,n,t||void 0);let a=Zb(ab(n));if(a&&a!==Yb.VENDOR_UNREACHABLE)throw p(a,c.status,sx(n));let l=tx(c.status,n,t);if(l)throw p(l,c.status,rx(n)??(t||void 0));if(nx(c.status,n))throw p(Yb.REQUEST_TOO_LARGE,c.status,t||void 0);let u=gx(c.headers);if(s.includes(c.status)&&!u&&e<5){Zy.warn(`${o}Transport: retryable status ${c.status}, retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,_x(c.headers)||vx(n));continue}throw a?p(a,c.status,sx(n)):Error(`${o} request error ${c.status}: ${t}`)}if((c.headers?.get(`content-type`))?.toLowerCase().includes(`application/x-ndjson`)&&c.body){b();let t=yield px(c.body,b,o,l);if(t.t===`ok`)return t.body;if(t.code===`UPSTREAM_STALLED`)throw new DOMException(`${o} request stalled: ${t.error??`no upstream data`}`,`TimeoutError`);let n=gb(f,t.code,t);if(n)throw _b(o,n,t.status,t,t.error);let r=fx(f,t.status,t);if(r)throw new ux(o,r.promptTokens,r.limitTokens,r.message??t.error);if(rb(t.status,t.code))throw lb(o,t);let i=Zb(t.code);if(i&&i!==Yb.VENDOR_UNREACHABLE)throw p(i,t.status,sx(t));if(s.includes(t.status)&&e<5){Zy.warn(`${o}Transport: retryable status ${t.status} (err frame), retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,vx(t));continue}throw i?p(i,t.status,sx(t)):Error(`${o} request error ${t.status}: ${t.error??JSON.stringify(t.details)}`)}return yield c.json()}catch(e){throw qb(e,u.signal,d)}finally{clearTimeout(y),x()}}throw Error(`${o} request failed: max retries exceeded`)})}function Sx(e){if(e&&e!==`auto`)return e===`required`?{type:`any`}:e===`none`?{type:`none`}:{type:`tool`,name:e.tool}}let Cx={"claude-fable-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-sonnet-5":1e6,"claude-sonnet-4-6":1e6,"claude-haiku-4-5-20251001":2e5},wx=`emit_structured_response`;function Tx(e){if(!bb.includes(e))throw Error(`AnthropicTransport: unsupported model "${e}". Use one of: ${bb.join(`, `)}.`)}function Ex(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-opus-4-7`||e===`claude-sonnet-5`}function Dx(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`||e===`claude-haiku-4-5-20251001`}function Ox(e){return e!==`claude-haiku-4-5-20251001`}function kx(e){return e===`claude-fable-5`}function Ax(e,t){let n=e===`claude-sonnet-5`||kx(e),r={type:`adaptive`,display:`summarized`};return t===`off`?kx(e)?r:n?{type:`disabled`}:void 0:t===`auto`||t!==void 0?Ox(e)?r:void 0:n?r:void 0}function jx(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`}let Mx={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Nx(e,t){if(t!==void 0&&t!==`auto`&&t!==`off`&&jx(e)&&Ox(e))return Mx[t]}let Px=`anthropic`;var Fx=class extends Error{constructor(e,t,n,r){super(`Response truncated at ${t==null?`the model's output-token limit`:`the max_tokens cap (${t})`} for model ${e}`+(r.length>0?` while emitting tool call(s): ${r.join(`, `)}`:``)+`. The output exceeds the per-response limit — raise the provider maxTokens (where configurable) or split the work into smaller outputs.`),this.model=e,this.maxTokens=t,this.outputTokens=n,this.toolNames=r,this.name=`ResponseTruncatedError`}},Ix=class e{warnIfThinkingUnclampable(e){if(this.warnedThinkingClamped)return;let t=this.clampWarning(e);t&&(this.warnedThinkingClamped=!0,Zy.warn(t))}clampWarning(e){switch(e){case void 0:return;case`off`:return kx(this.model)?`AnthropicTransport: thinkingPolicy 'off' ignored — ${this.model} always thinks and rejects an explicit disable. Reasoning tokens are still billed as output; switch model if you need them gone.`:void 0;case`auto`:return Ox(this.model)?void 0:`AnthropicTransport: thinkingPolicy 'auto' ignored — ${this.model} does not support adaptive thinking, so this turn runs without reasoning. Use a Sonnet or Opus tier if the agent needs it.`;case`minimal`:case`low`:case`medium`:case`high`:case`max`:return!Ox(this.model)||!jx(this.model)?`AnthropicTransport: thinkingPolicy '${e}' ignored — ${this.model} predates output_config.effort, so this turn runs at its default posture. Use Opus 4.8, Sonnet 5, or Fable 5 to set reasoning depth.`:void 0;default:return e}}constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=!1,this.warnedUnknownServingModels=/* @__PURE__ */ new Set;let t=e.model??`claude-haiku-4-5-20251001`;Tx(t),this.model=t,t===`claude-sonnet-5`?Zy.warn(`AnthropicTransport: using claude-sonnet-5 — standard Sonnet tier, higher cost than Haiku, and adaptive thinking runs by default so reasoning tokens add to output cost. Use for stronger reasoning or agent tasks.`):t===`claude-sonnet-4-6`?Zy.warn(`AnthropicTransport: using claude-sonnet-4-6 — higher cost than Haiku; use for stronger reasoning or agent tasks.`):t===`claude-opus-4-7`||t===`claude-opus-4-8`?Zy.warn(`AnthropicTransport: using ${t} — significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`):t===`claude-fable-5`&&Zy.warn(`AnthropicTransport: using claude-fable-5 — Anthropic's most capable model, priced above Opus tier ($10 / $50 per MTok) with thinking always on. Reserve for the hardest reasoning/long-horizon work. Requires ≥30-day data retention (unavailable under ZDR) and may return stop_reason "refusal"; pair with an Opus 4.8 fallback.`),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint,this.maxTokens=e.maxTokens??4096}getConfig(){return{provider:`anthropic`,model:this.model,contextLimit:Cx[this.model]}}getLifetimeCost(){return this.lifetimeCostUsd}getLifetimeSavings(){return this.lifetimeSavingsUsd}resetLifetimeCost(){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0}sendStructuredPrompt(e){return J(this,void 0,void 0,function*(){let{systemPrompt:t,userPrompt:n,responseSchema:r}=e,i=[{role:`user`,content:n}],a={model:this.model,max_tokens:this.maxTokens,messages:i};t&&(a.system=t);let o=r!=null&&Dx(this.model),s=r!=null&&!o;o?a.output_config=Object.assign(Object.assign({},a.output_config),{format:{type:`json_schema`,schema:r}}):s&&(a.tools=[{name:wx,description:`Emit the structured response that matches the required schema.`,input_schema:r}],a.tool_choice={type:`tool`,name:wx}),this.model===`claude-sonnet-5`&&(a.thinking={type:`disabled`});let c=yield this.post(a);if(s){let e=(c.content??[]).find(e=>e.type===`tool_use`&&e.name===wx);return e?JSON.stringify(e.input??{}):``}return(c.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(``)})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=/* @__PURE__ */ new Set([this.model,...(n?.fallbacks??[]).map(e=>e.model)]),i=this.toAnthropicMessages(e,t,n?.attachments,r),a={model:this.model,max_tokens:n?.maxTokens??this.maxTokens,messages:i};if(n?.systemPrompt&&(a.system=n.systemPrompt),n?.tools?.length&&(a.tools=n.tools.map(e=>Object.assign({name:e.name,description:e.description,input_schema:e.enforceSchema?Hb(e.parameters,e.name):e.parameters},e.enforceSchema?{strict:!0}:{}))),a.tools?.length){let e=Sx(n?.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingUnclampable(n?.thinkingPolicy);let o=Ax(this.model,n?.thinkingPolicy);o&&(a.thinking=o);let s=Nx(this.model,n?.thinkingPolicy);s&&(a.output_config=Object.assign(Object.assign({},a.output_config),{effort:s}));let c=o?.type===`adaptive`;n?.temperature!=null&&!Ex(this.model)&&!c&&(a.temperature=wb(n.temperature,{defaultTemp:1,maxTemp:1})),n?.responseSchema&&Dx(this.model)&&(a.output_config=Object.assign(Object.assign({},a.output_config),{format:{type:`json_schema`,schema:n.responseSchema}})),n?.fallbacks?.length&&(a.fallbacks=n.fallbacks.map(e=>e.maxTokens==null?{model:e.model}:{model:e.model,max_tokens:e.maxTokens})),n?.cachePolicy&&this.applyCacheControl(a,n.cachePolicy),n?.tailContext&&this.appendTailContext(a,n.tailContext);let l=yield this.post(a,n?.signal);return this.fromAnthropicResponse(l,a.max_tokens)})}applyCacheControl(e,t){if(t.scope==="default")return;let n=t.ttl===`1h`?{type:`ephemeral`,ttl:`1h`}:{type:`ephemeral`};if(t.scope===`tools`){e.tools?.length&&(e.tools[e.tools.length-1].cache_control=n);return}if(typeof e.system==`string`&&e.system.length>0?e.system=[{type:`text`,text:e.system,cache_control:n}]:e.tools?.length&&(e.tools[e.tools.length-1].cache_control=n),t.scope===`history`){let t=e.messages[e.messages.length-1];t&&Array.isArray(t.content)&&t.content.length>0&&(t.content[t.content.length-1].cache_control=n)}}appendTailContext(e,t){let n={type:`text`,text:t},r=e.messages[e.messages.length-1];r?.role===`user`&&Array.isArray(r.content)?r.content.push(n):e.messages.push({role:`user`,content:[n]})}logTokenUsage(t,n,r,i,a,o){let{costUsd:s,savedUsd:c,breakdown:l}=Ob(t,{uncachedInputTokens:n,outputTokens:r,cacheReadTokens:i,cacheWriteTokens:a,cacheWrite1hTokens:o});this.lifetimeCostUsd+=s,this.lifetimeSavingsUsd+=c;let u=e.COST_DECIMAL_PLACES;return console.log(`--- Anthropic Token Usage (${t}) ---`),console.log(`Prompt Tokens: ${n} ($${l.promptUsd.toFixed(u)})`),console.log(`Cache Read: ${i} ($${l.cacheReadUsd.toFixed(u)})`),console.log(`Cache Write: ${a} ($${l.cacheWriteUsd.toFixed(u)})`),console.log(`Candidate Tokens: ${r} ($${l.candidateUsd.toFixed(u)})`),console.log(`Total Cost: $${s.toFixed(u)}`),console.log(`Cache Saved: $${c.toFixed(u)} (lifetime $${this.lifetimeSavingsUsd.toFixed(u)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(u)}`),console.log(`--------------------------`),s}toAnthropicMessages(e,t,n,r=/* @__PURE__ */ new Set([this.model])){let i=[],a=(e,t)=>{let n=i[i.length-1];if(n&&n.role===e&&Array.isArray(n.content)){n.content.push(t);return}i.push({role:e,content:[t]})},o=e=>{let t=[],n=[];for(let r of e)r.kind===`image`?t.push({type:`image`,source:{type:`base64`,media_type:xb(r.mimeType),data:Sb(r.data)}}):n.push({type:`text`,text:`[File: ${r.name}]\n${r.content}`});return{images:t,texts:n}};for(let t of e){if(t.role===`system`||t.role===`system-event`||t.role===`synthetic-user`||t.role===`compacted-summary`||t.category===`reasoning`||t.category===`narration`||t.excludeFromProvider||t.thinking)continue;if(t.toolResult){let e=t.toolResult.attachments??[];a(`user`,{type:`tool_result`,tool_use_id:t.toolResult.toolCallId,content:e.length?[...t.toolResult.content?[{type:`text`,text:t.toolResult.content}]:[],...e.map(e=>({type:`image`,source:{type:`base64`,media_type:xb(e.mimeType),data:Sb(e.data)}}))]:t.toolResult.content});continue}if(t.toolCalls?.length){for(let e of this.reasoningToReplay(t.toolCalls[0],r))a(`assistant`,e);t.content&&a(`assistant`,{type:`text`,text:t.content});for(let e of t.toolCalls)a(`assistant`,{type:`tool_use`,id:e.id,name:e.name,input:e.args??{}});continue}let e=t.role===`user`?`user`:`assistant`;if(e===`user`&&t.attachments?.length){let{images:n,texts:r}=o(t.attachments);for(let t of n)a(e,t);t.content&&a(e,{type:`text`,text:t.content});for(let t of r)a(e,t)}else t.content&&a(e,{type:`text`,text:t.content})}if(t||n?.length){let{images:e,texts:r}=o(n??[]);for(let t of e)a(`user`,t);t&&a(`user`,{type:`text`,text:t});for(let e of r)a(`user`,e)}return i}reasoningToReplay(e,t){let n=e.providerMetadata?.[Px];if(!n)return[];let r=n.fallbacks??[],i=n.requestedModel===this.model&&t.has(n.model),a=n.model===this.model||i;return[...r,...a?n.reasoning??[]:[]]}servingModel(e){let t=e.model;return!t||t===this.model?this.model:bb.includes(t)?t:(this.warnedUnknownServingModels.has(t)||(this.warnedUnknownServingModels.add(t),Zy.warn(`AnthropicTransport: response was served by "${t}", which is not a known model — pricing it at the configured "${this.model}" rate instead of guessing. The reported cost for this request may be wrong; add the model to SUPPORTED_ANTHROPIC_MODEL_IDS.`)),this.model)}isUnbilledRefusal(e,t,n){return(t.output_tokens??0)>0?!1:e.type===`message`||n}costAttempt(e,t){let n=t.cache_read_input_tokens??0,r=t.cache_creation,i=r?.ephemeral_1h_input_tokens??0,a=t.cache_creation_input_tokens??(r?(r.ephemeral_5m_input_tokens??0)+i:0);return this.logTokenUsage(e,t.input_tokens??0,t.output_tokens??0,n,a,i)}fromAnthropicResponse(e,t=this.maxTokens){let n,r,i,a,o,s=this.servingModel(e);if(e.usage){let t=e.usage.input_tokens??0,c=e.usage.cache_read_input_tokens??0,l=e.usage.cache_creation,u=l?.ephemeral_1h_input_tokens??0,d=e.usage.cache_creation_input_tokens??(l?(l.ephemeral_5m_input_tokens??0)+u:0),f=e.usage.iterations;if(f?.length){let t=e.stop_reason===`refusal`;o=f.reduce((e,n,r)=>{let i=n.usage??n;if(this.isUnbilledRefusal(n,i,r===f.length-1&&t))return e;let a=n.model?this.servingModel({model:n.model}):this.model;return e+this.costAttempt(a,i)},0)}else o=this.isUnbilledRefusal({},e.usage,e.stop_reason===`refusal`)?0:this.costAttempt(s,e.usage);n=t+c+d,i=c,a=d,e.usage.output_tokens!=null&&(r=e.usage.output_tokens)}let c=e.content??[],l=[],u=[],d=[],f=[],p=c.map(e=>e.type).lastIndexOf(`fallback`),m=c.filter(e=>e.type===`fallback`);for(let[e,t]of c.entries()){let n=e>p;t.type===`tool_use`?n&&l.push({id:t.id,name:t.name,args:t.input??{}}):t.type===`thinking`?(n&&f.push(t),u.push(t.thinking)):t.type===`redacted_thinking`?n&&f.push(t):t.type===`text`&&d.push(t.text)}if(l.length>0&&(f.length>0||m.length>0)){let e={reasoning:f,model:s,requestedModel:this.model};m.length>0&&(e.fallbacks=m),l[0].providerMetadata=Object.assign(Object.assign({},l[0].providerMetadata),{[Px]:e})}if(e.stop_reason===`max_tokens`&&l.length>0)throw new Fx(this.model,t,r,l.map(e=>e.name));let h=u.join(``)||void 0,g=l.length>0?{role:`assistant`,content:d.join(``),reasoning:h,toolCalls:l}:{role:`assistant`,content:d.join(``),reasoning:h};n!=null&&(g.inputTokens=n),r!=null&&(g.outputTokens=r),i!=null&&(g.cacheReadTokens=i),a!=null&&(g.cacheWriteTokens=a),o!=null&&(g.cost=o),g.model=s;let _={parts:{functionCall:c.filter(e=>e.type===`tool_use`).length,thought:c.filter(e=>e.type===`thinking`||e.type===`redacted_thinking`).length,text:c.filter(e=>e.type===`text`).length}};return e.stop_reason&&(_.finishReason=e.stop_reason),g.responseMeta=_,g}buildEndpoint(){if(this.apiKey)return{url:`https://api.anthropic.com/v1/messages`,headers:{"Content-Type":`application/json`,"x-api-key":this.apiKey,"anthropic-version":`2023-06-01`,"anthropic-dangerous-direct-browser-access":`true`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`AnthropicTransport: no API key or server endpoint configured. Set ANTHROPIC_API_KEY in your .env or pass apiKey/serverEndpoint in AnthropicAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,headers:i,credentials:a}=this.buildEndpoint();return yield xx({url:r,headers:t.fallbacks?.length?Object.assign(Object.assign({},i),{"anthropic-beta":[i[`anthropic-beta`],`server-side-fallback-2026-06-01`].filter(Boolean).join(`,`)}):i,body:t,credentials:a,vendorLabel:tb.anthropic,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};Ix.TOKENS_PER_MILLION=1e6,Ix.COST_DECIMAL_PLACES=6,Ix.RATE_LIMIT_STATUS=429,Ix.SERVICE_UNAVAILABLE_STATUS=503,Ix.OVERLOADED_STATUS=529,Ix.RETRYABLE_STATUSES=[Ix.RATE_LIMIT_STATUS,Ix.SERVICE_UNAVAILABLE_STATUS,Ix.OVERLOADED_STATUS],Ix.BACKOFF_BASE_MS=1e3;let Lx=`default_api.`,Rx=/print\(\s*$/;var zx=class{constructor(e){this.src=e,this.pos=0}parse(){let e=this.src.indexOf(Lx);e===-1&&this.bail();let t=Rx.test(this.src.slice(0,e));this.pos=e;let n=this.parseCall();return this.skipWhitespace(),t&&(this.expect(`)`),this.skipWhitespace()),this.pos!==this.src.length&&this.bail(),n}parseCall(){this.expectLiteral(Lx);let e=this.readIdentifier();this.expect(`(`);let t=this.parseKwargs();return this.expect(`)`),{name:e,args:t}}parseKwargs(){let e={};for(;this.skipWhitespace(),this.peek()!==`)`;){let t=this.readIdentifier();this.skipWhitespace(),this.expect(`=`),this.skipWhitespace();let n=this.parseValue();Object.prototype.hasOwnProperty.call(e,t)&&this.bail(),e[t]=n,this.skipWhitespace();let r=this.peek();if(r===`,`){this.pos+=1;continue}if(r===`)`)break;this.bail()}return e}parseValue(){let e=this.peek();return e===`"`||e===`'`?this.readString():e===`-`||e===`+`||this.isDigit(e)?this.readNumber():/[A-Za-z]/.test(e)?this.readBareword():this.bail()}readString(){let e=this.src[this.pos];this.pos+=1;let t=``;for(;;){this.pos>=this.src.length&&this.bail();let n=this.src[this.pos];if(this.pos+=1,n===e)return t;if(n===`\\`){t+=this.readEscape();continue}t+=n}}readEscape(){this.pos>=this.src.length&&this.bail();let e=this.src[this.pos];switch(this.pos+=1,e){case`n`:return`
248
248
  `;case`t`:return` `;case`r`:return`\r`;case`b`:return`\b`;case`f`:return`\f`;case`\\`:return`\\`;case`"`:return`"`;case`'`:return`'`;case`/`:return`/`;case`u`:return this.readHexCodepoint(4);case`x`:return this.readHexCodepoint(2);default:return this.bail()}}readHexCodepoint(e){let t=this.src.slice(this.pos,this.pos+e);return(t.length!==e||!/^[0-9a-fA-F]+$/.test(t))&&this.bail(),this.pos+=e,String.fromCharCode(parseInt(t,16))}readNumber(){let e=this.pos;for((this.peek()===`-`||this.peek()===`+`)&&(this.pos+=1);this.pos<this.src.length&&/[0-9.eE+-]/.test(this.src[this.pos]);)this.pos+=1;let t=Number(this.src.slice(e,this.pos));return Number.isFinite(t)||this.bail(),t}readBareword(){switch(this.readIdentifier()){case`true`:case`True`:return!0;case`false`:case`False`:return!1;case`null`:case`None`:return null;default:return this.bail()}}readIdentifier(){let e=this.pos;for(/[A-Za-z_]/.test(this.peek())||this.bail();this.pos<this.src.length&&/[A-Za-z0-9_]/.test(this.src[this.pos]);)this.pos+=1;return this.src.slice(e,this.pos)}isDigit(e){return e>=`0`&&e<=`9`}peek(){return this.pos<this.src.length?this.src[this.pos]:``}skipWhitespace(){for(;this.pos<this.src.length&&/\s/.test(this.src[this.pos]);)this.pos+=1}expect(e){this.src[this.pos]!==e&&this.bail(),this.pos+=1}expectLiteral(e){this.src.slice(this.pos,this.pos+e.length)!==e&&this.bail(),this.pos+=e.length}bail(){throw Error(`MalformedFunctionCallParser: unexpected token`)}};function Bx(e,t){if(!e)return null;let n;try{n=new zx(e).parse()}catch{return null}return t.has(n.name)?n:null}let Vx=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,Hx={"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,"gemini-2.5-flash-lite":1048576,"gemini-3.8-flash":1048576,"gemini-3.5-flash":1048576,"gemini-3.1-flash-lite":1048576,"gemini-3.1-pro-preview":1048576};function Ux(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Wx(e){if(!yb.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${yb.join(`, `)}.`)}let Gx={"gemini-2.5-flash":`GeminiTransport: using gemini-2.5-flash — higher cost than flash-lite; use for harder reasoning or agent tasks.`,"gemini-2.5-pro":`GeminiTransport: using gemini-2.5-pro — significantly higher, prompt-size-tiered cost; reserve for tasks where flash reliability is insufficient.`,"gemini-3.5-flash":`GeminiTransport: using gemini-3.5-flash — frontier model, materially higher cost than flash-lite; use for harder reasoning or agent tasks.`,"gemini-3.8-flash":`GeminiTransport: using gemini-3.8-flash — frontier model, materially higher cost than flash-lite. Its $0.75/$3.75 per-MTok rate is introductory and DOUBLES to $1.50/$7.50 on 2027-01-01; re-check this tier choice before then.`,"gemini-3.1-pro-preview":`GeminiTransport: using gemini-3.1-pro-preview — PREVIEW model (no stability guarantee, may be withdrawn) with significantly higher, prompt-size-tiered cost; reserve for tasks where flash reliability is insufficient.`},Kx=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],qx=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],Jx=[`minimal`,`low`,`medium`,`high`],Yx={"gemini-3.8-flash":[`low`,`medium`,`high`],"gemini-3.5-flash":[`minimal`,`low`,`medium`,`high`],"gemini-3.1-flash-lite":[`minimal`,`low`,`medium`,`high`],"gemini-3.1-pro-preview":[`low`,`medium`,`high`]};function Xx(e,t){if(!e?.length||e.includes(t))return t;let n=Jx.indexOf(t),r=e=>Math.abs(Jx.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let Zx={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},Qx=e=>e!==void 0&&e!==`auto`&&e!==`off`;function $x(e,t){if(Qx(t)){let n=Yx[e];if(n)return{includeThoughts:!0,thinkingLevel:Xx(n,Zx[t])}}return t===`off`&&Kx.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&Kx.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let eS=`gemini`;function tS(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:xb(r.mimeType),data:Sb(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var nS=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},rS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!Kx.includes(this.model)){this.warnedThinkingClamped=!0,Zy.warn(`GeminiTransport: thinkingPolicy 'off' ignored — ${this.model} runs its default thinking posture and takes no budget we can safely set. Reasoning tokens are still billed at the candidate rate; use a flash tier if you need them gone.`);return}if(Qx(e)){let t=Yx[this.model];if(!t){this.warnedThinkingClamped=!0,Zy.warn(`GeminiTransport: thinkingPolicy '${e}' ignored — ${this.model} takes a numeric thinking budget, not the graded 'thinkingLevel' the Gemini 3 tiers use, so this turn runs at its default reasoning posture. Use a Gemini 3 tier to set reasoning depth.`);return}let n=Zx[e],r=Xx(t,n);r!==n&&(this.warnedThinkingClamped=!0,Zy.warn(`GeminiTransport: thinkingPolicy '${e}' sent as thinkingLevel '${r}' — ${this.model} does not accept '${n}' (it takes ${t.join(`/`)}). Reasoning bills at the candidate rate, so an upward clamp costs more than you asked for.`))}}}constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=!1;let t=e.model??`gemini-2.5-flash-lite`;Wx(t),this.model=t;let n=Gx[t];n&&Zy.warn(n),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint}getConfig(){return{provider:`gemini`,model:this.model,contextLimit:Hx[this.model]}}getLifetimeCost(){return this.lifetimeCostUsd}getLifetimeSavings(){return this.lifetimeSavingsUsd}resetLifetimeCost(){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0}sendStructuredPrompt(e){return J(this,void 0,void 0,function*(){let{systemPrompt:t,userPrompt:n,responseSchema:r}=e,i=[];return t&&(i.push({role:`user`,parts:[{text:t}]}),i.push({role:`model`,parts:[{text:`Understood.`}]})),i.push({role:`user`,parts:[{text:n}]}),(yield this.post({model:this.model,contents:i,responseSchema:r}))?.content??``})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=this.toGeminiContents(e,t,n?.attachments);n?.tailContext&&r.push({role:`user`,parts:[{text:n.tailContext}]});let i=n?.tools?.length?[{functionDeclarations:n.tools.map(e=>({name:e.name,description:e.description,parameters:Kb(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Ux(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:$x(this.model,n?.thinkingPolicy)};n?.maxTokens!=null&&(s.maxOutputTokens=n.maxTokens);let c=[...n?.attachments??[],...e.flatMap(e=>e.attachments??[]),...e.flatMap(e=>e.toolResult?.attachments??[])].find(e=>e.kind===`image`&&e.detail);c?.kind===`image`&&c.detail&&qx.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=wb(n.temperature,{defaultTemp:1,maxTemp:2}));let l=new Set((n?.tools??[]).map(e=>e.name)),u=this.model.startsWith(`gemini-3`),d=n?.responseSchema!=null&&(!i||u),f=yield this.post(Object.assign({model:this.model,contents:r,tools:i,systemInstruction:a,toolConfig:o,generationConfig:s},d?{responseSchema:Kb(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=jb(this.model,{promptTokens:t,candidateTokens:n,thoughtTokens:r,cachedTokens:i});this.lifetimeCostUsd+=a,this.lifetimeSavingsUsd+=o;let c=e.COST_DECIMAL_PLACES;return console.log(`--- Gemini Token Usage (${this.model}) ---`),console.log(`Prompt Tokens: ${t} (${i} cached) ($${s.promptUsd.toFixed(c)} + $${s.cacheReadUsd.toFixed(c)})`),console.log(`Candidate Tokens: ${n} (+${r} thinking) ($${s.candidateUsd.toFixed(c)})`),console.log(`Total Cost: $${a.toFixed(c)}`),console.log(`Cache Saved: $${o.toFixed(c)} (lifetime $${this.lifetimeSavingsUsd.toFixed(c)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(c)}`),console.log(`--------------------------`),a}toGeminiContents(e,t,n){let r=[],i=/* @__PURE__ */ new Map;for(let t of e){if(t.role===`system`||t.role===`system-event`||t.role===`synthetic-user`||t.role===`compacted-summary`||t.category===`reasoning`||t.category===`narration`||t.excludeFromProvider||t.thinking)continue;let e=t.role===`user`?`user`:`model`;if(t.toolResult){let e=i.get(t.toolResult.toolCallId)??t.toolResult.toolCallId;r.push({role:`user`,parts:[{functionResponse:{name:e,response:{content:t.toolResult.content}}}]});let n=t.toolResult.attachments??[];n.length&&r.push({role:`user`,parts:n.map(e=>({inlineData:{mimeType:xb(e.mimeType),data:e.data}}))})}else if(t.toolCalls?.length){for(let e of t.toolCalls)i.set(e.id,e.name);r.push({role:`model`,parts:t.toolCalls.map((e,t)=>{let n={functionCall:{name:e.name,args:e.args}},r=e.providerMetadata?.[eS],i=r?.model===this.model?r.thoughtSignature:void 0;return i?n.thoughtSignature=i:t===0&&(n.thoughtSignature=`skip_thought_signature_validator`),n})})}else if(e===`user`&&t.attachments?.length){let{imageParts:e,textParts:n}=tS(t.attachments);r.push({role:`user`,parts:[...e,...t.content?[{text:t.content}]:[],...n]})}else r.push({role:e,parts:[{text:t.content}]})}let{imageParts:a,textParts:o}=tS(n??[]);return(t||a.length||o.length)&&r.push({role:`user`,parts:[...a,...t?[{text:t}]:[],...o]}),r}usageFromGemini(e){if(!e)return{};let t=e,n=this.logTokenUsage(t.promptTokenCount??0,t.candidatesTokenCount??0,t.thoughtsTokenCount??0,t.cachedContentTokenCount??0);return{inputTokens:t.promptTokenCount,outputTokens:t.candidatesTokenCount!=null||t.thoughtsTokenCount!=null?(t.candidatesTokenCount??0)+(t.thoughtsTokenCount??0):void 0,thoughtsTokens:t.thoughtsTokenCount,cacheReadTokens:t.cachedContentTokenCount,cost:n}}fromGeminiResponse(e,t=/* @__PURE__ */ new Set,n){let{inputTokens:r,outputTokens:i,thoughtsTokens:a,cacheReadTokens:o,cost:s}=this.usageFromGemini(e.usageMetadata),c=e?.candidates?.[0],l=c?.content?.parts??[],u=[],d=[],f=[];for(let e of l)if(e.functionCall){let t={model:this.model};e.thoughtSignature&&(t.thoughtSignature=e.thoughtSignature),u.push({id:crypto.randomUUID(),name:e.functionCall.name,args:e.functionCall.args??{},providerMetadata:{[eS]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=Bx(c.finishMessage,t);if(!e)throw new nS(c.finishMessage);u.push({id:crypto.randomUUID(),name:e.name,args:e.args})}let p=d.join(``),m=f.join(``),h=u.length>0?{role:`assistant`,content:m,reasoning:p||void 0,toolCalls:u}:{role:`assistant`,content:m,reasoning:p||void 0},g=c?.finishReason;(u.length===0&&!p&&!m||g&&g!==`STOP`&&g!==`MALFORMED_FUNCTION_CALL`)&&this.logAbnormalResponse(e,{finishReason:g,functionCallParts:u.length,thoughtParts:d.length,textParts:f.length}),this.guardMaxTokensTruncation(g,u,m,i,n),r!=null&&(h.inputTokens=r),i!=null&&(h.outputTokens=i),o!=null&&(h.cacheReadTokens=o),s!=null&&(h.cost=s);let _=e.promptFeedback?.blockReason;return(g!=null||a!=null||_!=null)&&(h.responseMeta={finishReason:g,thoughtsTokens:a,parts:{functionCall:u.length,thought:d.length,text:f.length},blockReason:_}),h}guardMaxTokensTruncation(e,t,n,r,i){if(e===`MAX_TOKENS`&&(t.length!==0||n.trim()===``))throw new Fx(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};Zy.warn(`GeminiTransport: blank/non-STOP response`,{model:this.model,finishReason:t.finishReason,finishMessage:r.finishMessage,parts:{total:t.functionCallParts+t.thoughtParts+t.textParts,functionCall:t.functionCallParts,thought:t.thoughtParts,text:t.textParts},usage:{promptTokenCount:n.promptTokenCount,candidatesTokenCount:n.candidatesTokenCount,thoughtsTokenCount:n.thoughtsTokenCount,totalTokenCount:n.totalTokenCount},promptFeedback:e.promptFeedback,safetyRatings:r.safetyRatings,citationMetadata:r.citationMetadata})}buildEndpoint(e){if(this.apiKey)return{url:`${Vx(this.model)}?key=${this.apiKey}`,payload:this.toDirectPayload(e),headers:{"Content-Type":`application/json`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`GeminiTransport: no API key or server endpoint configured. Set GEMINI_API_KEY in your .env or pass apiKey/serverEndpoint in GeminiAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield xx({url:r,headers:a,body:i,credentials:o,vendorLabel:tb.gemini,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}toDirectPayload(e){let t=Object.assign({},e);return delete t.model,t.responseSchema&&(t.generationConfig=Object.assign(Object.assign({},t.generationConfig),{responseMimeType:`application/json`,responseSchema:t.responseSchema}),delete t.responseSchema),t}};rS.TOKENS_PER_MILLION=1e6,rS.COST_DECIMAL_PLACES=6,rS.RATE_LIMIT_STATUS=429,rS.SERVICE_UNAVAILABLE_STATUS=503,rS.BAD_GATEWAY_STATUS=502,rS.RETRYABLE_STATUSES=[rS.RATE_LIMIT_STATUS,rS.SERVICE_UNAVAILABLE_STATUS,rS.BAD_GATEWAY_STATUS],rS.BACKOFF_BASE_MS=1e3;var iS=class e{constructor(){this.noopProvider=new eb}get(t){return t===e.DEFAULT_NAME?this.noopProvider:void 0}default(){return this.noopProvider}defaultName(){return e.DEFAULT_NAME}names(){return[e.DEFAULT_NAME]}getStatus(t){return J(this,void 0,void 0,function*(){var n;return t!==void 0&&t!==e.DEFAULT_NAME?null:(yield(n=this.noopProvider).getStatus?.call(n))??null})}listStatuses(){return J(this,void 0,void 0,function*(){var t;let n=(yield(t=this.noopProvider).getStatus?.call(t))??null;return[{name:e.DEFAULT_NAME,isDefault:!0,status:n}]})}};iS.DEFAULT_NAME=`default`;let aS=N.createInterface(e=>e.singleton(iS)),oS=6e4,sS=3e5;Object.freeze({anthropic:Object.freeze({low:Object.freeze({model:`claude-haiku-4-5-20251001`,maxTokens:16e3,stallTimeoutMs:oS,timeoutMs:sS}),high:Object.freeze({model:`claude-sonnet-5`,maxTokens:128e3,stallTimeoutMs:oS,timeoutMs:sS}),reasoning:Object.freeze({model:`claude-opus-4-8`,maxTokens:32e3,stallTimeoutMs:oS,timeoutMs:sS})}),gemini:Object.freeze({low:Object.freeze({model:`gemini-3.1-flash-lite`,stallTimeoutMs:oS,timeoutMs:sS}),high:Object.freeze({model:`gemini-3.8-flash`,stallTimeoutMs:oS,timeoutMs:sS}),reasoning:Object.freeze({model:`gemini-3.1-pro-preview`,stallTimeoutMs:oS,timeoutMs:sS})})});let cS=O` :host{display: block;width: 800px}.ai-criteria-search{display: flex;flex-direction: column;gap: calc(${B} * 2px)}.ai-criteria-search-row{display: flex;flex-direction: row;gap: calc(${B} * 2px);align-items: center}.criteria-input{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0}.criteria-chips-inline{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0;display: flex;align-items: center;gap: calc(${B} * 1px);overflow-x: auto;padding: 0 calc(${B} * 2px);background: var(--neutral-fill-input-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(var(--control-corner-radius) * 1px);scrollbar-width: none}.criteria-chips-inline::-webkit-scrollbar{display: none}.mic-icon{color: var(--neutral-foreground-rest);fill: currentColor}.criteria-toggle-button, .criteria-clear-button{flex-shrink: 0}.criteria-chip{display: inline-flex;align-items: center;flex-shrink: 0;gap: calc(${B} * 1px);padding: calc(${B} * 0.5px) calc(${B} * 2px);background: var(--neutral-fill-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(${B} * 4px);font-size: var(--type-ramp-minus-1-font-size);color: var(--neutral-foreground-rest);white-space: nowrap}.criteria-chip-field{font-weight: 600}.criteria-chip-operator{color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-style: italic}.criteria-chip-remove{display: inline-flex;align-items: center;justify-content: center;width: 14px;height: 14px;padding: 0;margin-left: calc(${B} * 0.5px);background: none;border: none;cursor: pointer;color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-size: 10px;border-radius: 50%;line-height: 1}.criteria-chip-remove:hover{background: var(--neutral-fill-hover);color: var(--neutral-foreground-rest)}`,lS=e=>T` ${A(()=>Xy(),T`<div class="ai-criteria-search"><div class="ai-criteria-search-row">${A(e=>!e.showingChips,T`<${e}-text-area ${k(`textAreaRef`)}class="criteria-input" placeholder="${e=>e.placeholder}" ?disabled=${e=>e.disabled||e.isInterpreting}:value=${wf(e=>e.inputValue,`string`,`input`)}@blur=${e=>e.handleBlur()}rows="1"></${e}-text-area>`)} ${A(e=>e.showingChips,T`<div class="criteria-chips-inline">${j(e=>e.criteriaChips,T`<span class="criteria-chip"><span class="criteria-chip-field">${e=>e.fieldLabel}</span><span class="criteria-chip-operator">${e=>e.operatorLabel}</span>${A(e=>!!e.valueLabel,T`<span class="criteria-chip-value">${e=>e.valueLabel}</span>`)}<button class="criteria-chip-remove" aria-label="Remove filter" @click=${(e,t)=>t.parent.removeChip(e.groupIndex,e.clauseIndex)}>
@@ -265,7 +265,7 @@ function uv(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r
265
265
  </svg>
266
266
  `,indeterminateIndicator:`
267
267
  <div part="indeterminate-indicator" class="indeterminate-indicator"></div>
268
- `};ow.compose(Object.assign({baseName:`checkbox`,template:iw,styles:aw,shadowOptions:void 0},sw));let cw=(e,t)=>O` .combo-box-indicator{transition-property: transform;transition-duration: 0.2s;transition-timing-function: ease-out}:host([open]) .combo-box-indicator{transform: rotate(180deg)}${du(e,t)}`,lw=(e,t)=>T`<template aria-activedescendant="${e=>e.activeDescendant}" class="${e=>e.open?`open`:``} ${e=>e.disabled?`disabled`:``} ${e=>e.position}" ?open="${e=>e.open}" @click="${(e,t)=>e.clickHandler(t.event)}" @focusout="${(e,t)=>e.focusoutHandler(t.event)}" @keydown="${(e,t)=>e.keydownHandler(t.event)}"><div class="control" part="control">${Et(e,t)}<slot name="control"><input aria-activedescendant="${e=>e.activeDescendant}" aria-autocomplete="${e=>e.ariaAutoComplete||e.autocomplete}" aria-controls="${e=>e.ariaControls||e.listboxId}" aria-disabled="${e=>e.disabled?`true`:`false`}" aria-expanded="${e=>e.open?`true`:`false`}" aria-haspopup="listbox" aria-labelledby="${e=>e.ariaLabelledby}" aria-label="${e=>e.ariaLabel}" autocomplete="${e=>e.autocomplete}" class="selected-value" part="selected-value" placeholder="${e=>e.placeholder}" role="combobox" type="text" ?disabled="${e=>e.disabled}" :value="${e=>e.value}" @input="${(e,t)=>e.inputHandler(t.event)}" @keyup="${(e,t)=>e.keyupHandler(t.event)}" ${k(`control`)}/><div class="indicator" part="indicator" aria-hidden="true"><slot name="indicator">${t.indicator||``}</slot></div></slot>${Tt(e,t)}</div><div class="listbox" id="${e=>e.listboxId}" part="listbox" role="listbox" ?disabled="${e=>e.disabled}" ?hidden="${e=>!e.open}" ${k(`listbox`)}><slot ${k(`slottedDatasource`)} ${St({filter:Vr.slottedOptionFilter,flatten:!0,property:`slottedOptions`})}></slot></div></template>`;var uw,dw,fw=class extends fu{constructor(){super(...arguments),uw.set(this,void 0),dw.set(this,!1),this.needManualChangeEventDispatch=!1,this.async=!1,this.debounce=500,this.caseSensitive=!1,this.ignoreInputClick=!1,this.filterMode=`startsWith`,this.scrollToSelectedWhenOpening=!1,this.scrollToSelectedWhenOpeningOptions={behavior:`auto`,block:`nearest`},this.scrollWhenSelectionChanges=!1,this.scrollWhenSelectionChangesOptions={behavior:`auto`,block:`center`},this.resetCombobox=()=>{this.selectedOptions=[],this.selectedIndex=-1,this.value=``,this.control.value=``,this.filter=``,this.filterOptions()}}get activeDescendant(){if(this.selectedOptions&&this.selectedOptions.length!==0)return this.ariaActiveDescendant=this.selectedOptions[0]?.id,this.selectedOptions[0]?.id}debounceChanged(e,t){this.debouncedInputHandler=(0,KC.default)(this.asyncSetFilter,t)}get scrollableListbox(){return this.listbox??this.shadowRoot?.querySelector(`.listbox`)}openChanged(){super.openChanged(),this.$emit(`open-change`,{open:this.open}),this.open?this.scrollToSelectedWhenOpening&&setTimeout(()=>{this.options[this.selectedIndex]?.scrollIntoView(this.scrollToSelectedWhenOpeningOptions)},500):(this.manuallyDispatchChangeEvent(),this.filter=``,this.filterOptions())}get value(){return S.track(this,`value`),this._ourValue}set value(e){if(e===void 0)return;let t=`${this._ourValue}`;if(this.$fastController.isConnected&&this.options){let t=this.caseSensitive?t=>t.text===e:t=>t.text.toLowerCase()===String(e).toLowerCase(),n=this.options?this.options.findIndex(t):-1,r=this.options[this.selectedIndex]?.text,i=this.options[n]?.text;this.selectedIndex=i&&i!==r?n:this.selectedIndex,e&&e.trim()!==``&&n===-1&&(e=this.firstSelectedOption?.text||e)}t!==e&&(this._ourValue=e,super.valueChanged(t,e),S.notify(this,`value`))}slottedOptionsChanged(e,t){this.enableAsyncForInfiniteScrollDatasource(),super.slottedOptionsChanged(e,t),this.updateValue(!1)}enableAsyncForInfiniteScrollDatasource(){this.async||this.slottedDatasource?.assignedNodes().find(e=>e instanceof YC)?.infiniteScroll&&(this.async=!0)}filterOptions(){if(this.async){this.filteredOptions=[...this._options],this._options.forEach(e=>e.hidden=!1);return}(!this.autocomplete||this.autocomplete===Wr.none)&&(this.filter=``);let e=this.filter,t=this.caseSensitive?e:e.toLowerCase(),n=e=>{let n=this.caseSensitive?e.text:e.text.toLowerCase();return this.filterMode===`contains`?n.includes(t):n.startsWith(t)};this.filteredOptions=this._options.filter(n),this.isAutocompleteList&&(!this.filteredOptions.length&&!t&&(this.filteredOptions=this._options),this._options.forEach(e=>e.hidden=!this.filteredOptions.includes(e)))}clickHandler(e){if(!this.disabled){if(Cy(e,this)){this.open=!1;return}if(wy(e,this.indicator)){this.open=!this.open,this.open&&this.control.focus();return}if(!(this.ignoreInputClick&&wy(e,this.control)))return super.clickHandler(e)}}keydownHandler(e){let t=e.key;if(e.ctrlKey||e.shiftKey)return!0;switch(t){case`Enter`:if(wd(this,dw,this.open,`f`),!this.open)return this.open=!0,!0;break;case`ArrowDown`:case`ArrowUp`:if(!this.open)return this.open=!0,!0;this.scrollWhenSelectionChanges&&this.options[this.selectedIndex]?.scrollIntoView(this.scrollWhenSelectionChangesOptions);break;case`Escape`:if(this.control.value!==this.currentValue){this.filter=``,this.filterOptions(),this.control.value=this.currentValue,this.selectItemByValue(this.currentValue),this.open=!1;return}if(!this.open)return!0}let n=super.keydownHandler(e);if(t!==`Enter`)return n}keyupHandler(e){let t=e.key;if(e.ctrlKey||e.shiftKey)return!0;switch(t){case`Enter`:return!Cd(this,dw,`f`);case`ArrowDown`:case`ArrowUp`:this.open&&this.firstSelectedOption&&this.autocomplete===Wr.both&&(this.needManualChangeEventDispatch=!0,this.currentValue=this.firstSelectedOption?.value);break;case`Home`:case`End`:return;case`Backspace`:case`Delete`:let t=super.keyupHandler(e);return this.selectItemByValue(this.control.value),t}return super.keyupHandler(e)}get indicator(){return Cd(this,uw,`f`)||wd(this,uw,this.shadowRoot.querySelector(`[part="indicator"]`),`f`),Cd(this,uw,`f`)}selectItemByValue(e){var t;this.selectedIndex=this.options?.findIndex(t=>t.text===e)??-1,(t=this.options)==null||t.forEach((e,t)=>e.selected=t===this.selectedIndex)}inputHandler(e){this.async?(this.selectedIndex=this.options.map(e=>e.text).indexOf(this.control.value),this.debouncedInputHandler()):super.inputHandler(e)}asyncSetFilter(){let e=this.control.value,t=this.slottedDatasource.assignedNodes().filter(e=>e instanceof YC);if(t.length>0){let n=t[0];e==null||e===``?n.criteria=n.baseCriteria||``:By(n,e),x.queueUpdate(()=>{this.control.value=e})}else xy.warn(`Options-datasource is not connected. Please add a datasource to use this functionality.`)}manuallyDispatchChangeEvent(){this.needManualChangeEventDispatch&&this.firstSelectedOption&&this.autocomplete===Wr.both&&(this.dispatchEvent(new Event(`change`,{bubbles:!0})),this.needManualChangeEventDispatch=!1)}};uw=/* @__PURE__ */ new WeakMap,dw=/* @__PURE__ */ new WeakMap,q([C],fw.prototype,`activeDescendant`,null),q([C],fw.prototype,`slottedDatasource`,void 0),q([D({mode:`boolean`})],fw.prototype,`async`,void 0),q([D],fw.prototype,`debounce`,void 0),q([D({mode:`boolean`,attribute:`case-sensitive`})],fw.prototype,`caseSensitive`,void 0),q([D({mode:`boolean`,attribute:`ignore-input-click`})],fw.prototype,`ignoreInputClick`,void 0),q([D({attribute:`filter-mode`})],fw.prototype,`filterMode`,void 0),q([D({mode:`boolean`,attribute:`scroll-to-selected-when-opening`})],fw.prototype,`scrollToSelectedWhenOpening`,void 0),q([C],fw.prototype,`scrollToSelectedWhenOpeningOptions`,void 0),q([D({mode:`boolean`,attribute:`scroll-when-selection-changes`})],fw.prototype,`scrollWhenSelectionChanges`,void 0),q([C],fw.prototype,`scrollWhenSelectionChangesOptions`,void 0);let pw={delegatesFocus:!0,mode:`open`},mw={indicator:`
268
+ `};ow.compose(Object.assign({baseName:`checkbox`,template:iw,styles:aw,shadowOptions:void 0},sw));let cw=(e,t)=>O` .combo-box-indicator{transition-property: transform;transition-duration: 0.2s;transition-timing-function: ease-out}:host([open]) .combo-box-indicator{transform: rotate(180deg)}${du(e,t)}`,lw=(e,t)=>T`<template aria-activedescendant="${e=>e.activeDescendant}" class="${e=>e.open?`open`:``} ${e=>e.disabled?`disabled`:``} ${e=>e.position}" ?open="${e=>e.open}" @click="${(e,t)=>e.clickHandler(t.event)}" @focusout="${(e,t)=>e.focusoutHandler(t.event)}" @keydown="${(e,t)=>e.keydownHandler(t.event)}"><div class="control" part="control">${Et(e,t)}<slot name="control"><input aria-activedescendant="${e=>e.activeDescendant}" aria-autocomplete="${e=>e.ariaAutoComplete||e.autocomplete}" aria-controls="${e=>e.ariaControls||e.listboxId}" aria-disabled="${e=>e.disabled?`true`:`false`}" aria-expanded="${e=>e.open?`true`:`false`}" aria-haspopup="listbox" aria-labelledby="${e=>e.ariaLabelledby}" aria-label="${e=>e.ariaLabel}" autocomplete="${e=>e.autocomplete}" class="selected-value" part="selected-value" placeholder="${e=>e.placeholder}" role="combobox" type="text" ?disabled="${e=>e.disabled}" :value="${e=>e.value}" @input="${(e,t)=>e.inputHandler(t.event)}" @keyup="${(e,t)=>e.keyupHandler(t.event)}" ${k(`control`)}/><div class="indicator" part="indicator" aria-hidden="true"><slot name="indicator">${t.indicator||``}</slot></div></slot>${Tt(e,t)}</div><div class="listbox" id="${e=>e.listboxId}" part="listbox" role="listbox" ?disabled="${e=>e.disabled}" ?hidden="${e=>!e.open}" ${k(`listbox`)}><slot ${k(`slottedDatasource`)} ${St({filter:Vr.slottedOptionFilter,flatten:!0,property:`slottedOptions`})}></slot></div></template>`;var uw,dw,fw=class extends fu{constructor(){super(...arguments),uw.set(this,void 0),dw.set(this,!1),this.needManualChangeEventDispatch=!1,this.async=!1,this.debounce=500,this.caseSensitive=!1,this.ignoreInputClick=!1,this.filterMode=`startsWith`,this.scrollToSelectedWhenOpening=!1,this.scrollToSelectedWhenOpeningOptions={behavior:`auto`,block:`nearest`},this.scrollWhenSelectionChanges=!1,this.scrollWhenSelectionChangesOptions={behavior:`auto`,block:`center`},this.resetCombobox=()=>{this.selectedOptions=[],this.selectedIndex=-1,this.value=``,this.control.value=``,this.filter=``,this.filterOptions()}}get activeDescendant(){if(this.selectedOptions&&this.selectedOptions.length!==0)return this.ariaActiveDescendant=this.selectedOptions[0]?.id,this.selectedOptions[0]?.id}debounceChanged(e,t){this.debouncedInputHandler=(0,KC.default)(this.asyncSetFilter,t)}get scrollableListbox(){return this.listbox??this.shadowRoot?.querySelector(`.listbox`)}openChanged(){super.openChanged(),this.$emit(`open-change`,{open:this.open}),this.open?this.scrollToSelectedWhenOpening&&setTimeout(()=>{this.options[this.selectedIndex]?.scrollIntoView(this.scrollToSelectedWhenOpeningOptions)},500):(this.manuallyDispatchChangeEvent(),this.filter=``,this.filterOptions())}get value(){return S.track(this,`value`),this._ourValue}set value(e){if(e===void 0)return;let t=`${this._ourValue}`;if(this.$fastController.isConnected&&this.options){let t=this.caseSensitive?t=>t.text===e:t=>t.text.toLowerCase()===String(e).toLowerCase(),n=this.options?this.options.findIndex(t):-1,r=this.options[this.selectedIndex]?.text,i=this.options[n]?.text;this.selectedIndex=i&&i!==r?n:this.selectedIndex,e&&e.trim()!==``&&n===-1&&(e=this.firstSelectedOption?.text||e)}t!==e&&(this._ourValue=e,super.valueChanged(t,e),S.notify(this,`value`))}slottedOptionsChanged(e,t){this.enableAsyncForInfiniteScrollDatasource(),super.slottedOptionsChanged(e,t),this.updateValue(!1)}enableAsyncForInfiniteScrollDatasource(){this.async||this.slottedDatasource?.assignedNodes().find(e=>e instanceof YC)?.infiniteScroll&&(this.async=!0)}get options(){return this.async?(S.track(this,`options`),this._options):super.options}set options(e){super.options=e}filterOptions(){if(this.async){this.filteredOptions=[...this._options],this._options.forEach(e=>e.hidden=!1);return}(!this.autocomplete||this.autocomplete===Wr.none)&&(this.filter=``);let e=this.filter,t=this.caseSensitive?e:e.toLowerCase(),n=e=>{let n=this.caseSensitive?e.text:e.text.toLowerCase();return this.filterMode===`contains`?n.includes(t):n.startsWith(t)};this.filteredOptions=this._options.filter(n),this.isAutocompleteList&&(!this.filteredOptions.length&&!t&&(this.filteredOptions=this._options),this._options.forEach(e=>e.hidden=!this.filteredOptions.includes(e)))}clickHandler(e){if(!this.disabled){if(Cy(e,this)){this.open=!1;return}if(wy(e,this.indicator)){this.open=!this.open,this.open&&this.control.focus();return}if(!(this.ignoreInputClick&&wy(e,this.control)))return super.clickHandler(e)}}keydownHandler(e){let t=e.key;if(e.ctrlKey||e.shiftKey)return!0;switch(t){case`Enter`:if(wd(this,dw,this.open,`f`),!this.open)return this.open=!0,!0;break;case`ArrowDown`:case`ArrowUp`:if(!this.open)return this.open=!0,!0;this.scrollWhenSelectionChanges&&this.options[this.selectedIndex]?.scrollIntoView(this.scrollWhenSelectionChangesOptions);break;case`Escape`:if(this.control.value!==this.currentValue){this.filter=``,this.filterOptions(),this.control.value=this.currentValue,this.selectItemByValue(this.currentValue),this.open=!1;return}if(!this.open)return!0}let n=super.keydownHandler(e);if(t!==`Enter`)return n}keyupHandler(e){let t=e.key;if(e.ctrlKey||e.shiftKey)return!0;switch(t){case`Enter`:return!Cd(this,dw,`f`);case`ArrowDown`:case`ArrowUp`:this.open&&this.firstSelectedOption&&this.autocomplete===Wr.both&&(this.needManualChangeEventDispatch=!0,this.currentValue=this.firstSelectedOption?.value);break;case`Home`:case`End`:return;case`Backspace`:case`Delete`:let t=super.keyupHandler(e);return this.selectItemByValue(this.control.value),t}return super.keyupHandler(e)}get indicator(){return Cd(this,uw,`f`)||wd(this,uw,this.shadowRoot.querySelector(`[part="indicator"]`),`f`),Cd(this,uw,`f`)}selectItemByValue(e){var t;this.selectedIndex=this.options?.findIndex(t=>t.text===e)??-1,(t=this.options)==null||t.forEach((e,t)=>e.selected=t===this.selectedIndex)}inputHandler(e){this.async?(this.selectedIndex=this.options.map(e=>e.text).indexOf(this.control.value),this.debouncedInputHandler()):super.inputHandler(e)}asyncSetFilter(){let e=this.control.value,t=this.slottedDatasource.assignedNodes().filter(e=>e instanceof YC);if(t.length>0){let n=t[0];e==null||e===``?n.criteria=n.baseCriteria||``:By(n,e),x.queueUpdate(()=>{this.control.value=e})}else xy.warn(`Options-datasource is not connected. Please add a datasource to use this functionality.`)}manuallyDispatchChangeEvent(){this.needManualChangeEventDispatch&&this.firstSelectedOption&&this.autocomplete===Wr.both&&(this.dispatchEvent(new Event(`change`,{bubbles:!0})),this.needManualChangeEventDispatch=!1)}};uw=/* @__PURE__ */ new WeakMap,dw=/* @__PURE__ */ new WeakMap,q([C],fw.prototype,`activeDescendant`,null),q([C],fw.prototype,`slottedDatasource`,void 0),q([D({mode:`boolean`})],fw.prototype,`async`,void 0),q([D],fw.prototype,`debounce`,void 0),q([D({mode:`boolean`,attribute:`case-sensitive`})],fw.prototype,`caseSensitive`,void 0),q([D({mode:`boolean`,attribute:`ignore-input-click`})],fw.prototype,`ignoreInputClick`,void 0),q([D({attribute:`filter-mode`})],fw.prototype,`filterMode`,void 0),q([D({mode:`boolean`,attribute:`scroll-to-selected-when-opening`})],fw.prototype,`scrollToSelectedWhenOpening`,void 0),q([C],fw.prototype,`scrollToSelectedWhenOpeningOptions`,void 0),q([D({mode:`boolean`,attribute:`scroll-when-selection-changes`})],fw.prototype,`scrollWhenSelectionChanges`,void 0),q([C],fw.prototype,`scrollWhenSelectionChangesOptions`,void 0);let pw={delegatesFocus:!0,mode:`open`},mw={indicator:`
269
269
  <svg
270
270
  class="combo-box-indicator"
271
271
  part="combo-box-indicator"