@genesislcap/foundation-rapid-cdn 15.50.1 → 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}`}},Ag;(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`})(Ag||(Ag={}));var jg;(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`})(jg||(jg={}));var Mg;(function(e){e.SESSION_NOT_FOUND=`SESSION_NOT_FOUND`,e.UNKNOWN_MESSAGE_TYPE=`UNKNOWN_MESSAGE_TYPE`})(Mg||(Mg={}));let Ng=e=>Array.isArray(e)?e.map(Ng):e&&typeof e==`object`&&e.constructor===Object?Object.keys(e).sort().reduce((t,n)=>(t[n]=Ng(e[n]),t),{}):e;function Pg(e,t){return`${e}::${JSON.stringify(Ng(t??{}))}`}let Fg=(e,t)=>Array.isArray(e?.ERROR)?e?.ERROR.some(e=>e.CODE?.includes(`${t}`)||e.STATUS_CODE?.includes(`${t}`)):!1,Ig=class{constructor(e,t){this.session=e,this.uuid=t}createLoginMessage(e){let t;switch(e.type){case Og.BASIC:t={USER_NAME:e.username,PASSWORD:e.password,MFA_CODE:e.mfaToken};break;case Og.REFRESH:t={USER_NAME:e.username,REFRESH_AUTH_TOKEN:e.refreshToken,MFA_CODE:e.mfaToken};break;case Og.SSO:t={SSO_TOKEN:e.ssoToken};break;case Og.JWT:t={JWT:e.jwt,DOMAIN:e.domain}}return{DETAILS:t,SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:jg.EVENT_LOGIN_AUTH}}createLogoutMessage(e){return{SOURCE_REF:this.uuid.createId(),MESSAGE_TYPE:jg.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:jg.DATA_LOGON,DETAILS:Object.assign({DATASOURCE_NAME:e},t),SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}createDataLogoffMessage(e){return{SOURCE_REF:e,MESSAGE_TYPE:jg.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:jg.RESOURCES_REQUEST},e)}createMetaRequestMessage(e,t=jg.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:jg.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:jg.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:jg.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:jg.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:Ag.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:Ag.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===jg.EVENT_LOGOUT&&(n[`SESSION-ID`]=e.SESSION_ID),n}createHeartbeatPingMessage(e=!1){return{MESSAGE_TYPE:Ag.HEARTBEAT_PING,SOURCE_REF:this.uuid.createId(),VERBOSE:e,DETAILS:{},SESSION_AUTH_TOKEN:this.session.getSessionStorageItem(`authToken`)}}};Ig=q([_d(0,Tg),_d(1,lg)],Ig);let Lg=N.createInterface(e=>e.singleton(Ig));var Rg;let zg=Rg=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(Rg.getUrl(e,t),{body:Rg.getBody(t),headers:this.messageBuilder.createHTTPHeadersFromMessage(t)})}get(e,t){return this.http.get(Rg.getUrl(e,t),{headers:this.messageBuilder.createHTTPHeadersFromMessage(t)})}requestServer(e,t){let n=Rg.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===jg.DATA_LOGON&&(r=t.DETAILS.DATASOURCE_NAME.replace(/_/g,`-`).toLowerCase()),`${e}${r}`}};zg=Rg=q([_d(0,Dg),_d(1,Lg)],zg);let Bg=N.createInterface(e=>e.singleton(zg));function Vg(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 Hg=class{constructor(e){this.path=e}};let Ug=/* @__PURE__ */ new Set,Wg=Object.freeze({register(e){Ug.add(e)},unregister(e){Ug.delete(e)}}),Gg=/^([a-z][a-z0-9+\-.]*:)?\/\//i,Kg=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:s_.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&&Gg.test(e)){location.href=e;return}history.pushState({},document.title,e),t&&Kg.path.trigger(e)},replace(e,t=!0){if(e&&Gg.test(e)){location.href=e;return}history.replaceState({},document.title,e),t&&Kg.path.trigger(e)},trigger(e){let t=new Hg(e);for(let e of Ug)e.enqueue(t)}}),name:Object.freeze({generateRoute(e,t,n={}){return J(this,void 0,void 0,function*(){let r=`config`in e?e:s_.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 Kg.name.generateRoute(e,t,n);i!==null&&Kg.path.push(i,r)})},replace(e,t,n={},r=!0){return J(this,void 0,void 0,function*(){let i=yield Kg.name.generateRoute(e,t,n);i!==null&&Kg.path.replace(i,r)})},trigger(e,t,n={}){return J(this,void 0,void 0,function*(){let r=yield Kg.name.generateRoute(e,t,n);r!==null&&Kg.path.trigger(r)})}})});var Fie=class{constructor(){this.queue=[],this.promise=null,this.resolve=null}connect(){this.enqueue(new Hg(Kg.path.current)),window.addEventListener(`popstate`,this),Wg.register(this)}disconnect(){this.queue=[],this.promise=null,this.resolve=null,window.removeEventListener(`popstate`,this),Wg.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 Hg(Kg.path.current))}};let qg=encodeURIComponent,Jg=e=>qg(e).replace(`%24`,`$`);function Yg(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(`${Jg(e)}=${qg(t[i])}`);else{let n=e+`[`+(typeof t[i]==`object`&&t[i]!==null?i:``)+`]`;r=r.concat(Yg(n,t[i]))}else if(typeof t==`object`&&!n)for(let n in t)r=r.concat(Yg(e+`[`+n+`]`,t[n]));else r.push(`${Jg(e)}=${qg(t)}`);return r}function Iie(e,t){return Array.isArray(e)?(e.push(t),e):e===void 0?t:[e,t]}function Lie(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 Xg=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(Yg(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?Lie(t,a,e):t[i]=Iie(t[i],e)}else t[i]=!0}return t}}),Rie=e=>e;var Zg=class{constructor(e,t,n){this.path=e,this.name=t,this.caseSensitive=n}},Qg=class{constructor(e,t,n,r){this.route=e,this.paramNames=t,this.paramTypes=n,this.settings=r}get path(){return this.route.path}},$g=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}},zie=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 Bie(e){return e.head.endpoint!==null}function Vie(e,t){return e.compareTo(t)}var Hie=class{constructor(e){this.candidates=[],this.candidates=[new zie([``],[e],[],this)]}get isEmpty(){return this.candidates.length===0}getSolution(){let e=this.candidates.filter(Bie);if(e.length===0)return null;for(let t of e)t.finalize();return e.sort(Vie),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)}},Uie=class{constructor(){this.names=/* @__PURE__ */ new Map,this.paths=/* @__PURE__ */ new Map,this.rootState=new Wie(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 Zg(e.path,e.name||``,e.caseSensitive===!0),i=n===``?[``]:n.split(`/`).filter(Gie),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 e_(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 qie(t);c.push(n),s=n.appendTo(s);break}default:{let t=new Kie(e,r.caseSensitive);c.push(t),s=t.appendTo(s);break}}let l=new Qg(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=Xg.separate(e),r=Xg.parse(n.queryString);e=decodeURI(n.path),e.startsWith(`/`)||(e=`/${e}`),e.length>1&&e.endsWith(`/`)&&(e=e.slice(0,-1));let i=new Hie(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]]||Rie,i=l[n];u[n]=yield r(i)}return new $g(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 e_&&!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=Xg.build(n);return i+=a?`?${a}`:``,i}},Wie=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 Gie(e){return e.length>0}var Kie=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}},e_=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}},qie=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 t_=`fast-child-route`;function n_(e,t){return`command`in t?t.command:`redirect`in t?new f_(t.redirect):g_.fromDefinition(e,t)}let r_=e=>{if(e==null)return!1;switch(e.toLowerCase().trim()){case`true`:case`yes`:case`1`:return!0;default:return!1}},Jie={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:r_,bool:r_};var i_=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 rae),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 f_(t.redirect):g_.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+`/*${t_}`});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 n_(t,i).createContributor(n,r)})}}:n_(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=Xg.separate(e),n=Xg.parse(t.queryString);return{route:new $g(new Qg(new Zg(`*`,``,!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({},Jie),this.converters):Object.assign(Object.assign({},this.owner.parent.routes.aggregateConverters()),this.converters)}};let a_=`$router`;function Yie(e){let t=e.parentElement;if(t)return t;{let t=e.getRootNode();if(t.host instanceof HTMLElement)return t.host}return null}function o_(e){let t=e;for(;t=Yie(t);)if(a_ in t)return t[a_];return null}let s_=Object.freeze({getOrCreateFor(e){let t=e[a_];return t===void 0?e[a_]=new c_(e):t},find(e){return e[a_]||o_(e)},from(e){class t extends e{constructor(){super(),s_.getOrCreateFor(this)}get config(){return this[a_].config}set config(e){this[a_].config=e}}let n=t.prototype;if(`connectedCallback`in n){let e=n.connectedCallback;n.connectedCallback=function(){e.call(this),this[a_].connect()}}else n.connectedCallback=function(){this[a_].connect()};if(`disconnectedCallback`in n){let e=n.disconnectedCallback;n.disconnectedCallback=function(){e.call(this),this[a_].disconnect()}}else n.disconnectedCallback=function(){this[a_].disconnect()};return t}});function Xie(e){return e instanceof Qe}var c_=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[a_]=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=o_(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,Zie.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 Hg(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 Zie=Object.freeze({create(e){return Object.create(ae,{router:{value:e}})}}),Qie=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 l_=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){Xie(e)&&(e.$fastController.template!==this.template&&(e.$fastController.template=this.template),e.$fastController.styles!==this.styles&&(e.$fastController.styles=this.styles))}};let $ie=Object.freeze({default:new l_(T`<slot></slot>`)});function u_(e,t){return t in e}let eae={lifecycle:!0,parameters:!0};var tae=class extends oe{constructor(e){super(),this.options=e}createPlaceholder(e){return x.createCustomAttributePlaceholder(`fast-navigation-contributor`,e)}createBehavior(e){return new nae(e,this.options)}},nae=class{constructor(e,t){this.contributor=e,this.options=t,this.router=null}bind(e,t){if(this.options.lifecycle&&(this.router=t.router||s_.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 d_(e){return new tae(Object.assign({},eae,e))}var rae=class{createContributor(){return J(this,void 0,void 0,function*(){return{navigate(e){return J(this,void 0,void 0,function*(){e.cancel()})}}})}},f_=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 Kg.path.replace(r)}))})}}})}};function p_(e){return T`<${e} ${d_()}></${e}>`}function m_(e){let t=document.createDocumentFragment();t.appendChild(e);let n=new Ae(t,[d_().createBehavior(e)]);return{create(){return n}}}var h_=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)})}},g_=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 h_(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=p_(n.name);else if(e=yield e(),typeof e==`string`)t=p_(e);else if(e instanceof HTMLElement)t=m_(e);else if(n=qe.forType(e),n)t=p_(n.name);else throw Error(`Invalid value for element in route config.`)}else n.factory=t=e instanceof HTMLElement?m_(e):p_(e);return t.create()});let i=new e(t,r);return n.layout&&(i.layout=n.layout instanceof je?new l_(n.layout):n.layout),n.transition&&(i.transition=n.transition),n.title&&(i.title=n.title),i}},__=class{constructor(){this.handler=e=>{let{shouldHandleEvent:t,href:n}=this.getEventInfo(e);t&&(e.preventDefault(),Kg.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`}},v_=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*(){u_(e,this.name)&&(this.routes.push(t),this.routers.push(n),yield e[this.name](this),this.routes.pop(),this.routers.pop())})}},y_=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 v_(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)}},b_=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}},x_=class{onUnhandledNavigationMessage(e,t){}onNavigationBegin(e,t,n){}onPhaseBegin(e){}onPhaseEnd(e){}onNavigationEnd(e,t,n){}},S_=class{constructor(){this.isConfigured=!1,this.routes=new i_(this),this.contributors=[],this.defaultLayout=$ie.default,this.defaultTransition=Qie.default,this.title=``,this.parent=null}createNavigationQueue(){return this.construct(Fie)}createLinkHandler(){return this.construct(__)}createNavigationProcess(){return new y_}createEventSink(){return this.construct(x_)}createTitleBuilder(){return this.construct(b_)}createRouteRecognizer(){return this.construct(Uie)}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=>u_(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 C_=class extends s_.from(Qe){};C_=q([$e(`fast-router`)],C_);let w_=[];setTimeout(()=>{w_.length&&console.warn(`${w_.length} attribute deprecation notice(s):\n ${w_.join(`
|
|
237
|
-
`)}`)},5e3);let T_=`reauthActionLock`;var E_;(function(e){e.SUCCESS=`SUCCESS`,e.FAILED=`FAILED`,e.HANDLED_BY_OTHER_TAB=`HANDLED_BY_OTHER_TAB`,e.ALREADY_VALID=`ALREADY_VALID`})(E_||(E_={}));function D_(){let e=parseInt(localStorage.getItem(T_)||`0`);Date.now()-e>3e4&&localStorage.removeItem(T_)}function O_(){return!localStorage.getItem(T_)&&(localStorage.setItem(T_,Date.now().toString()),!0)}function k_(){localStorage.removeItem(T_)}function A_(){return J(this,void 0,void 0,function*(){return(yield(yield fetch(Lf,{credentials:`include`})).json()).MESSAGE_TYPE===`EVENT_LOGIN_DETAILS_ACK`})}function j_(){return J(this,void 0,void 0,function*(){return(yield N.getOrCreateDOMContainer().get(Dg).post(If,{body:JSON.stringify({DETAILS:{},MESSAGE_TYPE:`EVENT_LOGIN_AUTH`})})).MESSAGE_TYPE===`EVENT_LOGIN_AUTH_ACK`})}function M_(){return J(this,arguments,void 0,function*(e={}){let{reloadOnFailure:t=!0}=e;if(D_(),!O_())return E_.HANDLED_BY_OTHER_TAB;try{return(yield A_())?E_.ALREADY_VALID:(yield j_())?E_.SUCCESS:(t&&window.location.reload(),E_.FAILED)}finally{k_()}})}function N_(e){let t=n=>{n.key===T_&&n.newValue===null&&(e(),window.removeEventListener(`storage`,t))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)}let P_=(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 F_;let I_=F_=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 Km(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 M_();return t===E_.HANDLED_BY_OTHER_TAB&&(yield new Promise(e=>{setTimeout(e,F_.REAUTH_WAIT_MS)}),t=yield M_()),t===E_.SUCCESS||t===E_.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:Ag.HEARTBEAT_PING,SOURCE_REF:`host check`}).then(e=>e.MESSAGE_TYPE===Ag.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 Km(o),RESOURCE_NAME:e});let s=this.streams.get(a).POLLING_FREQUENCY,c=Ah(Ch(this.send(i)),s.pipe(Mh(()=>document.visibilityState===`visible`)).pipe(Fh(e=>Xre(e))).pipe(Fh(()=>Ch(this.getMessage(i))))).pipe(Ih(()=>this.streams.has(a)),$re({count:F_.MAX_RETRIES,delay:(e,t)=>{let n=e;if(Y.error(`Retry ${t}/${F_.MAX_RETRIES}:`,n.status,n),!(n.status===0||n.status&&n.status>=Sg.BAD_REQUEST&&n.status<Sg.INTERNAL_SERVER_ERROR))throw e;return n.status===Sg.NOT_FOUND&&this.streams.delete(a),n.status===Sg.UNAUTHORIZED?Ch(this.handleSessionRefresh()):jh(F_.RETRY_DELAY_MS)}}),Qre(()=>{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(Nh(P_,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,jg.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=Pg(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))}}};I_.REAUTH_WAIT_MS=5e3,I_.RETRY_DELAY_MS=1e3,I_.MAX_RETRIES=3,q([C],I_.prototype,`host`,void 0),q([C],I_.prototype,`isWorking`,void 0),q([C],I_.prototype,`_isConnected`,void 0),q([w],I_.prototype,`isConnected`,null),I_=F_=q([_d(0,Dg),_d(1,Lg),_d(2,Tg),_d(3,mg),_d(4,mm),_d(5,Pie),_d(6,Bg)],I_);let L_=N.createInterface(e=>e.singleton(I_));var R_={url:``,deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},z_=`WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }`,B_=function(e){md(t,e);function t(t,n){var r=e.call(this)||this;if(r._socket=null,t instanceof Lm)r.destination=n,r.source=t;else{var i=r._config=hd({},R_);if(r._output=new Wm,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 Jm}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 Jm),this._output=new Wm},t.prototype.multiplex=function(e,t,n){var r=this;return new Lm(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 ym(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=Am.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(z_)),e._resetState()},function(){var t=e._config.closingObserver;t&&t.next(void 0),s.close(),e._resetState()}),r&&r instanceof Jm&&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}(Gm);let V_=1e4,H_=6e4;var U_;(function(e){e.Linear=`linear`,e.Exponential=`exponential`})(U_||(U_={}));let W_=(e,t)=>new Lm(n=>{let r=0,i;function a(){n.next(r),clearTimeout(i),i=setTimeout(a,t(e,r)),r+=1}return a(),()=>{clearTimeout(i)}}),G_=(e,t)=>{let{reconnectInterval:n=V_}=e,r=n>H_?H_:n;return r*2**(t%Math.round(Math.log2(H_/r)))},K_=e=>{let{reconnectInterval:t=V_}=e;return t>H_?H_:t};var q_=class{constructor(){this.isConfigured=!1,this.isConnecting=!1,this.isConnected=!1,this.isReconnecting=!1,this.reconnectionLimitReached=!1,this.isConnectedSubject=new Km(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],q_.prototype,`isConfigured`,void 0),q([C],q_.prototype,`isConnecting`,void 0),q([C],q_.prototype,`isConnected`,void 0),q([C],q_.prototype,`isReconnecting`,void 0),q([C],q_.prototype,`reconnectionLimitReached`,void 0),q([C],q_.prototype,`closedCode`,void 0),q([C],q_.prototype,`closedReason`,void 0),q([C],q_.prototype,`closedClean`,void 0),q([pg],q_.prototype,`user`,void 0);let J_=N.createInterface(e=>e.singleton(q_));var Y_=class{constructor(e){this.interval=e}get workerScript(){return`
|
|
237
|
+
`)}`)},5e3);let T_=`reauthActionLock`;var E_;(function(e){e.SUCCESS=`SUCCESS`,e.FAILED=`FAILED`,e.HANDLED_BY_OTHER_TAB=`HANDLED_BY_OTHER_TAB`,e.ALREADY_VALID=`ALREADY_VALID`})(E_||(E_={}));function D_(){let e=parseInt(localStorage.getItem(T_)||`0`);Date.now()-e>3e4&&localStorage.removeItem(T_)}function O_(){return!localStorage.getItem(T_)&&(localStorage.setItem(T_,Date.now().toString()),!0)}function k_(){localStorage.removeItem(T_)}function A_(){return J(this,void 0,void 0,function*(){let e=yield fetch(Lf,{credentials:`include`});return e.status!==401&&(yield e.json()).MESSAGE_TYPE===`EVENT_LOGIN_DETAILS_ACK`})}function j_(){return J(this,void 0,void 0,function*(){return(yield N.getOrCreateDOMContainer().get(Dg).post(If,{body:JSON.stringify({DETAILS:{},MESSAGE_TYPE:`EVENT_LOGIN_AUTH`})})).MESSAGE_TYPE===`EVENT_LOGIN_AUTH_ACK`})}function M_(){return J(this,arguments,void 0,function*(e={}){let{reloadOnFailure:t=!0}=e;if(D_(),!O_())return E_.HANDLED_BY_OTHER_TAB;try{return(yield A_())?E_.ALREADY_VALID:(yield j_())?E_.SUCCESS:(t&&window.location.reload(),E_.FAILED)}finally{k_()}})}function N_(e){let t=n=>{n.key===T_&&n.newValue===null&&(e(),window.removeEventListener(`storage`,t))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)}let P_=(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 F_;let I_=F_=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 Km(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 M_();return t===E_.HANDLED_BY_OTHER_TAB&&(yield new Promise(e=>{setTimeout(e,F_.REAUTH_WAIT_MS)}),t=yield M_()),t===E_.SUCCESS||t===E_.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:Ag.HEARTBEAT_PING,SOURCE_REF:`host check`}).then(e=>e.MESSAGE_TYPE===Ag.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 Km(o),RESOURCE_NAME:e});let s=this.streams.get(a).POLLING_FREQUENCY,c=Ah(Ch(this.send(i)),s.pipe(Mh(()=>document.visibilityState===`visible`)).pipe(Fh(e=>Xre(e))).pipe(Fh(()=>Ch(this.getMessage(i))))).pipe(Ih(()=>this.streams.has(a)),$re({count:F_.MAX_RETRIES,delay:(e,t)=>{let n=e;if(Y.error(`Retry ${t}/${F_.MAX_RETRIES}:`,n.status,n),!(n.status===0||n.status&&n.status>=Sg.BAD_REQUEST&&n.status<Sg.INTERNAL_SERVER_ERROR))throw e;return n.status===Sg.NOT_FOUND&&this.streams.delete(a),n.status===Sg.UNAUTHORIZED?Ch(this.handleSessionRefresh()):jh(F_.RETRY_DELAY_MS)}}),Qre(()=>{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(Nh(P_,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,jg.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=Pg(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))}}};I_.REAUTH_WAIT_MS=5e3,I_.RETRY_DELAY_MS=1e3,I_.MAX_RETRIES=3,q([C],I_.prototype,`host`,void 0),q([C],I_.prototype,`isWorking`,void 0),q([C],I_.prototype,`_isConnected`,void 0),q([w],I_.prototype,`isConnected`,null),I_=F_=q([_d(0,Dg),_d(1,Lg),_d(2,Tg),_d(3,mg),_d(4,mm),_d(5,Pie),_d(6,Bg)],I_);let L_=N.createInterface(e=>e.singleton(I_));var R_={url:``,deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},z_=`WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }`,B_=function(e){md(t,e);function t(t,n){var r=e.call(this)||this;if(r._socket=null,t instanceof Lm)r.destination=n,r.source=t;else{var i=r._config=hd({},R_);if(r._output=new Wm,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 Jm}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 Jm),this._output=new Wm},t.prototype.multiplex=function(e,t,n){var r=this;return new Lm(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 ym(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=Am.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(z_)),e._resetState()},function(){var t=e._config.closingObserver;t&&t.next(void 0),s.close(),e._resetState()}),r&&r instanceof Jm&&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}(Gm);let V_=1e4,H_=6e4;var U_;(function(e){e.Linear=`linear`,e.Exponential=`exponential`})(U_||(U_={}));let W_=(e,t)=>new Lm(n=>{let r=0,i;function a(){n.next(r),clearTimeout(i),i=setTimeout(a,t(e,r)),r+=1}return a(),()=>{clearTimeout(i)}}),G_=(e,t)=>{let{reconnectInterval:n=V_}=e,r=n>H_?H_:n;return r*2**(t%Math.round(Math.log2(H_/r)))},K_=e=>{let{reconnectInterval:t=V_}=e;return t>H_?H_:t};var q_=class{constructor(){this.isConfigured=!1,this.isConnecting=!1,this.isConnected=!1,this.isReconnecting=!1,this.reconnectionLimitReached=!1,this.isConnectedSubject=new Km(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],q_.prototype,`isConfigured`,void 0),q([C],q_.prototype,`isConnecting`,void 0),q([C],q_.prototype,`isConnected`,void 0),q([C],q_.prototype,`isReconnecting`,void 0),q([C],q_.prototype,`reconnectionLimitReached`,void 0),q([C],q_.prototype,`closedCode`,void 0),q([C],q_.prototype,`closedReason`,void 0),q([C],q_.prototype,`closedClean`,void 0),q([pg],q_.prototype,`user`,void 0);let J_=N.createInterface(e=>e.singleton(q_));var Y_=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))}},X_=class extends Wm{constructor(){super()}},Z_=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 Q_=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??Pf}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=Pf,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 B_({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===Ag.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 jg.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 Ag.LOGOUT_ACK:i.onReceivedMessage.call(this,e),this.cleanMessages();return;case Ag.LOGON_ACK:return;case Ag.LOGOFF_ACK:break;case Ag.QUERY_UPDATE:i.isSubscription||this.sendDataLogoff(n);break;case Ag.MSG_NACK:case Ag.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 M_();if(e===E_.HANDLED_BY_OTHER_TAB){N_(()=>this.connect());return}e!==E_.FAILED&&(yield this.connect())})}updateSessionAndSubscriptions(e){e?.MESSAGE_TYPE===jg.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===Ag.HEARTBEAT_PONG&&t.SOURCE_REF===e.SOURCE_REF});if(this.connectOptions?.enableHeartbeat??this.heartbeatIsEnabled){let t=this.connectOptions?.heartbeatInterval??this.heartbeatInterval;this.heartbeatTicker=new Y_(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===U_.Exponential?G_:K_;this.isConnectedSubject.asObservable().pipe(Fh(e=>e?wh(-1):W_(this.reconnectOptions,t).pipe(kh(e=>{let t;return t=this.connectOptions?.alwaysOn?e+1:this.reconnectOptions?.reconnectAttempts??10,e<t?wh(e):(this.status.reconnectionLimitReached=!0,Th(()=>/* @__PURE__ */ Error(`Max reconnect attempts ${t} reached.`)))}))),Ih(()=>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 X_,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 Th(()=>/* @__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 Lm(t=>{let n=this.wsMessages.pipe(Mh(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 Th(()=>/* @__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(Mh(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 Z_(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 jg.DATA_LOGOFF:t(n);break;case Ag.HEARTBEAT_PING:case Ag.HEARTBEAT_PONG:this.heartbeatLoggingIsEnabled&&t(n);break;default:this.messageLoggingIsEnabled&&t(n)}}};q([C],Q_.prototype,`websocket`,void 0),q([C],Q_.prototype,`wsMessages`,void 0),q([C],Q_.prototype,`wsMessageHandlers`,void 0),q([Dg],Q_.prototype,`http`,void 0),q([C],Q_.prototype,`heartbeatIsEnabled`,void 0),Q_=q([_d(0,Lg),_d(1,Tg),_d(2,mm),_d(3,lg),_d(4,J_),_d(5,pg),_d(6,xg)],Q_);let $_=N.createInterface(e=>e.singleton(Q_));function ev(){return N.getOrCreateDOMContainer().get($_)}let tv=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 Nf===`true`||kf(`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=Pf){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(Nh(P_,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,jg.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=Pg(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],tv.prototype,`isWorking`,void 0),tv=q([_d(0,$_),_d(1,Lg),_d(2,mg),_d(3,Cie),_d(4,xg),_d(5,Bg)],tv);let nv=Mf===`true`||kf(`forceHttp`),rv=N.createInterface(e=>e.singleton(tv)),iv=N.createInterface(e=>nv?e.aliasTo(L_):e.aliasTo(rv));function av(){return N.getOrCreateDOMContainer().get(iv)}var ov=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(ov));
|
|
243
243
|
/*! js-cookie v3.0.7 | MIT */
|
|
244
244
|
function sv(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 cv={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 lv(e,t){function n(n,r,i){if(typeof document<`u`){i=sv({},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,``,sv({},t,{expires:-1}))},withAttributes:function(e){return lv(this.converter,sv({},this.attributes,e))},withConverter:function(e){return lv(sv({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var uv=lv(cv,{path:`/`});let dv=N.createInterface();function fv(){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 pv(e=``,t=`:`,n){return e.split(t,n).map(e=>e.trim()).filter(e=>e!==``)}function mv(e,t=`:`){let n=typeof e==`string`&&e.trim();return n?n.includes(t):!1}function hv(e,t=`:`){return typeof e==`string`&&e.trim()?(e.match(new RegExp(t,`g`))||[]).length:0}function gv(e,t=`:`){for(let n of e)if(mv(n,t))return n;return e.find(e=>typeof e==`string`&&e.trim()!==``)}function _v(e,t,n){let r=typeof e==`string`&&e.trim();return!r||n&&!r.includes(n)||hv(r)>1?n&&t&&n!==t?`${t}:${n}`:t||n:r}function vv(e=`credential`){Y.warn(`Unable to migrate legacy ${e} to latest format. Please remove from your browser.`)}let yv={password:!0,mediation:`optional`},bv={cookie:{path:`/`,name:`credentials`,expires:7300,storePasswords:!1}},xv=class{constructor(e,t=bv){this.session=e,this.config=t}createBasicCredentials(e){return{type:Og.BASIC,username:e.username,password:e.password,mfaToken:this.getMFAToken()}}createRefreshCredentials(e){return{type:Og.REFRESH,username:e?.username??this.getUsername(),refreshToken:e?.refreshToken??this.getRefreshToken(),mfaToken:e?.mfaToken??this.getMFAToken()}}createSSOCredentials(e){return{type:Og.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(`:`)&&hv(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]=pv(t.name||t.id),[r,i]=pv(gv([t.id,t.name]));return[{id:_v(t.id||t.name,n,i),name:n,password:t.password||``},!0]}catch{vv(`PasswordCredential`)}if(t)try{let e=t,[n]=pv(e.name||e.username||e.organisation),[r,i]=pv(gv([e.organisation||e.username||e.name]));return[{id:_v(e.id||e.username||e.name,n,i),name:n,password:e.password||``},!1]}catch{vv(`cookie`)}return[void 0,!1]}storeCredentialsInContainer(e){return J(this,void 0,void 0,function*(){if(!fv())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=yv){if(fv())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`),!!uv.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=uv.get(this.config.cookie.name);return e?JSON.parse(e):void 0}storeCredentials(e){return J(this,void 0,void 0,function*(){if(fv()){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 fv()?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(){uv.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 fv()&&navigator.credentials.preventSilentAccess()}};xv=q([_d(0,Tg),_d(1,Rt(dv))],xv);let Sv=N.createInterface(e=>e.singleton(xv)),Cv=e=>e?{date:e.DATE}:null,wv=e=>e?e.map(e=>({name:e.NAME,version:e.VERSION})):[],Tv=e=>Array.isArray(e)?e.map(e=>e??``):[],Ev=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:Cv(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:wv(t.PRODUCT)}:null,permission:Tv(e.PERMISSION),profile:Tv(e.PROFILE)}}throw Error(`No Entity mapping implementation for provided DTO`)}catch(e){throw Y.error(e),e}},Dv=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 Km(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 kg(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(Ev(n)),this.session.setAuthResult(n),Y.debug(`Login Authentication Result:`,n)}catch(e){if(Y.error(`Login Authentication Error:`,e),e instanceof kg&&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===Ag.LOGOUT_NACK;c&&Y.warn(`Unexpected Logout NACK received during logout.`,s),e={success:a===Ag.LOGOUT_ACK||n===Mg.SESSION_NOT_FOUND||!c,error:s},o&&window.open(o,`_self`)}catch(t){let n=new kg(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===jg.EVENT_LOGIN_AUTH_ACK)return this.session.setAuthResult(t),this.currentUser.set(Ev(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],Dv.prototype,`isWorking`,void 0),q([C],Dv.prototype,`loggedUserResult`,void 0),Dv=q([_d(0,Tg),_d(1,iv),_d(2,Lg),_d(3,Sv),_d(4,pg)],Dv);let Ov=N.createInterface(e=>e.singleton(Dv));function kv(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 Av(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 jv(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 Mv(e){if(!e)return{};let t=e.split(`&&`).map(e=>e.trim()),n={};return t.forEach(e=>{if(e){if(e.startsWith(`Expr`))Av(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`]=kv(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`]=kv(i,o)}}else jv(e,n)}}),n}function Nv(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 Pv=class{};Pv.MAX_ROWS_250=250,Pv.MAX_VIEW_1000=1e3,Pv.REQ_REP_POLLING_INTERVAL_MS=1e4,Pv.DATASERVER_ROW_ID=`ROW_REF`,Pv.REQUEST_SERVER_ROW_ID=`RECORD_ID`,Pv.DEFAULT_PAGINATION_PAGE_SIZE=25,Pv.DEFAULT_REQ_REP_OFFSET=0;let Fv={options:{criteria:``,isSnapshot:!1,maxRows:Pv.MAX_ROWS_250,maxView:Pv.MAX_VIEW_1000,pollingInterval:Pv.REQ_REP_POLLING_INTERVAL_MS,movingView:!1,orderBy:``,resourceName:``,reverse:!1,pollTriggerEvents:[]},criteriaToFields:Mv,dataServerResultFilter:Nv},Iv=N.createInterface(e=>e.instance(Fv));function Lv(e){let t=e==null?NaN:Number(e);return Number.isFinite(t)?t===0?1/0:t:Pv.MAX_VIEW_1000}function Rv(e){return e.moreRows===!1?`end`:e.rowsHeld>=Lv(e.maxView)?e.movingView?`more`:`view-full`:e.emptyReply?`stalled`:`more`}function zv(e){let t=Lv(e.maxView),n=Bv(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 Bv(e){return e==null||!Number.isFinite(Number(e))}let Vv=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(_g,this.onDatasourceStatusChanged,{passive:!0,capture:!0})}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(_g,this.onDatasourceStatusChanged,{capture:!0})}}return q([C],t.prototype,`datasourceStatus`,void 0),t},Hv={throwWhenUnavailable:!0,throwWhenUnknown:!1},Uv=N.createInterface(e=>e.instance(Hv)),Wv=qd(`genesis-resources`);function Gv(){return N.getOrCreateDOMContainer().get(Wv)}let Kv=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=Gv();e.postMessage(`resources-loaded`,this.resources),e.close()}};Kv=q([_d(0,iv),_d(1,Uv)],Kv);let qv=N.createInterface(e=>e.singleton(Kv)),Jv=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 Wm}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 Wm,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 gg.DATASERVER:return this.connect.snapshot(this.options.resourceName,Object.assign(Object.assign({},this.dataserverOnlyParams),e));case gg.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(![gg.DATASERVER,gg.REQUEST_SERVER].includes(this.resourceType))throw Error(`Streaming not supported for selected resource type: ${this.resourceType}`);return this.resourceType===gg.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===gg.REQUEST_SERVER&&this.loadMoreCount>0){let t=(this.options.maxRows||25)*(this.loadMoreCount+1);e.DETAILS.MAX_ROWS=t}return Gre([this.connect.isConnected$,this.auth.isLoggedIn$]).pipe(Ih(()=>this.connect.isConnected&&this.auth.isLoggedIn),Fh(()=>Ch(this.snapshot(e))))};return e?this.pollTrigger$.pipe(Ph(0),Fh(()=>jh(0,e).pipe(Fh(t)))):this.pollTrigger$.pipe(Ph(0),Fh(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=yg(e),this.fieldMetadata=vg(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 '${_g}'`,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],Jv.prototype,`status`,void 0),q([C],Jv.prototype,`fetchMetadataRequired`,void 0),q([C],Jv.prototype,`startStreamRequired`,void 0),q([C],Jv.prototype,`originalFieldDef`,void 0),q([C],Jv.prototype,`fieldMetadata`,void 0),q([C],Jv.prototype,`requestFields`,void 0),q([C],Jv.prototype,`customRequestFields`,void 0),q([C],Jv.prototype,`availableIndexes`,void 0),q([C],Jv.prototype,`availableSortableFields`,void 0),q([C],Jv.prototype,`availableCriteriaFields`,void 0),q([C],Jv.prototype,`criteriaOnlyRequest`,void 0),q([C],Jv.prototype,`loadMoreCount`,void 0),q([C],Jv.prototype,`readOnly`,void 0),q([C],Jv.prototype,`stream`,void 0),Jv=q([_d(0,iv),_d(1,Ov),_d(2,qv),_d(3,Iv),_d(4,bg)],Jv);let Yv=N.createInterface(e=>e.transient(Jv));var Xv=class extends Jv{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===Ag.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(Xv));function Zv(e,t=`;`){return e&&e.split(t).map(e=>e.trim()).sort((e,t)=>e.localeCompare(t)).join(t)}let Qv=`system-health-changed`,$v={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 av().getMoreColumns(e),n=Date.now(),r=t;return{isConnected:t.MESSAGE_TYPE===Ag.MORE_COLUMNS_ACK,lastUpdated:n,lastMessage:r}}),resourceDataLogon:({message:e,functions:t})=>{let{onMessage:n,onError:r}=t;ev().sendForStream(e,n,r)}},ey=N.createInterface(e=>e.instance($v));var ty=/* @__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}})}))})),ny=/* @__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)}}})),ry=/* @__PURE__ */ u(ty()),iy=/* @__PURE__ */ u(ny());let ay=Vd(`network-monitor`,{level:Dd.info}),oy=Date.now(),sy=window.navigator?.userAgent?ry.default.parse(window.navigator.userAgent):void 0,cy=(e,t={depthLimit:10,edgesLimit:10})=>e instanceof Event?`'${e.type}' Event`:typeof e==`string`?e:(0,iy.default)(e,void 0,2,t);var ly=class{constructor(){this.unsubscribableObservers=[],this.runAllChecks=(e,t)=>J(this,void 0,void 0,function*(){if(!this.isReady||this.isRunningChecks&&!t)return;ay.info(`Run health checks, triggered by`,cy(e),`| Active resources`,this.resources.size),this.isRunningChecks=!0,this.synchroniseCheckInterval();let n=this.getFormattedTimestamp(this.getNowTimestamp()),r=yield this.isOnlineCheck();r?ay.debug(`Network connected at ${n}`):ay.warn(`Network disconnected at ${n}`);let i=this.normaliseSerializedSocketStatus(this.socketStatus.serialize(),r),a=this.preFlightSocketChecks(i);if(a||ay.debug(`Socket pre-flight checks failed`),!r||!a){ay.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{ay.debug(`Running health check against ${r}`);let e=yield Promise.race([c(u,t),Zf(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===Ag.MSG_NACK||Fg(p,Sg.NOT_FOUND),n=this.getFormattedTimestamp(f??this.getNowTimestamp()),d?ay.debug(`${r} is healthy at ${n}`):ay.warn(`${r} is not healthy at ${n}`),p&&ay.debug(`${r} messaged at ${n}`,cy(p)),m&&ay.error(`${r} errored at ${n}`,cy(m)),h&&ay.warn(`${r} timed out at ${n}`),g&&(ay.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 ay.warn(`Unexpected promise rejection occurred. Please check any custom resourceChecks return MonitoredResourceChecksResult.`),e},{});ay.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&&(ay.level=this.config.logLevel)}create(){if(this.resources){ay.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=``;Fg(i,Sg.NOT_FOUND)?a=`Please check the resource is running.`:Fg(i,Sg.FORBIDDEN)&&(a=`You are not authorised to access this resource, removing it from monitoring.`,this.removeResource(n)),ay.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){ay.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?ay.debug:ay.warn)(`Emitting 'system-health-changed' event`,cy(this.status)),t?.dispatchEvent(new CustomEvent(`system-health-changed`,{detail:this.status,bubbles:t!==document,composed:!0})),this.status.socket.reconnectionLimitReached&&(ay.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 ay.debug(`User requested report stability to Genesis.`),ay.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:sy,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:oy,runAllChecks:()=>{ay.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return ay.debug(`Socket not configured`),!1;if(e.isReconnecting)return ay.debug(`Socket reconnecting`),!1;if(e.isConnecting)return ay.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return ay.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&ay.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return ay.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return Vf(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([ey],ly.prototype,`config`,void 0),q([J_],ly.prototype,`socketStatus`,void 0),q([bg],ly.prototype,`connectEvents`,void 0),q([pg],ly.prototype,`user`,void 0),q([C],ly.prototype,`status`,void 0);let uy=N.createInterface(e=>e.singleton(ly)),dy={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},fy=N.createInterface();var py;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(py||(py={}));var my;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(my||(my={}));let hy=class{constructor(e,t,n=dy){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(my.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(py.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=Tf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=Tf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=Tf(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(py.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?Df(e.value):e.value}))}},n=yield this.connect.commitEvent(my.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};hy=q([_d(0,iv),_d(1,pg),_d(2,Rt(fy))],hy),N.createInterface(e=>e.singleton(hy));var gy=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Km(!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 fg,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],gy.prototype,`isWorking`,void 0),q([C],gy.prototype,`loggedUserResult`,void 0),q([C],gy.prototype,`currentUser`,void 0),q([C],gy.prototype,`isLoggedIn`,void 0);var _y=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=yg(e),this.fieldMetadata=vg(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=Ch(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],_y.prototype,`status`,void 0),q([C],_y.prototype,`fetchMetadataRequired`,void 0),q([C],_y.prototype,`originalFieldDef`,void 0),q([C],_y.prototype,`fieldMetadata`,void 0),q([C],_y.prototype,`requestFields`,void 0),q([C],_y.prototype,`customRequestFields`,void 0),q([C],_y.prototype,`availableIndexes`,void 0),q([C],_y.prototype,`availableSortableFields`,void 0),q([C],_y.prototype,`availableCriteriaFields`,void 0),q([C],_y.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(pg));let vy=Vd(`foundation-ui`);var yy=class extends Vv(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Pv.MAX_ROWS_250,this.maxView=Pv.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 Km(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==Zv(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===gg.REQUEST_SERVER?Pv.REQUEST_SERVER_ROW_ID:Pv.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}vy.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?Nv(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Ag.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 gg.REQUEST_SERVER:return!0;case gg.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===gg.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 Nv(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==gg.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=Rv({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=zv({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&vy.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 Zv((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&&vy[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===hg.DATE||t===hg.DATETIME?Hf(e,t===hg.DATETIME):e}};q([iv],yy.prototype,`connect`,void 0),q([Yv],yy.prototype,`datasource`,void 0),q([D({mode:`boolean`})],yy.prototype,`withGridInit`,void 0),q([D],yy.prototype,`criteria`,void 0),q([C],yy.prototype,`data`,void 0),q([D],yy.prototype,`fields`,void 0),q([D({mode:`boolean`})],yy.prototype,`isSnapshot`,void 0),q([D],yy.prototype,`maxRows`,void 0),q([D],yy.prototype,`maxView`,void 0),q([D],yy.prototype,`orderBy`,void 0),q([D],yy.prototype,`request`,void 0),q([D],yy.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],yy.prototype,`reverse`,void 0),q([D],yy.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],yy.prototype,`withTimestampFormatting`,void 0);let by=(e,t)=>!e.composedPath().includes(t),xy=(e,t)=>e.composedPath().includes(t),Sy=e=>e.tagName.toLowerCase().split(`-`)[0];function Cy(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let wy=Vd(`foundation-criteria`);var Ty;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(Ty||(Ty={}));var Ey=class e{constructor(e){this.$$operator=e}static And(){return new e(Ty.AND)}static Or(){return new e(Ty.OR)}static Not(){return new e(Ty.NOT)}static GreaterThan(){return new e(Ty.GT)}static GreaterThanOrEqual(){return new e(Ty.GE)}static LessThan(){return new e(Ty.LT)}static LessThanOrEqual(){return new e(Ty.LE)}static NotEqual(){return new e(Ty.NE)}static Equal(){return new e(Ty.EQ)}get operator(){return this.$$operator}};let Dy=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},Oy=e=>t=>`${t.field} ${e} ${Dy(t)}`,ky={AND:e=>Oy(Ty.AND)(e),OR:e=>Oy(Ty.OR)(e),NOT:e=>Oy(Ty.NOT)(e),GT:e=>Oy(Ty.GT)(e),GE:e=>Oy(Ty.GE)(e),LT:e=>Oy(Ty.LT)(e),LE:e=>Oy(Ty.LE)(e),NE:e=>Oy(Ty.NE)(e),EQ:e=>Oy(Ty.EQ)(e),equals:e=>`${e.field}.equals(${Dy(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Dy(e)})`,contains:e=>`Expr.contains(${e.field}, ${Dy(e)})`,fieldContains:e=>`${e.field}.contains(${Dy(e)})`,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Dy(e)})`,startsWith:e=>`${e.field}.startsWith(${Dy(e)})`,endsWith:e=>`${e.field}.endsWith(${Dy(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Dy(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Dy(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Dy(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Dy(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Dy(e)})`},Ay=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),jy=e=>Array.isArray(e)?e:[e],My=`default`;var Ny=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,Ey.And()),this.Or=(e,t={})=>this.withExpression(e,t,Ey.Or()),this.Not=(e,t={})=>this.withExpression(e,t,Ey.Not())}withExpression(e,t={},n=Ey.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=My)=>{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 Ey;return t&&wy.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Ay(t,i),My)}else o(e,My)}else typeof e==`string`?o(e,My):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 Ey&&n[t-1]instanceof Ey)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof Ey?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Py=class{constructor(e){this.serialiser=ky.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 Fy=(e=`rapid`)=>T`<${e}-segmented-control :value="${xf(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>`,Iy=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Ny,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(jy(i).map(e=>jy(n).map(t=>new Py().withField(t).withValue(e).withSerialiser(r).build())),{join:Ey.Or()}):t.And(new Py().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],Iy.prototype,`criteriaOptions`,void 0),q([C],Iy.prototype,`prefix`,void 0),q([C],Iy.prototype,`value`,void 0),q([C],Iy.prototype,`selectedLabel`,void 0),Iy=q([$e({name:`criteria-segmented-control`,template:Fy(),styles:O``})],Iy);function Ly(e,t){let n=new Ny;n.withExpression(new Py().withField(e.labelField??e.valueField).withValue(t).withSerialiser(ky.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Ry(e,t){let n=new Ny;n.withExpression(new Py().withField(e.valueField).withValue(t).withSerialiser(ky.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let zy=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,By=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>`,Vy=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>`,Hy=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Sy(e))}</div>`;var Uy=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 By(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],Vy(e)):By(e)}};q([C],Uy.prototype,`actions`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],Uy.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],Uy.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],Uy.prototype,`autoCloseOnAction`,void 0),q([C],Uy.prototype,`classNames`,void 0),q([C],Uy.prototype,`definition`,void 0),q([D],Uy.prototype,`name`,void 0),q([D({attribute:`open`,mode:`boolean`})],Uy.prototype,`open`,void 0),q([D],Uy.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],Uy.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],Uy.prototype,`hideMenuSingleOption`,void 0),q([C],Uy.prototype,`singleOption`,void 0),Uy.compose({baseName:`actions-menu`,styles:Nne,template:Hy});let Wy=()=>{};function Gy(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:Wy};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 Ky=!1;try{typeof GENX_ENABLE_AI<`u`&&(Ky=GENX_ENABLE_AI===`true`)}catch{}let qy=()=>Ky||kf(`ai`),Jy=Vd(`foundation-ai`);function Yy(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function Xy(e,t){if(!Yy())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 Zy=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 Qy=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`]),new Map(Object.entries(Qy).map(([e,t])=>[t.toLowerCase(),e]));var $y=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 eb=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,tb=e=>{try{return JSON.parse(e)}catch{return}},nb=e=>{let t=e?.code;return typeof t==`string`?t:void 0},rb=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,ib=e=>typeof e==`boolean`?e:void 0,ab=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function ob(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 $y(e,rb(r.budgetUsd)??rb(i.budgetUsd),rb(r.spentUsd)??rb(i.spentUsd),a,{otherVendorAvailable:ib(r.otherVendorAvailable)??ib(i.otherVendorAvailable),serverVendor:ab(r.vendor)??ab(i.vendor)})}var sb=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 cb=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),lb=Object.freeze([`authentication_error`,`permission_error`]);function ub(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 db(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 fb(e){let t=ub(e);if(t?.type){if(lb.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function pb(e,t,n){if(t===`PROVIDER_REFUSED`)return db(n)??fb(n)??`spend`;if(e!==`anthropic`)return;let r=fb(n);if(r)return r;let i=ub(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(cb.some(t=>t.test(e)))return`spend`}}function mb(e,t,n,r,i){let a=ub(r);return new sb(e,t,n,a?.type,a?.message??i)}function hb(e){return Object.entries(Qy).find(([,t])=>t===e)?.[0]}let gb=[`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`],_b=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`];function vb(e){return e===`image/jpg`?`image/jpeg`:e}function yb(e){return e.replace(/^data:[^,]*;base64,/,``)}let bb=.5;function xb(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=bb?r/bb*t:t+(r-bb)/.5*(n-t)}let Sb=1e6,Cb={"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 wb(e){return Cb[e]}function Tb(e,t){let{promptPerMillion:n,candidatePerMillion:r}=wb(e),i=Sb,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 Eb={"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 Db(e,t){let n=Eb[e];return n.kind===`flat`?n.rate:t>2e5?n.longContext:n.standard}function Ob(e,t){let{promptPerMillion:n,candidatePerMillion:r}=Db(e,t.promptTokens),i=Sb,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 kb=[`properties`,`patternProperties`,`$defs`,`definitions`],Ab=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],jb=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Mb=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Nb(e){if(Array.isArray(e))return e.map(Nb);if(Mb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nb(r);return t}return e}function Pb(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=kb.includes(i)&&Mb(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Mb(r)?t(r,`${e}/${n}`):Nb(r)])):Ab.includes(i)&&Array.isArray(a)?a.map((n,r)=>Mb(n)?t(n,`${e}/${r}`):Nb(n)):jb.includes(i)?Mb(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Mb(n)?t(n,`${e}/${r}`):Nb(n)):Nb(a):Nb(a)}return r}function Fb(e,t,n=``){return t(Pb(e,(e,n)=>Fb(e,t,n),n),n)}let Ib=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Lb=[`oneOf`,`not`];function Rb(e){let t=[],n=[],r=[];return{schema:Fb(e,(e,i)=>{for(let n of Ib)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 Lb)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Mb(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function zb(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Rb(e);return r.length&&Jy.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&Jy.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&&Jy.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 Bb=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Vb(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Mb(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Mb(n)?n:void 0}function Hb(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=Vb(e,o);if(!t)break;let{$ref:n}=i,r=gd(i,[`$ref`]);i=Object.assign(Object.assign({},Nb(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),Pb(i,t=>Hb(e,t,a,r),``)}function Ub(e){let t=[],n=Hb(e,e,/* @__PURE__ */ new Set,t);return t.length&&Jy.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.`),Fb(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(Mb),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 Bb)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}function Wb(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 Gb(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 Kb=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`}),qb=new Set(Object.values(Kb));function Jb(e){return typeof e==`string`&&qb.has(e)?e:void 0}let Yb=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),Xb=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},Zb=e=>e?.code!==void 0;function Qb(e,t,n){if(e!==401&&e!==403||Zb(t))return;let r=typeof n==`string`&&n.trim()===``;if(Xb(t)||r)return e===401?Yb.SIGNED_OUT:Yb.ACCESS_DENIED}function $b(e,t){return e===413&&t===void 0}function ex(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let tx=`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:tx,FALLBACKS_NOT_SUPPORTED:tx,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 nx=e=>e!==Kb.VENDOR_UNREACHABLE;var rx=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 nx(this.code)}};function ix(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let ax=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]),ox=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var sx=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 cx(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 lx(e,t,n){if(t===400)for(let e of cx(n)){if(!ax.some(t=>t.test(e)))continue;let t=ox.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function ux(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:sy,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:oy,runAllChecks:()=>{ay.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return ay.debug(`Socket not configured`),!1;if(e.isReconnecting)return ay.debug(`Socket reconnecting`),!1;if(e.isConnecting)return ay.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return ay.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&ay.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return ay.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return Vf(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([ey],ly.prototype,`config`,void 0),q([J_],ly.prototype,`socketStatus`,void 0),q([bg],ly.prototype,`connectEvents`,void 0),q([pg],ly.prototype,`user`,void 0),q([C],ly.prototype,`status`,void 0);let uy=N.createInterface(e=>e.singleton(ly)),dy={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},fy=N.createInterface();var py;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(py||(py={}));var my;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(my||(my={}));let hy=class{constructor(e,t,n=dy){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(my.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(py.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=Tf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=Tf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=Tf(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(py.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?Df(e.value):e.value}))}},n=yield this.connect.commitEvent(my.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};hy=q([_d(0,iv),_d(1,pg),_d(2,Rt(fy))],hy),N.createInterface(e=>e.singleton(hy));var gy=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Km(!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 fg,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],gy.prototype,`isWorking`,void 0),q([C],gy.prototype,`loggedUserResult`,void 0),q([C],gy.prototype,`currentUser`,void 0),q([C],gy.prototype,`isLoggedIn`,void 0);var _y=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=yg(e),this.fieldMetadata=vg(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=Ch(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],_y.prototype,`status`,void 0),q([C],_y.prototype,`fetchMetadataRequired`,void 0),q([C],_y.prototype,`originalFieldDef`,void 0),q([C],_y.prototype,`fieldMetadata`,void 0),q([C],_y.prototype,`requestFields`,void 0),q([C],_y.prototype,`customRequestFields`,void 0),q([C],_y.prototype,`availableIndexes`,void 0),q([C],_y.prototype,`availableSortableFields`,void 0),q([C],_y.prototype,`availableCriteriaFields`,void 0),q([C],_y.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(pg));let vy=Vd(`foundation-ui`);var yy=class extends Vv(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Pv.MAX_ROWS_250,this.maxView=Pv.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 Km(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==Zv(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===gg.REQUEST_SERVER?Pv.REQUEST_SERVER_ROW_ID:Pv.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}vy.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?Nv(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Ag.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 gg.REQUEST_SERVER:return!0;case gg.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===gg.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 Nv(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==gg.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=Rv({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=zv({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&vy.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 Zv((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&&vy[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===hg.DATE||t===hg.DATETIME?Hf(e,t===hg.DATETIME):e}};q([iv],yy.prototype,`connect`,void 0),q([Yv],yy.prototype,`datasource`,void 0),q([D({mode:`boolean`})],yy.prototype,`withGridInit`,void 0),q([D],yy.prototype,`criteria`,void 0),q([C],yy.prototype,`data`,void 0),q([D],yy.prototype,`fields`,void 0),q([D({mode:`boolean`})],yy.prototype,`isSnapshot`,void 0),q([D],yy.prototype,`maxRows`,void 0),q([D],yy.prototype,`maxView`,void 0),q([D],yy.prototype,`orderBy`,void 0),q([D],yy.prototype,`request`,void 0),q([D],yy.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],yy.prototype,`reverse`,void 0),q([D],yy.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],yy.prototype,`withTimestampFormatting`,void 0);let by=(e,t)=>!e.composedPath().includes(t),xy=(e,t)=>e.composedPath().includes(t),Sy=e=>e.tagName.toLowerCase().split(`-`)[0];function Cy(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let wy=Vd(`foundation-criteria`);var Ty;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(Ty||(Ty={}));var Ey=class e{constructor(e){this.$$operator=e}static And(){return new e(Ty.AND)}static Or(){return new e(Ty.OR)}static Not(){return new e(Ty.NOT)}static GreaterThan(){return new e(Ty.GT)}static GreaterThanOrEqual(){return new e(Ty.GE)}static LessThan(){return new e(Ty.LT)}static LessThanOrEqual(){return new e(Ty.LE)}static NotEqual(){return new e(Ty.NE)}static Equal(){return new e(Ty.EQ)}get operator(){return this.$$operator}};let Dy=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},Oy=e=>t=>`${t.field} ${e} ${Dy(t)}`,ky={AND:e=>Oy(Ty.AND)(e),OR:e=>Oy(Ty.OR)(e),NOT:e=>Oy(Ty.NOT)(e),GT:e=>Oy(Ty.GT)(e),GE:e=>Oy(Ty.GE)(e),LT:e=>Oy(Ty.LT)(e),LE:e=>Oy(Ty.LE)(e),NE:e=>Oy(Ty.NE)(e),EQ:e=>Oy(Ty.EQ)(e),equals:e=>`${e.field}.equals(${Dy(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Dy(e)})`,contains:e=>`Expr.contains(${e.field}, ${Dy(e)})`,fieldContains:e=>`${e.field}.contains(${Dy(e)})`,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Dy(e)})`,startsWith:e=>`${e.field}.startsWith(${Dy(e)})`,endsWith:e=>`${e.field}.endsWith(${Dy(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Dy(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Dy(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Dy(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Dy(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Dy(e)})`},Ay=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),jy=e=>Array.isArray(e)?e:[e],My=`default`;var Ny=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,Ey.And()),this.Or=(e,t={})=>this.withExpression(e,t,Ey.Or()),this.Not=(e,t={})=>this.withExpression(e,t,Ey.Not())}withExpression(e,t={},n=Ey.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=My)=>{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 Ey;return t&&wy.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Ay(t,i),My)}else o(e,My)}else typeof e==`string`?o(e,My):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 Ey&&n[t-1]instanceof Ey)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof Ey?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Py=class{constructor(e){this.serialiser=ky.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 Fy=(e=`rapid`)=>T`<${e}-segmented-control :value="${xf(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>`,Iy=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Ny,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(jy(i).map(e=>jy(n).map(t=>new Py().withField(t).withValue(e).withSerialiser(r).build())),{join:Ey.Or()}):t.And(new Py().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],Iy.prototype,`criteriaOptions`,void 0),q([C],Iy.prototype,`prefix`,void 0),q([C],Iy.prototype,`value`,void 0),q([C],Iy.prototype,`selectedLabel`,void 0),Iy=q([$e({name:`criteria-segmented-control`,template:Fy(),styles:O``})],Iy);function Ly(e,t){let n=new Ny;n.withExpression(new Py().withField(e.labelField??e.valueField).withValue(t).withSerialiser(ky.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Ry(e,t){let n=new Ny;n.withExpression(new Py().withField(e.valueField).withValue(t).withSerialiser(ky.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let zy=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,By=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>`,Vy=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>`,Hy=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Sy(e))}</div>`;var Uy=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 By(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],Vy(e)):By(e)}};q([C],Uy.prototype,`actions`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],Uy.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],Uy.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],Uy.prototype,`autoCloseOnAction`,void 0),q([C],Uy.prototype,`classNames`,void 0),q([C],Uy.prototype,`definition`,void 0),q([D],Uy.prototype,`name`,void 0),q([D({attribute:`open`,mode:`boolean`})],Uy.prototype,`open`,void 0),q([D],Uy.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],Uy.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],Uy.prototype,`hideMenuSingleOption`,void 0),q([C],Uy.prototype,`singleOption`,void 0),Uy.compose({baseName:`actions-menu`,styles:Nne,template:Hy});let Wy=()=>{};function Gy(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:Wy};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 Ky=!1;try{typeof GENX_ENABLE_AI<`u`&&(Ky=GENX_ENABLE_AI===`true`)}catch{}let qy=()=>Ky||kf(`ai`),Jy=Vd(`foundation-ai`);function Yy(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function Xy(e,t){if(!Yy())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 Zy=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 Qy=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`]),new Map(Object.entries(Qy).map(([e,t])=>[t.toLowerCase(),e]));var $y=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 eb=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,tb=e=>{try{return JSON.parse(e)}catch{return}},nb=e=>{let t=e?.code;return typeof t==`string`?t:void 0},rb=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,ib=e=>typeof e==`boolean`?e:void 0,ab=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function ob(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 $y(e,rb(r.budgetUsd)??rb(i.budgetUsd),rb(r.spentUsd)??rb(i.spentUsd),a,{otherVendorAvailable:ib(r.otherVendorAvailable)??ib(i.otherVendorAvailable),serverVendor:ab(r.vendor)??ab(i.vendor)})}var sb=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 cb=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),lb=Object.freeze([`authentication_error`,`permission_error`]);function ub(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 db(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 fb(e){let t=ub(e);if(t?.type){if(lb.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function pb(e,t,n){if(t===`PROVIDER_REFUSED`)return db(n)??fb(n)??`spend`;if(e!==`anthropic`)return;let r=fb(n);if(r)return r;let i=ub(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(cb.some(t=>t.test(e)))return`spend`}}function mb(e,t,n,r,i){let a=ub(r);return new sb(e,t,n,a?.type,a?.message??i)}function hb(e){return Object.entries(Qy).find(([,t])=>t===e)?.[0]}let gb=[`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`],_b=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`];function vb(e){return e===`image/jpg`?`image/jpeg`:e}function yb(e){return e.replace(/^data:[^,]*;base64,/,``)}let bb=.5;function xb(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=bb?r/bb*t:t+(r-bb)/.5*(n-t)}let Sb=1e6,Cb={"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 wb(e){return Cb[e]}function Tb(e,t){let{promptPerMillion:n,candidatePerMillion:r}=wb(e),i=Sb,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 Eb={"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 Db(e,t){let n=Eb[e];return n.kind===`flat`?n.rate:t>2e5?n.longContext:n.standard}function Ob(e,t){let{promptPerMillion:n,candidatePerMillion:r}=Db(e,t.promptTokens),i=Sb,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 kb=[`properties`,`patternProperties`,`$defs`,`definitions`],Ab=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],jb=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Mb=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Nb(e){if(Array.isArray(e))return e.map(Nb);if(Mb(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nb(r);return t}return e}function Pb(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=kb.includes(i)&&Mb(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Mb(r)?t(r,`${e}/${n}`):Nb(r)])):Ab.includes(i)&&Array.isArray(a)?a.map((n,r)=>Mb(n)?t(n,`${e}/${r}`):Nb(n)):jb.includes(i)?Mb(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Mb(n)?t(n,`${e}/${r}`):Nb(n)):Nb(a):Nb(a)}return r}function Fb(e,t,n=``){return t(Pb(e,(e,n)=>Fb(e,t,n),n),n)}let Ib=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Lb=[`oneOf`,`not`];function Rb(e){let t=[],n=[],r=[];return{schema:Fb(e,(e,i)=>{for(let n of Ib)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 Lb)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Mb(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function zb(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Rb(e);return r.length&&Jy.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&Jy.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&&Jy.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 Bb=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Vb(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Mb(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Mb(n)?n:void 0}function Hb(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=Vb(e,o);if(!t)break;let{$ref:n}=i,r=gd(i,[`$ref`]);i=Object.assign(Object.assign({},Nb(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),Pb(i,t=>Hb(e,t,a,r),``)}function Ub(e){let t=[],n=Hb(e,e,/* @__PURE__ */ new Set,t);return t.length&&Jy.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.`),Fb(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(Mb),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 Bb)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}function Wb(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 Gb(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 Kb=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`}),qb=new Set(Object.values(Kb));function Jb(e){return typeof e==`string`&&qb.has(e)?e:void 0}let Yb=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),Xb=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},Zb=e=>e?.code!==void 0;function Qb(e,t,n){if(e!==401&&e!==403||Zb(t))return;let r=typeof n==`string`&&n.trim()===``;if(Xb(t)||r)return e===401?Yb.SIGNED_OUT:Yb.ACCESS_DENIED}function $b(e,t){return e===413&&t===void 0}function ex(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let tx=`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:tx,FALLBACKS_NOT_SUPPORTED:tx,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 nx=e=>e!==Kb.VENDOR_UNREACHABLE;var rx=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 nx(this.code)}};function ix(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let ax=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]),ox=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var sx=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 cx(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 lx(e,t,n){if(t===400)for(let e of cx(n)){if(!ax.some(t=>t.test(e)))continue;let t=ox.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function ux(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 dx=12e4,fx=1e3;function px(e){let t=(e?.get)?.call(e,`x-should-retry`);return typeof t==`string`&&t.trim().toLowerCase()===`false`}function mx(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*fx);let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function hx(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*fx}}}function gx(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 _x(e,t){return Math.max(0,e-t)}function vx(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=hb(o),p=(e,t,n)=>(Jy.error(`${o}Transport: the AI service refused the request (${t} ${e})${n?`: ${n}`:``}`),new rx(o,e,t,n)),m=0,h=(e,t)=>{let n=u*2**e,r=dx-m,i=gx(e,u,t,r);return m+=_x(i,n),t!=null&&i>n?Jy.warn(`${o}Transport: honouring the server's requested retry delay (${Math.round(i)}ms, asked ${Math.round(t)}ms)`):t!=null&&t>n&&Jy.warn(`${o}Transport: declining the server's requested retry delay (asked ${Math.round(t)}ms; the ${dx}ms sequence allowance is spent) — using the ladder's ${Math.round(i)}ms`),Gb(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}=Gy([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=tb(t),r=pb(f,nb(n),n);if(r)throw mb(o,r,c.status,n,t||void 0);let i=lx(f,c.status,n);if(i)throw new sx(o,i.promptTokens,i.limitTokens,i.message??(t||void 0));if(eb(c.status,nb(n)))throw ob(o,n,t||void 0);let a=Jb(nb(n));if(a&&a!==Kb.VENDOR_UNREACHABLE)throw p(a,c.status,ix(n));let l=Qb(c.status,n,t);if(l)throw p(l,c.status,ex(n)??(t||void 0));if($b(c.status,n))throw p(Kb.REQUEST_TOO_LARGE,c.status,t||void 0);let u=px(c.headers);if(s.includes(c.status)&&!u&&e<5){Jy.warn(`${o}Transport: retryable status ${c.status}, retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,mx(c.headers)||hx(n));continue}throw a?p(a,c.status,ix(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 ux(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=pb(f,t.code,t);if(n)throw mb(o,n,t.status,t,t.error);let r=lx(f,t.status,t);if(r)throw new sx(o,r.promptTokens,r.limitTokens,r.message??t.error);if(eb(t.status,t.code))throw ob(o,t);let i=Jb(t.code);if(i&&i!==Kb.VENDOR_UNREACHABLE)throw p(i,t.status,ix(t));if(s.includes(t.status)&&e<5){Jy.warn(`${o}Transport: retryable status ${t.status} (err frame), retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,hx(t));continue}throw i?p(i,t.status,ix(t)):Error(`${o} request error ${t.status}: ${t.error??JSON.stringify(t.details)}`)}return yield c.json()}catch(e){throw Wb(e,u.signal,d)}finally{clearTimeout(y),x()}}throw Error(`${o} request failed: max retries exceeded`)})}function yx(e){if(e&&e!==`auto`)return e===`required`?{type:`any`}:e===`none`?{type:`none`}:{type:`tool`,name:e.tool}}let bx={"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},xx=`emit_structured_response`;function Sx(e){if(!_b.includes(e))throw Error(`AnthropicTransport: unsupported model "${e}". Use one of: ${_b.join(`, `)}.`)}function Cx(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-opus-4-7`||e===`claude-sonnet-5`}function wx(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`||e===`claude-haiku-4-5-20251001`}function Tx(e){return e!==`claude-haiku-4-5-20251001`}function Ex(e){return e===`claude-fable-5`}function Dx(e,t){let n=e===`claude-sonnet-5`||Ex(e),r={type:`adaptive`,display:`summarized`};return t===`off`?Ex(e)?r:n?{type:`disabled`}:void 0:t===`auto`||t!==void 0?Tx(e)?r:void 0:n?r:void 0}function Ox(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`}let kx={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Ax(e,t){if(t!==void 0&&t!==`auto`&&t!==`off`&&Ox(e)&&Tx(e))return kx[t]}let jx=`anthropic`;var Mx=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`}},Nx=class e{warnIfThinkingUnclampable(e){if(this.warnedThinkingClamped)return;let t=this.clampWarning(e);t&&(this.warnedThinkingClamped=!0,Jy.warn(t))}clampWarning(e){switch(e){case void 0:return;case`off`:return Ex(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 Tx(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!Tx(this.model)||!Ox(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`;Sx(t),this.model=t,t===`claude-sonnet-5`?Jy.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`?Jy.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`?Jy.warn(`AnthropicTransport: using ${t} — significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`):t===`claude-fable-5`&&Jy.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:bx[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&&wx(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:xx,description:`Emit the structured response that matches the required schema.`,input_schema:r}],a.tool_choice={type:`tool`,name:xx}),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===xx);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?zb(e.parameters,e.name):e.parameters},e.enforceSchema?{strict:!0}:{}))),a.tools?.length){let e=yx(n?.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingUnclampable(n?.thinkingPolicy);let o=Dx(this.model,n?.thinkingPolicy);o&&(a.thinking=o);let s=Ax(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&&!Cx(this.model)&&!c&&(a.temperature=xb(n.temperature,{defaultTemp:1,maxTemp:1})),n?.responseSchema&&wx(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}=Tb(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:vb(r.mimeType),data:yb(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:vb(e.mimeType),data:yb(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?.[jx];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:_b.includes(t)?t:(this.warnedUnknownServingModels.has(t)||(this.warnedUnknownServingModels.add(t),Jy.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),{[jx]:e})}if(e.stop_reason===`max_tokens`&&l.length>0)throw new Mx(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 vx({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:Qy.anthropic,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};Nx.TOKENS_PER_MILLION=1e6,Nx.COST_DECIMAL_PLACES=6,Nx.RATE_LIMIT_STATUS=429,Nx.SERVICE_UNAVAILABLE_STATUS=503,Nx.OVERLOADED_STATUS=529,Nx.RETRYABLE_STATUSES=[Nx.RATE_LIMIT_STATUS,Nx.SERVICE_UNAVAILABLE_STATUS,Nx.OVERLOADED_STATUS],Nx.BACKOFF_BASE_MS=1e3;let Px=`default_api.`,Fx=/print\(\s*$/;var Ix=class{constructor(e){this.src=e,this.pos=0}parse(){let e=this.src.indexOf(Px);e===-1&&this.bail();let t=Fx.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(Px);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 Lx(e,t){if(!e)return null;let n;try{n=new Ix(e).parse()}catch{return null}return t.has(n.name)?n:null}let Rx=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,zx={"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 Bx(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Vx(e){if(!gb.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${gb.join(`, `)}.`)}let Hx={"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.`},Ux=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],Wx=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],Gx=[`minimal`,`low`,`medium`,`high`],Kx={"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 qx(e,t){if(!e?.length||e.includes(t))return t;let n=Gx.indexOf(t),r=e=>Math.abs(Gx.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let Jx={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},Yx=e=>e!==void 0&&e!==`auto`&&e!==`off`;function Xx(e,t){if(Yx(t)){let n=Kx[e];if(n)return{includeThoughts:!0,thinkingLevel:qx(n,Jx[t])}}return t===`off`&&Ux.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&Ux.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let Zx=`gemini`;function Qx(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:vb(r.mimeType),data:yb(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var $x=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},eS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!Ux.includes(this.model)){this.warnedThinkingClamped=!0,Jy.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(Yx(e)){let t=Kx[this.model];if(!t){this.warnedThinkingClamped=!0,Jy.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=Jx[e],r=qx(t,n);r!==n&&(this.warnedThinkingClamped=!0,Jy.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`;Vx(t),this.model=t;let n=Hx[t];n&&Jy.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:zx[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:Ub(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Bx(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:Xx(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&&Wx.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=xb(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:Ub(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=Ob(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:vb(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?.[Zx],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}=Qx(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}=Qx(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:{[Zx]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=Lx(c.finishMessage,t);if(!e)throw new $x(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 Mx(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};Jy.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:`${Rx(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 vx({url:r,headers:a,body:i,credentials:o,vendorLabel:Qy.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}};eS.TOKENS_PER_MILLION=1e6,eS.COST_DECIMAL_PLACES=6,eS.RATE_LIMIT_STATUS=429,eS.SERVICE_UNAVAILABLE_STATUS=503,eS.BAD_GATEWAY_STATUS=502,eS.RETRYABLE_STATUSES=[eS.RATE_LIMIT_STATUS,eS.SERVICE_UNAVAILABLE_STATUS,eS.BAD_GATEWAY_STATUS],eS.BACKOFF_BASE_MS=1e3;var tS=class e{constructor(){this.noopProvider=new Zy}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}]})}};tS.DEFAULT_NAME=`default`;let nS=N.createInterface(e=>e.singleton(tS)),rS=6e4,iS=3e5;Object.freeze({anthropic:Object.freeze({low:Object.freeze({model:`claude-haiku-4-5-20251001`,maxTokens:16e3,stallTimeoutMs:rS,timeoutMs:iS}),high:Object.freeze({model:`claude-sonnet-5`,maxTokens:128e3,stallTimeoutMs:rS,timeoutMs:iS}),reasoning:Object.freeze({model:`claude-opus-4-8`,maxTokens:32e3,stallTimeoutMs:rS,timeoutMs:iS})}),gemini:Object.freeze({low:Object.freeze({model:`gemini-3.1-flash-lite`,stallTimeoutMs:rS,timeoutMs:iS}),high:Object.freeze({model:`gemini-3.8-flash`,stallTimeoutMs:rS,timeoutMs:iS}),reasoning:Object.freeze({model:`gemini-3.1-pro-preview`,stallTimeoutMs:rS,timeoutMs:iS})})});let aS=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)}`,oS=e=>T` ${A(()=>qy(),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=${xf(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 sv(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
|
-
`};aw.compose(Object.assign({baseName:`checkbox`,template:rw,styles:iw,shadowOptions:void 0},ow));let sw=(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)}`,cw=(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 lw,uw,dw=class extends fu{constructor(){super(...arguments),lw.set(this,void 0),uw.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,GC.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 JC)?.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(by(e,this)){this.open=!1;return}if(xy(e,this.indicator)){this.open=!this.open,this.open&&this.control.focus();return}if(!(this.ignoreInputClick&&xy(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,uw,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,uw,`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,lw,`f`)||wd(this,lw,this.shadowRoot.querySelector(`[part="indicator"]`),`f`),Cd(this,lw,`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 JC);if(t.length>0){let n=t[0];e==null||e===``?n.criteria=n.baseCriteria||``:Ly(n,e),x.queueUpdate(()=>{this.control.value=e})}else vy.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)}};lw=/* @__PURE__ */ new WeakMap,uw=/* @__PURE__ */ new WeakMap,q([C],dw.prototype,`activeDescendant`,null),q([C],dw.prototype,`slottedDatasource`,void 0),q([D({mode:`boolean`})],dw.prototype,`async`,void 0),q([D],dw.prototype,`debounce`,void 0),q([D({mode:`boolean`,attribute:`case-sensitive`})],dw.prototype,`caseSensitive`,void 0),q([D({mode:`boolean`,attribute:`ignore-input-click`})],dw.prototype,`ignoreInputClick`,void 0),q([D({attribute:`filter-mode`})],dw.prototype,`filterMode`,void 0),q([D({mode:`boolean`,attribute:`scroll-to-selected-when-opening`})],dw.prototype,`scrollToSelectedWhenOpening`,void 0),q([C],dw.prototype,`scrollToSelectedWhenOpeningOptions`,void 0),q([D({mode:`boolean`,attribute:`scroll-when-selection-changes`})],dw.prototype,`scrollWhenSelectionChanges`,void 0),q([C],dw.prototype,`scrollWhenSelectionChangesOptions`,void 0);let fw={delegatesFocus:!0,mode:`open`},pw={indicator:`
|
|
268
|
+
`};aw.compose(Object.assign({baseName:`checkbox`,template:rw,styles:iw,shadowOptions:void 0},ow));let sw=(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)}`,cw=(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 lw,uw,dw=class extends fu{constructor(){super(...arguments),lw.set(this,void 0),uw.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,GC.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 JC)?.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(by(e,this)){this.open=!1;return}if(xy(e,this.indicator)){this.open=!this.open,this.open&&this.control.focus();return}if(!(this.ignoreInputClick&&xy(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,uw,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,uw,`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,lw,`f`)||wd(this,lw,this.shadowRoot.querySelector(`[part="indicator"]`),`f`),Cd(this,lw,`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 JC);if(t.length>0){let n=t[0];e==null||e===``?n.criteria=n.baseCriteria||``:Ly(n,e),x.queueUpdate(()=>{this.control.value=e})}else vy.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)}};lw=/* @__PURE__ */ new WeakMap,uw=/* @__PURE__ */ new WeakMap,q([C],dw.prototype,`activeDescendant`,null),q([C],dw.prototype,`slottedDatasource`,void 0),q([D({mode:`boolean`})],dw.prototype,`async`,void 0),q([D],dw.prototype,`debounce`,void 0),q([D({mode:`boolean`,attribute:`case-sensitive`})],dw.prototype,`caseSensitive`,void 0),q([D({mode:`boolean`,attribute:`ignore-input-click`})],dw.prototype,`ignoreInputClick`,void 0),q([D({attribute:`filter-mode`})],dw.prototype,`filterMode`,void 0),q([D({mode:`boolean`,attribute:`scroll-to-selected-when-opening`})],dw.prototype,`scrollToSelectedWhenOpening`,void 0),q([C],dw.prototype,`scrollToSelectedWhenOpeningOptions`,void 0),q([D({mode:`boolean`,attribute:`scroll-when-selection-changes`})],dw.prototype,`scrollWhenSelectionChanges`,void 0),q([C],dw.prototype,`scrollWhenSelectionChangesOptions`,void 0);let fw={delegatesFocus:!0,mode:`open`},pw={indicator:`
|
|
269
269
|
<svg
|
|
270
270
|
class="combo-box-indicator"
|
|
271
271
|
part="combo-box-indicator"
|