@genesislcap/foundation-rapid-cdn 15.98.1 → 15.98.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.
@@ -244,7 +244,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
244
244
  /*! js-cookie v3.0.7 | MIT */
245
245
  function cy(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 ly={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 uy(e,t){function n(n,r,i){if(typeof document<`u`){i=cy({},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,``,cy({},t,{expires:-1}))},withAttributes:function(e){return uy(this.converter,cy({},this.attributes,e))},withConverter:function(e){return uy(cy({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var dy=uy(ly,{path:`/`});let fy=N.createInterface();function py(){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 my(e=``,t=`:`,n){return e.split(t,n).map(e=>e.trim()).filter(e=>e!==``)}function hy(e,t=`:`){let n=typeof e==`string`&&e.trim();return n?n.includes(t):!1}function gy(e,t=`:`){return typeof e==`string`&&e.trim()?(e.match(new RegExp(t,`g`))||[]).length:0}function _y(e,t=`:`){for(let n of e)if(hy(n,t))return n;return e.find(e=>typeof e==`string`&&e.trim()!==``)}function vy(e,t,n){let r=typeof e==`string`&&e.trim();return!r||n&&!r.includes(n)||gy(r)>1?n&&t&&n!==t?`${t}:${n}`:t||n:r}function yy(e=`credential`){Y.warn(`Unable to migrate legacy ${e} to latest format. Please remove from your browser.`)}let by={password:!0,mediation:`optional`},xy={cookie:{path:`/`,name:`credentials`,expires:7300,storePasswords:!1}},Sy=class{constructor(e,t=xy){this.session=e,this.config=t}createBasicCredentials(e){return{type:Ag.BASIC,username:e.username,password:e.password,mfaToken:this.getMFAToken()}}createRefreshCredentials(e){return{type:Ag.REFRESH,username:e?.username??this.getUsername(),refreshToken:e?.refreshToken??this.getRefreshToken(),mfaToken:e?.mfaToken??this.getMFAToken()}}createSSOCredentials(e){return{type:Ag.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(`:`)&&gy(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]=my(t.name||t.id),[r,i]=my(_y([t.id,t.name]));return[{id:vy(t.id||t.name,n,i),name:n,password:t.password||``},!0]}catch{yy(`PasswordCredential`)}if(t)try{let e=t,[n]=my(e.name||e.username||e.organisation),[r,i]=my(_y([e.organisation||e.username||e.name]));return[{id:vy(e.id||e.username||e.name,n,i),name:n,password:e.password||``},!1]}catch{yy(`cookie`)}return[void 0,!1]}storeCredentialsInContainer(e){return J(this,void 0,void 0,function*(){if(!py())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=by){if(py())return Y.debug(`Getting credentials from CredentialsContainer`),yield navigator.credentials.get(e)})}storeCredentialsInCookie(e){let{password:t}=e,n=nd(e,[`password`]),r=this.config.cookie.storePasswords?e:n;return Y.debug(`Storing credentials in cookie`),!!dy.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=dy.get(this.config.cookie.name);return e?JSON.parse(e):void 0}storeCredentials(e){return J(this,void 0,void 0,function*(){if(py()){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 py()?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(){dy.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 py()&&navigator.credentials.preventSilentAccess()}};Sy=q([rd(0,Tg),rd(1,It(fy))],Sy);let Cy=N.createInterface(e=>e.singleton(Sy)),wy=e=>e?{date:e.DATE}:null,Ty=e=>e?e.map(e=>({name:e.NAME,version:e.VERSION})):[],Ey=e=>Array.isArray(e)?e.map(e=>e??``):[],Dy=e=>{try{if(e?.MESSAGE_TYPE===`EVENT_LOGIN_AUTH_ACK`){let{DETAILS:t}=e,n=e.UPDATE_QUEUE_DETAILS;return{messageType:e.MESSAGE_TYPE,sourceRef:e.SOURCE_REF,userName:e.USER_NAME,updateQueue:n?.UPDATE_QUEUE,zeroMqProxyModeEnabled:n?.ZERO_MQ_PROXY_MODE_ENABLED,zeroMqProxyInboundPort:n?.ZERO_MQ_PROXY_INBOUND_PORT,zeroMqProxyOutboundPort:n?.ZERO_MQ_PROXY_OUTBOUND_PORT,userKVs:e.USER,details:t?{system:wy(t.SYSTEM),heartbeatIntervalSecs:t.HEARTBEAT_INTERVAL_SECONDS,failedLoginAttempts:t.FAILED_LOGIN_ATTEMPTS,rejectedLoginAttempts:t.REJECTED_LOGIN_ATTEMPTS,lastLoginDatetime:t.LAST_LOGIN_DATE_TIME,daysToPasswordExpiry:t.DAYS_TO_PASSWORD_EXPIRY,product:Ty(t.PRODUCT)}:null,permission:Ey(e.PERMISSION),profile:Ey(e.PROFILE)}}throw Error(`No Entity mapping implementation for provided DTO`)}catch(e){throw Y.error(e),e}},Oy=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 Mm(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 jg(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(Dy(n)),this.session.setAuthResult(n),Y.debug(`Login Authentication Result:`,gg(n))}catch(e){if(Y.error(lg(`Login Authentication Error:`,e?.received),_g(e)),e instanceof jg&&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===Mg.LOGOUT_NACK;c&&Y.warn(`Unexpected Logout NACK received during logout.`,s),e={success:a===Mg.LOGOUT_ACK||n===Pg.SESSION_NOT_FOUND||!c,error:s},o&&window.open(o,`_self`)}catch(t){let n=new jg(t.sentMessage,t.receivedMessage);if(Y.error(lg(`Logout Authentication Error:`,n.received),_g(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===Ng.EVENT_LOGIN_AUTH_ACK)return this.session.setAuthResult(t),this.currentUser.set(Dy(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],Oy.prototype,`isWorking`,void 0),q([C],Oy.prototype,`loggedUserResult`,void 0),Oy=q([rd(0,Tg),rd(1,ay),rd(2,zg),rd(3,Cy),rd(4,ng)],Oy);let ky=N.createInterface(e=>e.singleton(Oy));function Ay(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`)}`}let jy={n:`
246
246
  `,r:`\r`,t:` `,b:`\b`,f:`\f`};function My(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2].replace(/\\([\s\S])/g,(e,t)=>jy[t]??t):t}function Ny(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`]=My(r)}break}case`dateTimeIsLessEqual`:{let n=e.match(/Expr\.dateTimeIsLessEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=My(r)}break}case`dateIsGreaterEqual`:{let n=e.match(/Expr\.dateIsGreaterEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_FROM`]=My(r)}break}case`dateIsLessEqual`:{let n=e.match(/Expr\.dateIsLessEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=My(r)}break}case`containsIgnoreCase`:{let n=e.match(/Expr\.containsIgnoreCase\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[e]=`*${My(r)}*`}break}}}function Py(e,t){let n=e.indexOf(`=`),r=e.substr(0,n).trim().replace(/["']/g,``);t[r]=My(e.slice(n).replace(/^==?/,``))}function Fy(e){if(!e)return{};let t=e.split(`&&`).map(e=>e.trim()),n={};return t.forEach(e=>{if(e){if(e.startsWith(`Expr`))Ny(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`]=Ay(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`]=Ay(i,o)}}else Py(e,n)}}),n}function Iy(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 Ly=class{};Ly.MAX_ROWS_250=250,Ly.MAX_VIEW_1000=1e3,Ly.REQ_REP_POLLING_INTERVAL_MS=1e4,Ly.DATASERVER_ROW_ID=`ROW_REF`,Ly.REQUEST_SERVER_ROW_ID=`RECORD_ID`,Ly.DEFAULT_PAGINATION_PAGE_SIZE=25,Ly.DEFAULT_REQ_REP_OFFSET=0;let Ry={options:{criteria:``,isSnapshot:!1,maxRows:Ly.MAX_ROWS_250,maxView:Ly.MAX_VIEW_1000,pollingInterval:Ly.REQ_REP_POLLING_INTERVAL_MS,movingView:!1,orderBy:``,resourceName:``,reverse:!1,pollTriggerEvents:[]},criteriaToFields:Fy,dataServerResultFilter:Iy},zy=N.createInterface(e=>e.instance(Ry));function By(e){let t=e==null?NaN:Number(e);return Number.isFinite(t)?t===0?1/0:t:Ly.MAX_VIEW_1000}function Vy(e){return e.moreRows===!1?`end`:e.rowsHeld>=By(e.maxView)?e.movingView?`more`:`view-full`:e.emptyReply?`stalled`:`more`}function Hy(e){let t=By(e.maxView),n=Uy(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 Uy(e){return e==null||!Number.isFinite(Number(e))}let Wy=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(og,this.onDatasourceStatusChanged,{passive:!0,capture:!0})}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(og,this.onDatasourceStatusChanged,{capture:!0})}}return q([C],t.prototype,`datasourceStatus`,void 0),t},Gy={throwWhenUnavailable:!0,throwWhenUnknown:!1},Ky=N.createInterface(e=>e.instance(Gy)),qy=jd(`genesis-resources`);function Jy(){return N.getOrCreateDOMContainer().get(qy)}let Yy=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=Jy();e.postMessage(`resources-loaded`,this.resources),e.close()}};Yy=q([rd(0,ay),rd(1,Ky)],Yy);let Xy=N.createInterface(e=>e.singleton(Yy)),Zy=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.generation=0,this.pollTrigger$=new Am}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){let r=this.generation+=1,i=this.initialise(r,e,t,n).catch(t=>{if(r===this.generation)throw t;return Y.debug(`${e?.resourceName} datasource initialisation failed after it was superseded:`,t),this.interruptedInit(e?.resourceName)});return this.latestInit={generation:r,result:i},i})}initialise(e,t,n,r){return J(this,void 0,void 0,function*(){this.fetchMetadataRequired=n,this.options=Object.assign(Object.assign({},this.config.options),t),this.invalidateCache();let{resourceName:i}=this.options,a=()=>e!==this.generation,o=this.connect.isConnected||(yield this.connect.connect(this.connect.host));if(a())return this.interruptedInit(i);if(!o)return Y.error(`Unable to connect to ${this.connect.host} to get ${i} datasource`),this.reportStatus(),!1;let s=yield this.resources.isValidResource(i);if(a())return this.interruptedInit(i);if(!s)return Y.error(`${i} datasource does not exist on ${this.connect.host}`),this.reportStatus(),!1;let c=yield this.resources.getResourceTypeFor(i);if(a())return this.interruptedInit(i);if(this.resourceType=c,!this.resourceType)return Y.error(`Unable to get the resource type for ${i} datasource from ${this.connect.host}`),this.reportStatus(),!1;if(this.fetchMetadataRequired){if(yield this.fetchAndApplyMetadata(i),a())return this.interruptedInit(i);this._allParams=null}return Y.debug(`Initializing ${i} datasource from ${this.connect.host}`),!this.options.isSnapshot&&r&&(this.pollTrigger$=new Am,this.stream=this.createStream()),Y.debug(`${i} datasource initialization ${this.initialized?`was successful.`:`has failed.`}`),this.reportStatus(),this.initialized})}startStream(){return J(this,void 0,void 0,function*(){!this.options.isSnapshot&&this.stream===void 0&&(this.stream=this.createStream())})}destroy(){var e;Y.debug(`Datasource.destroy`,this.options?.resourceName),this.generation+=1,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,ENCODING:this.options.encoding,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,ENCODING:this.allResourceParams.ENCODING}}get requestOnlyParams(){let e=this.allResourceParams,{REQUEST:t}=e,n=nd(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,ENCODING:n.ENCODING},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 ag.DATASERVER:return this.connect.snapshot(this.options.resourceName,Object.assign(Object.assign({},this.dataserverOnlyParams),e));case ag.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(){if(![ag.DATASERVER,ag.REQUEST_SERVER].includes(this.resourceType))throw Error(`Streaming not supported for selected resource type: ${this.resourceType}`);return this.resourceType===ag.DATASERVER?this.createDataserverStream():(Y.debug(`Creating fake stream by polling ${this.options.resourceName} REQUEST_SERVER`),this.createReqRepStream())}createDataserverStream(){let{resourceName:e}=this.options;return this.connect.stream(e,e=>{},t=>Y.error(lg(`${e} stream failed`,t),t),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===ag.REQUEST_SERVER&&this.loadMoreCount>0){let t=(this.options.maxRows||25)*(this.loadMoreCount+1);e.DETAILS.MAX_ROWS=t}return Tie([this.connect.isConnected$,this.auth.isLoggedIn$]).pipe(Th(()=>this.connect.isConnected&&this.auth.isLoggedIn),wh(()=>uh(this.snapshot(e))))};return e?this.pollTrigger$.pipe(Ch(0),wh(()=>vh(0,e).pipe(wh(t)))):this.pollTrigger$.pipe(Ch(0),wh(t))}fetchAndApplyMetadata(e){return J(this,void 0,void 0,function*(){let t=this.generation;try{Y.debug(`Requesting metadata for ${e} Datasource`);let n=yield this.connect.getMetadata(e);if(t!==this.generation)return;n&&(this.availableIndexes=n.INDEXES??[],this.availableSortableFields=n.SORTABLE_FIELDS??[],this.availableCriteriaFields=n.CRITERIA_FIELDS??[],this.originalFieldDef=cg(n),this.fieldMetadata=sg(this.originalFieldDef),this.requestFields=n.REQUEST_FIELD||[],this.customRequestFields=n.FIELD||[],this.criteriaOnlyRequest=n.CRITERIA_ONLY_REQUEST||!1,this.fetchMetadataRequired=!1),this.status=this.normaliseStatus({isInitialized:!0,metadataRequired:!0,hasMetadata:this.fieldMetadata?.length>0})}catch(n){if(t!==this.generation){Y.debug(`Metadata Fetch for ${e} failed after it was superseded:`,n);return}Y.error(lg(`Metadata Fetch failed for ${e}:`,n),n),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 '${og}'`,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}interruptedInit(e){Y.debug(`${e} datasource initialisation was superseded`);let t=this.latestInit;return t&&t.generation===this.generation?t.result:!1}};q([C],Zy.prototype,`status`,void 0),q([C],Zy.prototype,`fetchMetadataRequired`,void 0),q([C],Zy.prototype,`startStreamRequired`,void 0),q([C],Zy.prototype,`originalFieldDef`,void 0),q([C],Zy.prototype,`fieldMetadata`,void 0),q([C],Zy.prototype,`requestFields`,void 0),q([C],Zy.prototype,`customRequestFields`,void 0),q([C],Zy.prototype,`availableIndexes`,void 0),q([C],Zy.prototype,`availableSortableFields`,void 0),q([C],Zy.prototype,`availableCriteriaFields`,void 0),q([C],Zy.prototype,`criteriaOnlyRequest`,void 0),q([C],Zy.prototype,`loadMoreCount`,void 0),q([C],Zy.prototype,`readOnly`,void 0),q([C],Zy.prototype,`stream`,void 0),Zy=q([rd(0,ay),rd(1,ky),rd(2,Xy),rd(3,zy),rd(4,Cg)],Zy);let Qy=N.createInterface(e=>e.transient(Zy));var $y=class extends Zy{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===Mg.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($y));function eb(e,t=`;`){return e&&e.split(t).map(e=>e.trim()).sort((e,t)=>e.localeCompare(t)).join(t)}let tb=`system-health-changed`,nb={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 oy().getMoreColumns(e),n=Date.now(),r=t;return{isConnected:t.MESSAGE_TYPE===Mg.MORE_COLUMNS_ACK,lastUpdated:n,lastMessage:r}}),resourceDataLogon:({message:e,functions:t})=>{let{onMessage:n,onError:r}=t;$v().sendForStream(e,n,r)}},rb=N.createInterface(e=>e.instance(nb));var ib=/* @__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}})}))})),ab=/* @__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)}}})),ob=/* @__PURE__ */ u(ib()),sb=/* @__PURE__ */ u(ab());let cb=kd(`network-monitor`,{level:_d.info}),lb=Date.now(),ub=window.navigator?.userAgent?ob.default.parse(window.navigator.userAgent):void 0,db=(e,t={depthLimit:10,edgesLimit:10})=>e instanceof Event?`'${e.type}' Event`:typeof e==`string`?e:(0,sb.default)(e,void 0,2,t);var fb=class{constructor(){this.unsubscribableObservers=[],this.runAllChecks=(e,t)=>J(this,void 0,void 0,function*(){if(!this.isReady||this.isRunningChecks&&!t)return;cb.info(`Run health checks, triggered by`,db(e),`| Active resources`,this.resources.size),this.isRunningChecks=!0,this.synchroniseCheckInterval();let n=this.getFormattedTimestamp(this.getNowTimestamp()),r=yield this.isOnlineCheck();r?cb.debug(`Network connected at ${n}`):cb.warn(`Network disconnected at ${n}`);let i=this.normaliseSerializedSocketStatus(this.socketStatus.serialize(),r),a=this.preFlightSocketChecks(i);if(a||cb.debug(`Socket pre-flight checks failed`),!r||!a){cb.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{cb.debug(`Running health check against ${r}`);let e=yield Promise.race([c(u,t),Vf(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===Mg.MSG_NACK||Lg(p,ug.NOT_FOUND),n=this.getFormattedTimestamp(f??this.getNowTimestamp()),d?cb.debug(`${r} is healthy at ${n}`):cb.warn(`${r} is not healthy at ${n}`),p&&cb.debug(`${r} messaged at ${n}`,db(p)),m&&cb.error(`${r} errored at ${n}`,db(m)),h&&cb.warn(`${r} timed out at ${n}`),g&&(cb.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 cb.warn(`Unexpected promise rejection occurred. Please check any custom resourceChecks return MonitoredResourceChecksResult.`),e},{});cb.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&&(cb.level=this.config.logLevel)}create(){if(this.resources){cb.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=``;Lg(i,ug.NOT_FOUND)?a=`Please check the resource is running.`:Lg(i,ug.FORBIDDEN)&&(a=`You are not authorised to access this resource, removing it from monitoring.`,this.removeResource(n)),cb.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){cb.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?cb.debug:cb.warn)(`Emitting 'system-health-changed' event`,db(this.status)),t?.dispatchEvent(new CustomEvent(`system-health-changed`,{detail:this.status,bubbles:t!==document,composed:!0})),this.status.socket.reconnectionLimitReached&&(cb.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 cb.debug(`User requested report stability to Genesis.`),cb.info(`Please attach this data to your Genesis Support request:
247
- `,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:ub,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:lb,runAllChecks:()=>{cb.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return cb.debug(`Socket not configured`),!1;if(e.isReconnecting)return cb.debug(`Socket reconnecting`),!1;if(e.isConnecting)return cb.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return cb.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&cb.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return cb.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return jf(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([rb],fb.prototype,`config`,void 0),q([Kv],fb.prototype,`socketStatus`,void 0),q([Cg],fb.prototype,`connectEvents`,void 0),q([ng],fb.prototype,`user`,void 0),q([C],fb.prototype,`status`,void 0);let pb=N.createInterface(e=>e.singleton(fb)),mb={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},hb=N.createInterface();var gb;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(gb||(gb={}));var _b;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(_b||(_b={}));let vb=class{constructor(e,t,n=mb){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(_b.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(gb.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=hf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=hf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=hf(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(gb.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?_f(e.value):e.value}))}},n=yield this.connect.commitEvent(_b.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};vb=q([rd(0,ay),rd(1,ng),rd(2,It(hb))],vb),N.createInterface(e=>e.singleton(vb));var yb=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Mm(!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 tg,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],yb.prototype,`isWorking`,void 0),q([C],yb.prototype,`loggedUserResult`,void 0),q([C],yb.prototype,`currentUser`,void 0),q([C],yb.prototype,`isLoggedIn`,void 0);var bb=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=cg(e),this.fieldMetadata=sg(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=uh(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],bb.prototype,`status`,void 0),q([C],bb.prototype,`fetchMetadataRequired`,void 0),q([C],bb.prototype,`originalFieldDef`,void 0),q([C],bb.prototype,`fieldMetadata`,void 0),q([C],bb.prototype,`requestFields`,void 0),q([C],bb.prototype,`customRequestFields`,void 0),q([C],bb.prototype,`availableIndexes`,void 0),q([C],bb.prototype,`availableSortableFields`,void 0),q([C],bb.prototype,`availableCriteriaFields`,void 0),q([C],bb.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(ng));let xb=kd(`foundation-ui`);var Sb=class extends Wy(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Ly.MAX_ROWS_250,this.maxView=Ly.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 Mm(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==eb(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===ag.REQUEST_SERVER?Ly.REQUEST_SERVER_ROW_ID:Ly.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.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}xb.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?Iy(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Mg.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 ag.REQUEST_SERVER:return!0;case ag.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===ag.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 Iy(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==ag.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=Vy({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=Hy({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&xb.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 eb((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&&xb[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===ig.DATE||t===ig.DATETIME?Mf(e,t===ig.DATETIME):e}};q([ay],Sb.prototype,`connect`,void 0),q([Qy],Sb.prototype,`datasource`,void 0),q([D({mode:`boolean`})],Sb.prototype,`withGridInit`,void 0),q([D],Sb.prototype,`criteria`,void 0),q([C],Sb.prototype,`data`,void 0),q([D],Sb.prototype,`fields`,void 0),q([D({mode:`boolean`})],Sb.prototype,`isSnapshot`,void 0),q([D],Sb.prototype,`maxRows`,void 0),q([D],Sb.prototype,`maxView`,void 0),q([D],Sb.prototype,`orderBy`,void 0),q([D],Sb.prototype,`request`,void 0),q([D],Sb.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],Sb.prototype,`reverse`,void 0),q([D],Sb.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],Sb.prototype,`withTimestampFormatting`,void 0);let Cb=(e,t)=>!e.composedPath().includes(t),wb=(e,t)=>e.composedPath().includes(t),Tb=e=>e.tagName.toLowerCase().split(`-`)[0];function Eb(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let Db=kd(`foundation-criteria`);var Ob;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(Ob||(Ob={}));var kb=class e{constructor(e){this.$$operator=e}static And(){return new e(Ob.AND)}static Or(){return new e(Ob.OR)}static Not(){return new e(Ob.NOT)}static GreaterThan(){return new e(Ob.GT)}static GreaterThanOrEqual(){return new e(Ob.GE)}static LessThan(){return new e(Ob.LT)}static LessThanOrEqual(){return new e(Ob.LE)}static NotEqual(){return new e(Ob.NE)}static Equal(){return new e(Ob.EQ)}get operator(){return this.$$operator}};let Ab=e=>e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`),jb=e=>`'${Ab(e)}'`,Mb=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?jb(t):t},Nb=e=>t=>`${t.field} ${e} ${Mb(t)}`,Pb=e=>Nb(Ob.NE)(e),Fb=e=>`${e.field}.contains(${Mb(e)})`,Ib={AND:e=>Nb(Ob.AND)(e),OR:e=>Nb(Ob.OR)(e),NOT:Pb,GT:e=>Nb(Ob.GT)(e),GE:e=>Nb(Ob.GE)(e),LT:e=>Nb(Ob.LT)(e),LE:e=>Nb(Ob.LE)(e),NE:Pb,EQ:e=>Nb(Ob.EQ)(e),equals:e=>`${e.field}.equals(${Mb(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Mb(e)})`,contains:Fb,fieldContains:Fb,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Mb(e)})`,startsWith:e=>`${e.field}.startsWith(${Mb(e)})`,endsWith:e=>`${e.field}.endsWith(${Mb(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Mb(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Mb(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Mb(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Mb(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Mb(e)})`},Lb=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),Rb=e=>Array.isArray(e)?e:[e],zb=`default`;var Bb=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,kb.And()),this.Or=(e,t={})=>this.withExpression(e,t,kb.Or()),this.Not=(e,t={})=>this.withExpression(e,t,kb.Not())}withExpression(e,t={},n=kb.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=zb)=>{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 kb;return t&&Db.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Lb(t,i),zb)}else o(e,zb)}else typeof e==`string`?o(e,zb):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 kb&&n[t-1]instanceof kb)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof kb?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Vb=class{constructor(e){this.serialiser=Ib.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 Hb=(e=`rapid`)=>T`<${e}-segmented-control :value="${df(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>`,Ub=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Bb,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(Rb(i).map(e=>Rb(n).map(t=>new Vb().withField(t).withValue(e).withSerialiser(r).build())),{join:kb.Or()}):t.And(new Vb().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],Ub.prototype,`criteriaOptions`,void 0),q([C],Ub.prototype,`prefix`,void 0),q([C],Ub.prototype,`value`,void 0),q([C],Ub.prototype,`selectedLabel`,void 0),Ub=q([$e({name:`criteria-segmented-control`,template:Hb(),styles:O``})],Ub);function Wb(e,t){let n=new Bb;n.withExpression(new Vb().withField(e.labelField??e.valueField).withValue(t).withSerialiser(Ib.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Gb(e,t){let n=new Bb;n.withExpression(new Vb().withField(e.valueField).withValue(t).withSerialiser(Ib.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let Kb=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,qb=e=>{let t=/* @__PURE__ */ new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))},Jb=qb(e=>T`<div ${k(`actionsOpener`)}class="actions-opener icon-only${e=>e.open?` opened`:``}" part="icon-opener" role="button" tabindex="0" aria-label="${e=>e.name}" aria-haspopup="menu" aria-expanded="${e=>String(e.open)}" @click=${e=>e.toggleActionsMenuVisibility()}@keydown=${(e,t)=>e.onIconOpenerKeydown(t.event)}><${e}-icon name="${e=>e.iconName}" size="lg"></${e}-icon></div>`),Yb=qb(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>`),Xb=qb(e=>T` ${t=>t.iconName?Jb(e):Yb(e)}<${e}-menu ${k(`actionsMenu`)}popover="${e=>e.isVertical?`auto`:`manual`}" class="actions-menu ${e=>e.classNames}" part="actions-menu" @toggle=${(e,t)=>e.onPopoverToggle(t.event)}>${j(e=>e.allActions,T` ${A((e,t)=>t.parent.isActionDisabled(e),T`<${e}-menu-item class="menu-item" tabindex="${(e,t)=>t.index}" disabled style=${(e,t)=>t.parent.hideDisabled?`display:none`:``}>${A(e=>e.icon,T`<${e}-icon name=${e=>e.icon.name}size=${e=>e.icon.size}variant=${e=>e.icon.variant}slot="start"></${e}-icon>`)} ${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} ${A((e,t)=>!t.parent.isActionDisabled(e),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};`:``}">${A(e=>e.icon,T`<${e}-icon name=${e=>e.icon.name}size=${e=>e.icon.size}variant=${e=>e.icon.variant}slot="start"></${e}-icon>`)} ${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} `,{positioning:!0})}</${e}-menu>`),Zb=qb(e=>T`<${e}-button appearance="${e=>e.buttonAppearance}" part="actions-opener" class="actions-opener" @click=${e=>e?.singleOption.callback(e.rowData)}?disabled=${e=>e.isActionDisabled(e.singleOption)}>${e=>e.getLabel(e?.singleOption.name)}</${e}-button>`),Qb=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Tb(e))}</div>`;var $b=class{constructor(e,t,n){this.anchor=e,this.onReposition=t,this.onAnchorDetached=n,this.check=()=>{if(!this.anchor.isConnected){this.stop(),this.onAnchorDetached();return}let{top:e,right:t,bottom:n}=this.anchor.getBoundingClientRect(),r=`${e},${t},${n},${this.view.innerWidth},${this.view.innerHeight}`;this.lastPosition!==void 0&&r!==this.lastPosition&&(this.onReposition(),!this.view)||(this.lastPosition=r,this.frame=this.view.requestAnimationFrame(this.check))}}start(){this.stop(),this.view=this.anchor.ownerDocument.defaultView,this.view&&this.check()}stop(){var e;this.frame!==void 0&&((e=this.view)==null||e.cancelAnimationFrame(this.frame)),this.frame=void 0,this.lastPosition=void 0,this.view=void 0}},ex=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,this.focusMenuOnOpen=!1}disconnectedCallback(){this.stopTrackingPosition(),this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover(),super.disconnectedCallback()}updateMenuPosition(){let e=this.actionsOpener.getBoundingClientRect(),t=this.actionsMenu;if(t.style.position=`fixed`,t.style.left=`auto`,!this.isVertical){t.style.top=`${e.top}px`,t.style.right=`${window.innerWidth-e.right}px`;return}let{innerHeight:n,innerWidth:r}=window;t.style.maxHeight=`${n}px`;let{width:i,height:a}=t.getBoundingClientRect(),o=a<=n-e.bottom,s=a<=e.top,c=o||!s?e.bottom:e.top-a;t.style.top=`${Fn(0,Math.max(n-a,0),c)}px`,t.style.right=`${Fn(0,Math.max(r-i,0),r-e.right)}px`}startTrackingPosition(){this.positionTracker=new $b(this.actionsOpener,()=>this.updateMenuPosition(),()=>this.open=!1),this.positionTracker.start()}stopTrackingPosition(){var e;(e=this.positionTracker)==null||e.stop(),this.positionTracker=void 0}definitionChanged(e,t){t&&(typeof t.actions==`function`?(this.actionsResolver=t.actions,this.actions=[]):(this.actionsResolver=void 0,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.iconName&&(this.iconName=t.iconName,delete this.definition.iconName),t.addDefaultActions!==void 0&&(this.addDefaultActions=t.addDefaultActions,delete this.definition.addDefaultActions),t.hideDisabled!==void 0&&(this.hideDisabled=t.hideDisabled,delete this.definition.hideDisabled),t.buttonAppearance&&(this.buttonAppearance=t.buttonAppearance,delete this.definition.buttonAppearance),t.hideMenuSingleOption&&(this.hideMenuSingleOption=t.hideMenuSingleOption,delete this.definition.hideMenuSingleOption),this.open&&(this.isVertical&&!this.hasVisibleActions?this.open=!1:x.queueUpdate(()=>this.open&&this.updateMenuPosition())))}openChanged(){var e;if(this.classNames=fn([`visible`,this.open],[`hidden`,!this.open]),this.open)this.updateMenuPosition(),this.actionsMenu.showPopover(),this.startTrackingPosition(),x.queueUpdate(()=>{this.open&&(this.updateMenuPosition(),this.focusMenuOnOpen&&this.actionsMenu.focus(),this.focusMenuOnOpen=!1)});else{this.focusMenuOnOpen=!1,this.stopTrackingPosition();let t=this.actionsMenu?.contains(this.shadowRoot?.activeElement);this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover(),t&&((e=this.actionsOpener)==null||e.focus())}}toggleActionsMenuVisibility(){this.open=!this.open}onPopoverToggle(e){let t=e.newState;t&&(this.open=t===`open`)}onIconOpenerKeydown(e){return e.key!==`Enter`&&e.key!==` `||(this.focusMenuOnOpen=!this.open,this.toggleActionsMenuVisibility(),!1)}onActionMenuItemClick(e){this.autoCloseOnAction&&(this.open=!1),e(this.rowData)}isActionDisabled(e){return!!e.isDisabled?.call(e,this.rowData)}get resolvedActions(){return(this.actionsResolver?this.actionsResolver(this.rowData):this.actions)??[]}get hasVisibleActions(){let e=this.resolvedActions;return this.hideDisabled?e.some(e=>!this.isActionDisabled(e)):e.length>0}get allActions(){let e=[{name:`✖`,callback:()=>this.open=!1}];return this.addDefaultActions?[...this.resolvedActions,...e]:this.resolvedActions}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.isVertical&&!this.hasVisibleActions)return;let t=this.resolvedActions.filter(e=>!this.isActionDisabled(e));if(!this.hideMenuSingleOption)return Xb(e);if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],Zb(e)):Xb(e)}};q([C],ex.prototype,`actions`,void 0),q([C],ex.prototype,`actionsResolver`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],ex.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],ex.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],ex.prototype,`autoCloseOnAction`,void 0),q([C],ex.prototype,`classNames`,void 0),q([C],ex.prototype,`definition`,void 0),q([D],ex.prototype,`name`,void 0),q([D({attribute:`icon-name`})],ex.prototype,`iconName`,void 0),q([D({attribute:`open`,mode:`boolean`})],ex.prototype,`open`,void 0),q([D],ex.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],ex.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],ex.prototype,`hideMenuSingleOption`,void 0),q([C],ex.prototype,`singleOption`,void 0),ex.compose({baseName:`actions-menu`,styles:Jne,template:Qb});let tx=()=>{};function nx(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:tx};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 rx=!1;try{typeof GENX_ENABLE_AI<`u`&&(rx=GENX_ENABLE_AI===`true`)}catch{}let ix=()=>rx||yf(`ai`),ax=kd(`foundation-ai`);function ox(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function sx(e,t){if(!ox())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 cx=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 lx=[`gemini-2.5-pro`,`gemini-2.5-flash`,`gemini-2.5-flash-lite`,`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],ux=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`],dx=[`gpt-6-astra`,`gpt-6.1-sol`,`gpt-6.1-terra`,`gpt-6-sol`,`gpt-6-luna`];function fx(e){return e===`image/jpg`?`image/jpeg`:e}function px(e){return e.replace(/^data:[^,]*;base64,/,``)}let mx=.5;function hx(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=mx?r/mx*t:t+(r-mx)/.5*(n-t)}let gx=1e6,_x={"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 vx(e){return _x[e]}function yx(e,t){let{promptPerMillion:n,candidatePerMillion:r}=vx(e),i=gx,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 bx={"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:`dated`,before:{promptPerMillion:.75,candidatePerMillion:3.75},after:{promptPerMillion:1.5,candidatePerMillion:7.5},switchAtMs:Date.parse(`2027-01-01T00:00:00Z`)},"gemini-4-argon":{kind:`dated`,before:{promptPerMillion:2,candidatePerMillion:10},after:{promptPerMillion:4,candidatePerMillion:20},switchAtMs:Date.parse(`2026-12-01T00:00:00Z`)},"gemini-3.1-pro-preview":{kind:`tiered`,standard:{promptPerMillion:2,candidatePerMillion:12},longContext:{promptPerMillion:4,candidatePerMillion:18}}};function xx(e,t,n=/* @__PURE__ */ new Date){let r=bx[e];return r.kind===`flat`?r.rate:r.kind===`dated`?n.getTime()<r.switchAtMs?r.before:r.after:t>2e5?r.longContext:r.standard}function Sx(e,t,n=/* @__PURE__ */ new Date){let{promptPerMillion:r,candidatePerMillion:i}=xx(e,t.promptTokens,n),a=gx,o=Math.max(0,t.promptTokens-t.cachedTokens)/a*r,s=t.cachedTokens/a*r*.1,c=(t.candidateTokens+t.thoughtTokens)/a*i;return{costUsd:o+s+c,savedUsd:t.cachedTokens/a*r-s,breakdown:{promptUsd:o,cacheReadUsd:s,cacheWriteUsd:0,candidateUsd:c}}}let Cx={"gpt-6-astra":{promptPerMillion:10,cachedPerMillion:1,candidatePerMillion:50},"gpt-6.1-sol":{promptPerMillion:2,cachedPerMillion:.1,candidatePerMillion:10},"gpt-6.1-terra":{promptPerMillion:1,cachedPerMillion:.05,candidatePerMillion:5},"gpt-6-sol":{promptPerMillion:2,cachedPerMillion:.2,candidatePerMillion:10},"gpt-6-luna":{promptPerMillion:.1,cachedPerMillion:.01,candidatePerMillion:.5}};function wx(e,t){let n=Cx[e];return t<=272e3?n:{promptPerMillion:n.promptPerMillion*2,cachedPerMillion:n.cachedPerMillion*2,candidatePerMillion:n.candidatePerMillion*1.5}}function Tx(e,t){let{promptPerMillion:n,cachedPerMillion:r,candidatePerMillion:i}=wx(e,t.inputTokens),a=gx,o=Math.max(0,t.inputTokens-t.cacheReadTokens-t.cacheWriteTokens),s=Math.min(t.cacheWrite12hTokens,t.cacheWriteTokens),c=Math.max(0,t.cacheWriteTokens-s),l=o/a*n,u=t.cacheReadTokens/a*r,d=c/a*n*1.25+s/a*n*2.5,f=t.outputTokens/a*i,p=t.cacheReadTokens/a*n,m=t.cacheWriteTokens/a*n;return{costUsd:l+u+d+f,savedUsd:p-u+(m-d),breakdown:{promptUsd:l,cacheReadUsd:u,cacheWriteUsd:d,candidateUsd:f}}}let Ex=[`properties`,`patternProperties`,`$defs`,`definitions`],Dx=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],Ox=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],kx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ax(e){if(Array.isArray(e))return e.map(Ax);if(kx(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ax(r);return t}return e}function jx(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=Ex.includes(i)&&kx(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,kx(r)?t(r,`${e}/${n}`):Ax(r)])):Dx.includes(i)&&Array.isArray(a)?a.map((n,r)=>kx(n)?t(n,`${e}/${r}`):Ax(n)):Ox.includes(i)?kx(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>kx(n)?t(n,`${e}/${r}`):Ax(n)):Ax(a):Ax(a)}return r}function Mx(e,t,n=``){return t(jx(e,(e,n)=>Mx(e,t,n),n),n)}let Nx=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Px=[`oneOf`,`not`];function Fx(e){let t=[],n=[],r=[];return{schema:Mx(e,(e,i)=>{for(let n of Nx)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 Px)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||kx(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function Ix(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Fx(e);return r.length&&ax.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&ax.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&&ax.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 Lx=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Rx(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!kx(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return kx(n)?n:void 0}function zx(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=Rx(e,o);if(!t)break;let{$ref:n}=i,r=nd(i,[`$ref`]);i=Object.assign(Object.assign({},Ax(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),jx(i,t=>zx(e,t,a,r),``)}function Bx(e){let t=[],n=zx(e,e,/* @__PURE__ */ new Set,t);return t.length&&ax.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.`),Mx(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(kx),n=t.filter(e=>e.type!==`null`);if(t.length===2&&n.length===1){let{anyOf:t}=e,r=nd(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 Lx)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}let Vx=[`allOf`,`not`,`if`,`then`,`else`,`oneOf`];function Hx(e){if(typeof e.type==`string`){let t=Object.assign(Object.assign({},e),{type:e.type===`null`?`null`:[e.type,`null`]});return Array.isArray(e.enum)&&!e.enum.includes(null)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.type)){if(e.type.includes(`null`))return e;let t=Object.assign(Object.assign({},e),{type:[...e.type,`null`]});return Array.isArray(e.enum)&&!e.enum.includes(null)&&(t.enum=[...e.enum,null]),t}return Array.isArray(e.anyOf)?e.anyOf.some(e=>kx(e)&&e.type===`null`)?e:Object.assign(Object.assign({},e),{anyOf:[...e.anyOf,{type:`null`}]}):{anyOf:[e,{type:`null`}]}}function Ux(e){let t=[],n=[],r=[];return{schema:Mx(e,(e,i)=>{for(let t of Vx)t in e&&r.push(`${i}/${t}`);if(!(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||kx(e.properties)))return e;if(e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),kx(e.properties)){let n=Object.keys(e.properties),r=new Set(Array.isArray(e.required)?e.required:[]),a=e.properties;for(let e of n)r.has(e)||(a[e]=kx(a[e])?Hx(a[e]):{type:`null`},t.push(`${i}/properties/${e}`));e.required=n}return e}),madeNullable:t,overridden:n,undroppable:r}}function Wx(e,t){let{schema:n,madeNullable:r,overridden:i,undroppable:a}=Ux(e);return r.length&&ax.debug(`OpenAITransport: tool "${t}" is strict, which has no optional properties; these are now required and nullable, so an absent value arrives as null: ${r.join(`, `)}`),i.length&&ax.warn(`OpenAITransport: tool "${t}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}.`),a.length&&ax.warn(`OpenAITransport: tool "${t}" uses schema keywords strict mode cannot express (${a.join(`, `)}). They are left in place, so the request will be rejected. Rewrite them or drop enforceSchema for this tool.`),n}let Gx=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`,`openai`]),new Map(Object.entries(Gx).map(([e,t])=>[t.toLowerCase(),e]));var Kx=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 qx=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,Jx=e=>{try{return JSON.parse(e)}catch{return}},Yx=e=>{let t=e?.code;return typeof t==`string`?t:void 0},Xx=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Zx=e=>typeof e==`boolean`?e:void 0,Qx=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function $x(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 Kx(e,Xx(r.budgetUsd)??Xx(i.budgetUsd),Xx(r.spentUsd)??Xx(i.spentUsd),a,{otherVendorAvailable:Zx(r.otherVendorAvailable)??Zx(i.otherVendorAvailable),serverVendor:Qx(r.vendor)??Qx(i.vendor)})}function eS(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 tS(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 nS=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`}),rS=new Set(Object.values(nS));function iS(e){return typeof e==`string`&&rS.has(e)?e:void 0}let aS=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),oS=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},sS=e=>e?.code!==void 0;function cS(e,t,n){if(e!==401&&e!==403||sS(t))return;let r=typeof n==`string`&&n.trim()===``;if(oS(t)||r)return e===401?aS.SIGNED_OUT:aS.ACCESS_DENIED}function lS(e,t){return e===413&&t===void 0}function uS(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let dS=`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:dS,FALLBACKS_NOT_SUPPORTED:dS,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 fS=e=>e!==nS.VENDOR_UNREACHABLE;var toe=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 fS(this.code)}};function pS(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let noe=Object.freeze([/prompt is too long/i,/input token count .* exceeds/i,/maximum context length/i,/context[_ ]length[_ ]exceeded/i,/exceeds the context window/i,/too many (input )?tokens/i]),roe=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var mS=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 ioe(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 hS(e,t,n){if(t===400)for(let e of ioe(n)){if(!noe.some(t=>t.test(e)))continue;let t=roe.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function aoe(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(`
247
+ `,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:ub,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:lb,runAllChecks:()=>{cb.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return cb.debug(`Socket not configured`),!1;if(e.isReconnecting)return cb.debug(`Socket reconnecting`),!1;if(e.isConnecting)return cb.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return cb.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&cb.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return cb.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return jf(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([rb],fb.prototype,`config`,void 0),q([Kv],fb.prototype,`socketStatus`,void 0),q([Cg],fb.prototype,`connectEvents`,void 0),q([ng],fb.prototype,`user`,void 0),q([C],fb.prototype,`status`,void 0);let pb=N.createInterface(e=>e.singleton(fb)),mb={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},hb=N.createInterface();var gb;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(gb||(gb={}));var _b;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(_b||(_b={}));let vb=class{constructor(e,t,n=mb){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(_b.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(gb.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=hf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=hf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=hf(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(gb.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?_f(e.value):e.value}))}},n=yield this.connect.commitEvent(_b.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};vb=q([rd(0,ay),rd(1,ng),rd(2,It(hb))],vb),N.createInterface(e=>e.singleton(vb));var yb=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Mm(!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 tg,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],yb.prototype,`isWorking`,void 0),q([C],yb.prototype,`loggedUserResult`,void 0),q([C],yb.prototype,`currentUser`,void 0),q([C],yb.prototype,`isLoggedIn`,void 0);var bb=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=cg(e),this.fieldMetadata=sg(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=uh(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],bb.prototype,`status`,void 0),q([C],bb.prototype,`fetchMetadataRequired`,void 0),q([C],bb.prototype,`originalFieldDef`,void 0),q([C],bb.prototype,`fieldMetadata`,void 0),q([C],bb.prototype,`requestFields`,void 0),q([C],bb.prototype,`customRequestFields`,void 0),q([C],bb.prototype,`availableIndexes`,void 0),q([C],bb.prototype,`availableSortableFields`,void 0),q([C],bb.prototype,`availableCriteriaFields`,void 0),q([C],bb.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(ng));let xb=kd(`foundation-ui`);var Sb=class extends Wy(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Ly.MAX_ROWS_250,this.maxView=Ly.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 Mm(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==eb(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.fetchGeneration+=1,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===ag.REQUEST_SERVER?Ly.REQUEST_SERVER_ROW_ID:Ly.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.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}xb.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?Iy(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Mg.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 ag.REQUEST_SERVER:return!0;case ag.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===ag.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 Iy(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==ag.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=Vy({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=Hy({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&xb.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 eb((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&&xb[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===ig.DATE||t===ig.DATETIME?Mf(e,t===ig.DATETIME):e}};q([ay],Sb.prototype,`connect`,void 0),q([Qy],Sb.prototype,`datasource`,void 0),q([D({mode:`boolean`})],Sb.prototype,`withGridInit`,void 0),q([D],Sb.prototype,`criteria`,void 0),q([C],Sb.prototype,`data`,void 0),q([D],Sb.prototype,`fields`,void 0),q([D({mode:`boolean`})],Sb.prototype,`isSnapshot`,void 0),q([D],Sb.prototype,`maxRows`,void 0),q([D],Sb.prototype,`maxView`,void 0),q([D],Sb.prototype,`orderBy`,void 0),q([D],Sb.prototype,`request`,void 0),q([D],Sb.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],Sb.prototype,`reverse`,void 0),q([D],Sb.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],Sb.prototype,`withTimestampFormatting`,void 0);let Cb=(e,t)=>!e.composedPath().includes(t),wb=(e,t)=>e.composedPath().includes(t),Tb=e=>e.tagName.toLowerCase().split(`-`)[0];function Eb(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let Db=kd(`foundation-criteria`);var Ob;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(Ob||(Ob={}));var kb=class e{constructor(e){this.$$operator=e}static And(){return new e(Ob.AND)}static Or(){return new e(Ob.OR)}static Not(){return new e(Ob.NOT)}static GreaterThan(){return new e(Ob.GT)}static GreaterThanOrEqual(){return new e(Ob.GE)}static LessThan(){return new e(Ob.LT)}static LessThanOrEqual(){return new e(Ob.LE)}static NotEqual(){return new e(Ob.NE)}static Equal(){return new e(Ob.EQ)}get operator(){return this.$$operator}};let Ab=e=>e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`),jb=e=>`'${Ab(e)}'`,Mb=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?jb(t):t},Nb=e=>t=>`${t.field} ${e} ${Mb(t)}`,Pb=e=>Nb(Ob.NE)(e),Fb=e=>`${e.field}.contains(${Mb(e)})`,Ib={AND:e=>Nb(Ob.AND)(e),OR:e=>Nb(Ob.OR)(e),NOT:Pb,GT:e=>Nb(Ob.GT)(e),GE:e=>Nb(Ob.GE)(e),LT:e=>Nb(Ob.LT)(e),LE:e=>Nb(Ob.LE)(e),NE:Pb,EQ:e=>Nb(Ob.EQ)(e),equals:e=>`${e.field}.equals(${Mb(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Mb(e)})`,contains:Fb,fieldContains:Fb,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Mb(e)})`,startsWith:e=>`${e.field}.startsWith(${Mb(e)})`,endsWith:e=>`${e.field}.endsWith(${Mb(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Mb(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Mb(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Mb(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Mb(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Mb(e)})`},Lb=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),Rb=e=>Array.isArray(e)?e:[e],zb=`default`;var Bb=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,kb.And()),this.Or=(e,t={})=>this.withExpression(e,t,kb.Or()),this.Not=(e,t={})=>this.withExpression(e,t,kb.Not())}withExpression(e,t={},n=kb.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=zb)=>{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 kb;return t&&Db.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Lb(t,i),zb)}else o(e,zb)}else typeof e==`string`?o(e,zb):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 kb&&n[t-1]instanceof kb)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof kb?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Vb=class{constructor(e){this.serialiser=Ib.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 Hb=(e=`rapid`)=>T`<${e}-segmented-control :value="${df(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>`,Ub=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Bb,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(Rb(i).map(e=>Rb(n).map(t=>new Vb().withField(t).withValue(e).withSerialiser(r).build())),{join:kb.Or()}):t.And(new Vb().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],Ub.prototype,`criteriaOptions`,void 0),q([C],Ub.prototype,`prefix`,void 0),q([C],Ub.prototype,`value`,void 0),q([C],Ub.prototype,`selectedLabel`,void 0),Ub=q([$e({name:`criteria-segmented-control`,template:Hb(),styles:O``})],Ub);function Wb(e,t){let n=new Bb;n.withExpression(new Vb().withField(e.labelField??e.valueField).withValue(t).withSerialiser(Ib.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Gb(e,t){let n=new Bb;n.withExpression(new Vb().withField(e.valueField).withValue(t).withSerialiser(Ib.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let Kb=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,qb=e=>{let t=/* @__PURE__ */ new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))},Jb=qb(e=>T`<div ${k(`actionsOpener`)}class="actions-opener icon-only${e=>e.open?` opened`:``}" part="icon-opener" role="button" tabindex="0" aria-label="${e=>e.name}" aria-haspopup="menu" aria-expanded="${e=>String(e.open)}" @click=${e=>e.toggleActionsMenuVisibility()}@keydown=${(e,t)=>e.onIconOpenerKeydown(t.event)}><${e}-icon name="${e=>e.iconName}" size="lg"></${e}-icon></div>`),Yb=qb(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>`),Xb=qb(e=>T` ${t=>t.iconName?Jb(e):Yb(e)}<${e}-menu ${k(`actionsMenu`)}popover="${e=>e.isVertical?`auto`:`manual`}" class="actions-menu ${e=>e.classNames}" part="actions-menu" @toggle=${(e,t)=>e.onPopoverToggle(t.event)}>${j(e=>e.allActions,T` ${A((e,t)=>t.parent.isActionDisabled(e),T`<${e}-menu-item class="menu-item" tabindex="${(e,t)=>t.index}" disabled style=${(e,t)=>t.parent.hideDisabled?`display:none`:``}>${A(e=>e.icon,T`<${e}-icon name=${e=>e.icon.name}size=${e=>e.icon.size}variant=${e=>e.icon.variant}slot="start"></${e}-icon>`)} ${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} ${A((e,t)=>!t.parent.isActionDisabled(e),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};`:``}">${A(e=>e.icon,T`<${e}-icon name=${e=>e.icon.name}size=${e=>e.icon.size}variant=${e=>e.icon.variant}slot="start"></${e}-icon>`)} ${(e,t)=>t.parent.getLabel(e.name)}</${e}-menu-item>`)} `,{positioning:!0})}</${e}-menu>`),Zb=qb(e=>T`<${e}-button appearance="${e=>e.buttonAppearance}" part="actions-opener" class="actions-opener" @click=${e=>e?.singleOption.callback(e.rowData)}?disabled=${e=>e.isActionDisabled(e.singleOption)}>${e=>e.getLabel(e?.singleOption.name)}</${e}-button>`),Qb=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Tb(e))}</div>`;var $b=class{constructor(e,t,n){this.anchor=e,this.onReposition=t,this.onAnchorDetached=n,this.check=()=>{if(!this.anchor.isConnected){this.stop(),this.onAnchorDetached();return}let{top:e,right:t,bottom:n}=this.anchor.getBoundingClientRect(),r=`${e},${t},${n},${this.view.innerWidth},${this.view.innerHeight}`;this.lastPosition!==void 0&&r!==this.lastPosition&&(this.onReposition(),!this.view)||(this.lastPosition=r,this.frame=this.view.requestAnimationFrame(this.check))}}start(){this.stop(),this.view=this.anchor.ownerDocument.defaultView,this.view&&this.check()}stop(){var e;this.frame!==void 0&&((e=this.view)==null||e.cancelAnimationFrame(this.frame)),this.frame=void 0,this.lastPosition=void 0,this.view=void 0}},ex=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,this.focusMenuOnOpen=!1}disconnectedCallback(){this.stopTrackingPosition(),this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover(),super.disconnectedCallback()}updateMenuPosition(){let e=this.actionsOpener.getBoundingClientRect(),t=this.actionsMenu;if(t.style.position=`fixed`,t.style.left=`auto`,!this.isVertical){t.style.top=`${e.top}px`,t.style.right=`${window.innerWidth-e.right}px`;return}let{innerHeight:n,innerWidth:r}=window;t.style.maxHeight=`${n}px`;let{width:i,height:a}=t.getBoundingClientRect(),o=a<=n-e.bottom,s=a<=e.top,c=o||!s?e.bottom:e.top-a;t.style.top=`${Fn(0,Math.max(n-a,0),c)}px`,t.style.right=`${Fn(0,Math.max(r-i,0),r-e.right)}px`}startTrackingPosition(){this.positionTracker=new $b(this.actionsOpener,()=>this.updateMenuPosition(),()=>this.open=!1),this.positionTracker.start()}stopTrackingPosition(){var e;(e=this.positionTracker)==null||e.stop(),this.positionTracker=void 0}definitionChanged(e,t){t&&(typeof t.actions==`function`?(this.actionsResolver=t.actions,this.actions=[]):(this.actionsResolver=void 0,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.iconName&&(this.iconName=t.iconName,delete this.definition.iconName),t.addDefaultActions!==void 0&&(this.addDefaultActions=t.addDefaultActions,delete this.definition.addDefaultActions),t.hideDisabled!==void 0&&(this.hideDisabled=t.hideDisabled,delete this.definition.hideDisabled),t.buttonAppearance&&(this.buttonAppearance=t.buttonAppearance,delete this.definition.buttonAppearance),t.hideMenuSingleOption&&(this.hideMenuSingleOption=t.hideMenuSingleOption,delete this.definition.hideMenuSingleOption),this.open&&(this.isVertical&&!this.hasVisibleActions?this.open=!1:x.queueUpdate(()=>this.open&&this.updateMenuPosition())))}openChanged(){var e;if(this.classNames=fn([`visible`,this.open],[`hidden`,!this.open]),this.open)this.updateMenuPosition(),this.actionsMenu.showPopover(),this.startTrackingPosition(),x.queueUpdate(()=>{this.open&&(this.updateMenuPosition(),this.focusMenuOnOpen&&this.actionsMenu.focus(),this.focusMenuOnOpen=!1)});else{this.focusMenuOnOpen=!1,this.stopTrackingPosition();let t=this.actionsMenu?.contains(this.shadowRoot?.activeElement);this.actionsMenu?.matches(`:popover-open`)&&this.actionsMenu.hidePopover(),t&&((e=this.actionsOpener)==null||e.focus())}}toggleActionsMenuVisibility(){this.open=!this.open}onPopoverToggle(e){let t=e.newState;t&&(this.open=t===`open`)}onIconOpenerKeydown(e){return e.key!==`Enter`&&e.key!==` `||(this.focusMenuOnOpen=!this.open,this.toggleActionsMenuVisibility(),!1)}onActionMenuItemClick(e){this.autoCloseOnAction&&(this.open=!1),e(this.rowData)}isActionDisabled(e){return!!e.isDisabled?.call(e,this.rowData)}get resolvedActions(){return(this.actionsResolver?this.actionsResolver(this.rowData):this.actions)??[]}get hasVisibleActions(){let e=this.resolvedActions;return this.hideDisabled?e.some(e=>!this.isActionDisabled(e)):e.length>0}get allActions(){let e=[{name:`✖`,callback:()=>this.open=!1}];return this.addDefaultActions?[...this.resolvedActions,...e]:this.resolvedActions}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.isVertical&&!this.hasVisibleActions)return;let t=this.resolvedActions.filter(e=>!this.isActionDisabled(e));if(!this.hideMenuSingleOption)return Xb(e);if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],Zb(e)):Xb(e)}};q([C],ex.prototype,`actions`,void 0),q([C],ex.prototype,`actionsResolver`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],ex.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],ex.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],ex.prototype,`autoCloseOnAction`,void 0),q([C],ex.prototype,`classNames`,void 0),q([C],ex.prototype,`definition`,void 0),q([D],ex.prototype,`name`,void 0),q([D({attribute:`icon-name`})],ex.prototype,`iconName`,void 0),q([D({attribute:`open`,mode:`boolean`})],ex.prototype,`open`,void 0),q([D],ex.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],ex.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],ex.prototype,`hideMenuSingleOption`,void 0),q([C],ex.prototype,`singleOption`,void 0),ex.compose({baseName:`actions-menu`,styles:Jne,template:Qb});let tx=()=>{};function nx(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:tx};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 rx=!1;try{typeof GENX_ENABLE_AI<`u`&&(rx=GENX_ENABLE_AI===`true`)}catch{}let ix=()=>rx||yf(`ai`),ax=kd(`foundation-ai`);function ox(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function sx(e,t){if(!ox())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 cx=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 lx=[`gemini-2.5-pro`,`gemini-2.5-flash`,`gemini-2.5-flash-lite`,`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],ux=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`],dx=[`gpt-6-astra`,`gpt-6.1-sol`,`gpt-6.1-terra`,`gpt-6-sol`,`gpt-6-luna`];function fx(e){return e===`image/jpg`?`image/jpeg`:e}function px(e){return e.replace(/^data:[^,]*;base64,/,``)}let mx=.5;function hx(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=mx?r/mx*t:t+(r-mx)/.5*(n-t)}let gx=1e6,_x={"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 vx(e){return _x[e]}function yx(e,t){let{promptPerMillion:n,candidatePerMillion:r}=vx(e),i=gx,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 bx={"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:`dated`,before:{promptPerMillion:.75,candidatePerMillion:3.75},after:{promptPerMillion:1.5,candidatePerMillion:7.5},switchAtMs:Date.parse(`2027-01-01T00:00:00Z`)},"gemini-4-argon":{kind:`dated`,before:{promptPerMillion:2,candidatePerMillion:10},after:{promptPerMillion:4,candidatePerMillion:20},switchAtMs:Date.parse(`2026-12-01T00:00:00Z`)},"gemini-3.1-pro-preview":{kind:`tiered`,standard:{promptPerMillion:2,candidatePerMillion:12},longContext:{promptPerMillion:4,candidatePerMillion:18}}};function xx(e,t,n=/* @__PURE__ */ new Date){let r=bx[e];return r.kind===`flat`?r.rate:r.kind===`dated`?n.getTime()<r.switchAtMs?r.before:r.after:t>2e5?r.longContext:r.standard}function Sx(e,t,n=/* @__PURE__ */ new Date){let{promptPerMillion:r,candidatePerMillion:i}=xx(e,t.promptTokens,n),a=gx,o=Math.max(0,t.promptTokens-t.cachedTokens)/a*r,s=t.cachedTokens/a*r*.1,c=(t.candidateTokens+t.thoughtTokens)/a*i;return{costUsd:o+s+c,savedUsd:t.cachedTokens/a*r-s,breakdown:{promptUsd:o,cacheReadUsd:s,cacheWriteUsd:0,candidateUsd:c}}}let Cx={"gpt-6-astra":{promptPerMillion:10,cachedPerMillion:1,candidatePerMillion:50},"gpt-6.1-sol":{promptPerMillion:2,cachedPerMillion:.1,candidatePerMillion:10},"gpt-6.1-terra":{promptPerMillion:1,cachedPerMillion:.05,candidatePerMillion:5},"gpt-6-sol":{promptPerMillion:2,cachedPerMillion:.2,candidatePerMillion:10},"gpt-6-luna":{promptPerMillion:.1,cachedPerMillion:.01,candidatePerMillion:.5}};function wx(e,t){let n=Cx[e];return t<=272e3?n:{promptPerMillion:n.promptPerMillion*2,cachedPerMillion:n.cachedPerMillion*2,candidatePerMillion:n.candidatePerMillion*1.5}}function Tx(e,t){let{promptPerMillion:n,cachedPerMillion:r,candidatePerMillion:i}=wx(e,t.inputTokens),a=gx,o=Math.max(0,t.inputTokens-t.cacheReadTokens-t.cacheWriteTokens),s=Math.min(t.cacheWrite12hTokens,t.cacheWriteTokens),c=Math.max(0,t.cacheWriteTokens-s),l=o/a*n,u=t.cacheReadTokens/a*r,d=c/a*n*1.25+s/a*n*2.5,f=t.outputTokens/a*i,p=t.cacheReadTokens/a*n,m=t.cacheWriteTokens/a*n;return{costUsd:l+u+d+f,savedUsd:p-u+(m-d),breakdown:{promptUsd:l,cacheReadUsd:u,cacheWriteUsd:d,candidateUsd:f}}}let Ex=[`properties`,`patternProperties`,`$defs`,`definitions`],Dx=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],Ox=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],kx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ax(e){if(Array.isArray(e))return e.map(Ax);if(kx(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ax(r);return t}return e}function jx(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=Ex.includes(i)&&kx(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,kx(r)?t(r,`${e}/${n}`):Ax(r)])):Dx.includes(i)&&Array.isArray(a)?a.map((n,r)=>kx(n)?t(n,`${e}/${r}`):Ax(n)):Ox.includes(i)?kx(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>kx(n)?t(n,`${e}/${r}`):Ax(n)):Ax(a):Ax(a)}return r}function Mx(e,t,n=``){return t(jx(e,(e,n)=>Mx(e,t,n),n),n)}let Nx=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Px=[`oneOf`,`not`];function Fx(e){let t=[],n=[],r=[];return{schema:Mx(e,(e,i)=>{for(let n of Nx)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 Px)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||kx(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function Ix(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Fx(e);return r.length&&ax.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&ax.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&&ax.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 Lx=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Rx(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!kx(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return kx(n)?n:void 0}function zx(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=Rx(e,o);if(!t)break;let{$ref:n}=i,r=nd(i,[`$ref`]);i=Object.assign(Object.assign({},Ax(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),jx(i,t=>zx(e,t,a,r),``)}function Bx(e){let t=[],n=zx(e,e,/* @__PURE__ */ new Set,t);return t.length&&ax.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.`),Mx(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(kx),n=t.filter(e=>e.type!==`null`);if(t.length===2&&n.length===1){let{anyOf:t}=e,r=nd(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 Lx)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}let Vx=[`allOf`,`not`,`if`,`then`,`else`,`oneOf`];function Hx(e){if(typeof e.type==`string`){let t=Object.assign(Object.assign({},e),{type:e.type===`null`?`null`:[e.type,`null`]});return Array.isArray(e.enum)&&!e.enum.includes(null)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.type)){if(e.type.includes(`null`))return e;let t=Object.assign(Object.assign({},e),{type:[...e.type,`null`]});return Array.isArray(e.enum)&&!e.enum.includes(null)&&(t.enum=[...e.enum,null]),t}return Array.isArray(e.anyOf)?e.anyOf.some(e=>kx(e)&&e.type===`null`)?e:Object.assign(Object.assign({},e),{anyOf:[...e.anyOf,{type:`null`}]}):{anyOf:[e,{type:`null`}]}}function Ux(e){let t=[],n=[],r=[];return{schema:Mx(e,(e,i)=>{for(let t of Vx)t in e&&r.push(`${i}/${t}`);if(!(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||kx(e.properties)))return e;if(e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),kx(e.properties)){let n=Object.keys(e.properties),r=new Set(Array.isArray(e.required)?e.required:[]),a=e.properties;for(let e of n)r.has(e)||(a[e]=kx(a[e])?Hx(a[e]):{type:`null`},t.push(`${i}/properties/${e}`));e.required=n}return e}),madeNullable:t,overridden:n,undroppable:r}}function Wx(e,t){let{schema:n,madeNullable:r,overridden:i,undroppable:a}=Ux(e);return r.length&&ax.debug(`OpenAITransport: tool "${t}" is strict, which has no optional properties; these are now required and nullable, so an absent value arrives as null: ${r.join(`, `)}`),i.length&&ax.warn(`OpenAITransport: tool "${t}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}.`),a.length&&ax.warn(`OpenAITransport: tool "${t}" uses schema keywords strict mode cannot express (${a.join(`, `)}). They are left in place, so the request will be rejected. Rewrite them or drop enforceSchema for this tool.`),n}let Gx=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`,`openai`]),new Map(Object.entries(Gx).map(([e,t])=>[t.toLowerCase(),e]));var Kx=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 qx=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,Jx=e=>{try{return JSON.parse(e)}catch{return}},Yx=e=>{let t=e?.code;return typeof t==`string`?t:void 0},Xx=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Zx=e=>typeof e==`boolean`?e:void 0,Qx=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function $x(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 Kx(e,Xx(r.budgetUsd)??Xx(i.budgetUsd),Xx(r.spentUsd)??Xx(i.spentUsd),a,{otherVendorAvailable:Zx(r.otherVendorAvailable)??Zx(i.otherVendorAvailable),serverVendor:Qx(r.vendor)??Qx(i.vendor)})}function eS(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 tS(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 nS=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`}),rS=new Set(Object.values(nS));function iS(e){return typeof e==`string`&&rS.has(e)?e:void 0}let aS=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),oS=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},sS=e=>e?.code!==void 0;function cS(e,t,n){if(e!==401&&e!==403||sS(t))return;let r=typeof n==`string`&&n.trim()===``;if(oS(t)||r)return e===401?aS.SIGNED_OUT:aS.ACCESS_DENIED}function lS(e,t){return e===413&&t===void 0}function uS(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let dS=`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:dS,FALLBACKS_NOT_SUPPORTED:dS,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 fS=e=>e!==nS.VENDOR_UNREACHABLE;var toe=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 fS(this.code)}};function pS(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let noe=Object.freeze([/prompt is too long/i,/input token count .* exceeds/i,/maximum context length/i,/context[_ ]length[_ ]exceeded/i,/exceeds the context window/i,/too many (input )?tokens/i]),roe=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var mS=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 ioe(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 hS(e,t,n){if(t===400)for(let e of ioe(n)){if(!noe.some(t=>t.test(e)))continue;let t=roe.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function aoe(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(`
248
248
  `);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(`
249
249
  `)}}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(()=>{})}})}var ooe=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 soe=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),coe=Object.freeze([`authentication_error`,`permission_error`]);function gS(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 loe(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 _S(e){let t=gS(e);if(t?.type){if(coe.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function vS(e,t,n){if(t===`PROVIDER_REFUSED`)return loe(n)??_S(n)??`spend`;if(e!==`anthropic`)return;let r=_S(n);if(r)return r;let i=gS(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(soe.some(t=>t.test(e)))return`spend`}}function yS(e,t,n,r,i){let a=gS(r);return new ooe(e,t,n,a?.type,a?.message??i)}function uoe(e){return Object.entries(Gx).find(([,t])=>t===e)?.[0]}let bS=12e4,xS=1e3;function doe(e){let t=(e?.get)?.call(e,`x-should-retry`);return typeof t==`string`&&t.trim().toLowerCase()===`false`}function foe(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*xS);let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function SS(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*xS}}}function poe(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 moe(e,t){return Math.max(0,e-t)}function CS(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=uoe(o),p=(e,t,n)=>(ax.error(`${o}Transport: the AI service refused the request (${t} ${e})${n?`: ${n}`:``}`),new toe(o,e,t,n)),m=0,h=(e,t)=>{let n=u*2**e,r=bS-m,i=poe(e,u,t,r);return m+=moe(i,n),t!=null&&i>n?ax.warn(`${o}Transport: honouring the server's requested retry delay (${Math.round(i)}ms, asked ${Math.round(t)}ms)`):t!=null&&t>n&&ax.warn(`${o}Transport: declining the server's requested retry delay (asked ${Math.round(t)}ms; the ${bS}ms sequence allowance is spent) — using the ladder's ${Math.round(i)}ms`),tS(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}=nx([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=Jx(t),r=vS(f,Yx(n),n);if(r)throw yS(o,r,c.status,n,t||void 0);let i=hS(f,c.status,n);if(i)throw new mS(o,i.promptTokens,i.limitTokens,i.message??(t||void 0));if(qx(c.status,Yx(n)))throw $x(o,n,t||void 0);let a=iS(Yx(n));if(a&&a!==nS.VENDOR_UNREACHABLE)throw p(a,c.status,pS(n));let l=cS(c.status,n,t);if(l)throw p(l,c.status,uS(n)??(t||void 0));if(lS(c.status,n))throw p(nS.REQUEST_TOO_LARGE,c.status,t||void 0);let u=doe(c.headers);if(s.includes(c.status)&&!u&&e<5){ax.warn(`${o}Transport: retryable status ${c.status}, retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,foe(c.headers)||SS(n));continue}throw a?p(a,c.status,pS(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 aoe(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=vS(f,t.code,t);if(n)throw yS(o,n,t.status,t,t.error);let r=hS(f,t.status,t);if(r)throw new mS(o,r.promptTokens,r.limitTokens,r.message??t.error);if(qx(t.status,t.code))throw $x(o,t);let i=iS(t.code);if(i&&i!==nS.VENDOR_UNREACHABLE)throw p(i,t.status,pS(t));if(s.includes(t.status)&&e<5){ax.warn(`${o}Transport: retryable status ${t.status} (err frame), retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,SS(t));continue}throw i?p(i,t.status,pS(t)):Error(`${o} request error ${t.status}: ${t.error??JSON.stringify(t.details)}`)}return yield c.json()}catch(e){throw eS(e,u.signal,d)}finally{clearTimeout(y),x()}}throw Error(`${o} request failed: max retries exceeded`)})}function hoe(e){if(e&&e!==`auto`)return e===`required`?{type:`any`}:e===`none`?{type:`none`}:{type:`tool`,name:e.tool}}let goe={"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},wS=`emit_structured_response`;function _oe(e){if(!ux.includes(e))throw Error(`AnthropicTransport: unsupported model "${e}". Use one of: ${ux.join(`, `)}.`)}function voe(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-opus-4-7`||e===`claude-sonnet-5`}function TS(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`||e===`claude-haiku-4-5-20251001`}function ES(e){return e!==`claude-haiku-4-5-20251001`}function DS(e){return e===`claude-fable-5`}function yoe(e,t){let n=e===`claude-sonnet-5`||DS(e),r={type:`adaptive`,display:`summarized`};return t===`off`?DS(e)?r:n?{type:`disabled`}:void 0:t===`auto`||t!==void 0?ES(e)?r:void 0:n?r:void 0}function OS(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`}let boe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function xoe(e,t){if(t!==void 0&&t!==`auto`&&t!==`off`&&OS(e)&&ES(e))return boe[t]}let kS=`anthropic`;var AS=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`}},jS=class e{warnIfThinkingUnclampable(e){if(this.warnedThinkingClamped)return;let t=this.clampWarning(e);t&&(this.warnedThinkingClamped=!0,ax.warn(t))}clampWarning(e){switch(e){case void 0:return;case`off`:return DS(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 ES(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!ES(this.model)||!OS(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`;_oe(t),this.model=t,t===`claude-sonnet-5`?ax.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`?ax.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`?ax.warn(`AnthropicTransport: using ${t} — significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`):t===`claude-fable-5`&&ax.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:goe[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&&TS(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:wS,description:`Emit the structured response that matches the required schema.`,input_schema:r}],a.tool_choice={type:`tool`,name:wS}),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===wS);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?Ix(e.parameters,e.name):e.parameters},e.enforceSchema?{strict:!0}:{}))),a.tools?.length){let e=hoe(n?.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingUnclampable(n?.thinkingPolicy);let o=yoe(this.model,n?.thinkingPolicy);o&&(a.thinking=o);let s=xoe(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&&!voe(this.model)&&!c&&(a.temperature=hx(n.temperature,{defaultTemp:1,maxTemp:1})),n?.responseSchema&&TS(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}=yx(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:fx(r.mimeType),data:px(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:fx(e.mimeType),data:px(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?.[kS];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:ux.includes(t)?t:(this.warnedUnknownServingModels.has(t)||(this.warnedUnknownServingModels.add(t),ax.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),{[kS]:e})}if(e.stop_reason===`max_tokens`&&l.length>0)throw new AS(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 CS({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:Gx.anthropic,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};jS.TOKENS_PER_MILLION=1e6,jS.COST_DECIMAL_PLACES=6,jS.RATE_LIMIT_STATUS=429,jS.SERVICE_UNAVAILABLE_STATUS=503,jS.OVERLOADED_STATUS=529,jS.RETRYABLE_STATUSES=[jS.RATE_LIMIT_STATUS,jS.SERVICE_UNAVAILABLE_STATUS,jS.OVERLOADED_STATUS],jS.BACKOFF_BASE_MS=1e3;let MS=`default_api.`,Soe=/print\(\s*$/;var Coe=class{constructor(e){this.src=e,this.pos=0}parse(){let e=this.src.indexOf(MS);e===-1&&this.bail();let t=Soe.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(MS);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`
250
250
  `;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 woe(e,t){if(!e)return null;let n;try{n=new Coe(e).parse()}catch{return null}return t.has(n.name)?n:null}let Toe=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,Eoe={"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,"gemini-2.5-flash-lite":1048576,"gemini-4-argon":1048576,"gemini-3.8-flash":1048576,"gemini-3.5-flash":1048576,"gemini-3.1-flash-lite":1048576,"gemini-3.1-pro-preview":1048576};function Doe(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Ooe(e){if(!lx.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${lx.join(`, `)}.`)}let koe={"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. Billed at an introductory $0.75/$3.75 per MTok through 2026-12-31 and $1.50/$7.50 from 2027-01-01; weigh a tier choice against the later rate.`,"gemini-4-argon":`GeminiTransport: using gemini-4-argon — premium reasoning model, materially higher cost than the flash tiers. Billed at $2/$10 per MTok through 2026-11-30 and $4/$20 from 2026-12-01; weigh a tier choice against the later rate.`,"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.`},NS=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],Aoe=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],joe=[`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],PS=[`minimal`,`low`,`medium`,`high`],FS={"gemini-4-argon":[`low`,`medium`,`high`],"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 IS(e,t){if(!e?.length||e.includes(t))return t;let n=PS.indexOf(t),r=e=>Math.abs(PS.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let LS={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},RS=e=>e!==void 0&&e!==`auto`&&e!==`off`;function Moe(e,t){if(RS(t)){let n=FS[e];if(n)return{includeThoughts:!0,thinkingLevel:IS(n,LS[t])}}return t===`off`&&NS.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&NS.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let zS=`gemini`;function BS(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:fx(r.mimeType),data:px(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var Noe=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},VS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!NS.includes(this.model)){this.warnedThinkingClamped=!0,ax.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(RS(e)){let t=FS[this.model];if(!t){this.warnedThinkingClamped=!0,ax.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=LS[e],r=IS(t,n);r!==n&&(this.warnedThinkingClamped=!0,ax.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`;Ooe(t),this.model=t;let n=koe[t];n&&ax.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:Eoe[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:Bx(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Doe(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:Moe(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&&Aoe.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=hx(n.temperature,{defaultTemp:1,maxTemp:2}));let l=new Set((n?.tools??[]).map(e=>e.name)),u=joe.includes(this.model),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:Bx(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=Sx(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:fx(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?.[zS],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}=BS(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}=BS(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:{[zS]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=woe(c.finishMessage,t);if(!e)throw new Noe(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 AS(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};ax.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:`${Toe(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 CS({url:r,headers:a,body:i,credentials:o,vendorLabel:Gx.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}};VS.TOKENS_PER_MILLION=1e6,VS.COST_DECIMAL_PLACES=6,VS.RATE_LIMIT_STATUS=429,VS.SERVICE_UNAVAILABLE_STATUS=503,VS.BAD_GATEWAY_STATUS=502,VS.RETRYABLE_STATUSES=[VS.RATE_LIMIT_STATUS,VS.SERVICE_UNAVAILABLE_STATUS,VS.BAD_GATEWAY_STATUS],VS.BACKOFF_BASE_MS=1e3;let Poe={"gpt-6-astra":922e3,"gpt-6.1-sol":105e4,"gpt-6.1-terra":105e4,"gpt-6-sol":105e4,"gpt-6-luna":105e4},HS=[`gpt-6.1-terra`,`gpt-6-luna`],Foe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Ioe(e,t){if(t!==void 0&&t!==`auto`)return t===`off`?HS.includes(e)?`none`:`low`:Foe[t]}function Loe(e){if(e&&e!==`auto`)return e===`required`||e===`none`?e:{type:`function`,name:e.tool}}function Roe(e){let t=e.enforceSchema?Wx(e.parameters,e.name):e.parameters;return{type:`function`,name:e.name,description:e.description,parameters:t,strict:!!e.enforceSchema}}function zoe(e){if(!dx.includes(e))throw Error(`OpenAITransport: unsupported model "${e}". Use one of: ${dx.join(`, `)}.`)}let Boe={"gpt-6-astra":`OpenAITransport: using gpt-6-astra — flagship model at $10/$50 per MTok; reserve for tasks where the cheaper tiers are insufficient.`,"gpt-6.1-sol":`OpenAITransport: using gpt-6.1-sol — materially higher cost than terra/luna, and it cannot turn reasoning off (thinkingPolicy "off" runs at effort "low").`,"gpt-6-sol":`OpenAITransport: using gpt-6-sol — superseded by gpt-6.1-sol at the same price, and it cannot turn reasoning off.`},US=`openai`,WS=Object.freeze({mode:`explicit`});function Voe(e){let t=[],n=[],r=[],i=[],a=[],o;for(let s of e)if(s.type===`reasoning`){t.push(s);for(let e of s.summary??[])e.text&&n.push(e.text)}else if(s.type===`message`){typeof s.phase==`string`&&o!==`final_answer`&&(o=s.phase);for(let e of s.content??[])e.type===`output_text`&&typeof e.text==`string`&&r.push(e.text),e.type===`refusal`&&typeof e.refusal==`string`&&i.push(e.refusal)}else s.type===`function_call`&&a.push({id:String(s.call_id??s.id??crypto.randomUUID()),name:String(s.name),args:Koe(s.arguments)});return{reasoning:t,summaryParts:n,textParts:r,refusals:i,toolCalls:a,phase:o}}function GS(e){let t={type:`input_image`,image_url:`data:${fx(e.mimeType)};base64,${px(e.data)}`};return e.detail&&(t.detail=e.detail===`medium`?`auto`:e.detail),t}function KS(e,t){let n=[];for(let e of t)e.kind===`image`&&n.push(GS(e));e&&n.push({type:`input_text`,text:e});for(let e of t)e.kind!==`image`&&n.push({type:`input_text`,text:`[File: ${e.name}]\n${e.content}`});return n}function Hoe(e){return e.providerMetadata?.[US]??e.toolCalls?.[0]?.providerMetadata?.[US]}function Uoe(e){let{status:t}=e;return nd(e,[`status`])}var qS=class e{constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=/* @__PURE__ */ new Set;let t=e.model??`gpt-6-luna`;zoe(t),this.model=t;let n=Boe[t];n&&ax.warn(n),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint,this.maxTokens=e.maxTokens,this.reasoningSummary=e.reasoningSummary??`none`}getConfig(){return{provider:`openai`,model:this.model,contextLimit:Poe[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;return(yield this.sendChatMessage([],n,{systemPrompt:t,responseSchema:r})).content})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=this.buildRequestBody(e,t,n),i=yield this.post(r,n?.signal),a=this.fromResponse(i,r.max_output_tokens);return this.restoreOptionalFields(a,n),a})}restoreOptionalFields(e,t){let n=Goe(t?.tools);for(let t of e.toolCalls??[]){let e=n.get(t.name);e&&JS(t.args,e)}if(!t?.responseSchema||!e.content)return;let{madeNullable:r}=Ux(t.responseSchema);if(r.length)try{let t=JSON.parse(e.content);JS(t,r),e.content=JSON.stringify(t)}catch{}}buildRequestBody(e,t,n){let r=n?.cachePolicy&&n.cachePolicy.scope!=="default"?n.cachePolicy.scope:void 0,i=[];if(n?.systemPrompt){let e={type:`input_text`,text:n.systemPrompt};r&&(e.prompt_cache_breakpoint=WS),i.push({type:`message`,role:`developer`,content:[e]})}i.push(...this.toInputItems(e,t,n?.attachments)),r===`history`&&this.markHistoryBreakpoints(i),n?.tailContext&&i.push({type:`message`,role:`user`,content:[{type:`input_text`,text:n.tailContext}]});let a={model:this.model,input:i,store:!1,include:[`reasoning.encrypted_content`]};if(r&&(a.prompt_cache_options={mode:`explicit`,ttl:`30m`}),n?.tools?.length){a.tools=n.tools.map(Roe);let e=Loe(n.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingClamped(n?.thinkingPolicy);let o=Ioe(this.model,n?.thinkingPolicy);o?a.reasoning=o===`none`||this.reasoningSummary===`none`?{effort:o}:{effort:o,summary:this.reasoningSummary}:this.reasoningSummary!==`none`&&(a.reasoning={summary:this.reasoningSummary}),n?.temperature!=null&&o===`none`&&(a.temperature=hx(n.temperature,{defaultTemp:1,maxTemp:2}));let s=n?.maxTokens??this.maxTokens;return s!=null&&(a.max_output_tokens=s),n?.responseSchema&&(a.text={format:{type:`json_schema`,name:`response`,schema:Ux(n.responseSchema).schema,strict:!0}}),a}warnIfThinkingClamped(e){e&&!this.warnedThinkingClamped.has(e)&&(e===`off`&&!HS.includes(this.model)?(this.warnedThinkingClamped.add(e),ax.warn(`OpenAITransport: thinkingPolicy 'off' sent as effort 'low' — ${this.model} does not accept effort 'none'. Reasoning tokens are billed as output; use gpt-6.1-terra or gpt-6-luna if you need them gone.`)):e===`minimal`&&(this.warnedThinkingClamped.add(e),ax.warn(`OpenAITransport: thinkingPolicy 'minimal' sent as effort 'low' — OpenAI has no 'minimal' effort.`)))}toInputItems(e,t,n){let r=[],i=/* @__PURE__ */ new Set;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){r.push(this.toFunctionCallOutput(t));continue}if(t.role===`user`){let e=KS(t.content,t.attachments??[]);e.length&&r.push({type:`message`,role:`user`,content:e});continue}let e=Hoe(t);if(e?.model===this.model)for(let t of e.reasoning??[]){let e=t.id??t.encrypted_content;i.has(e)||(i.add(e),r.push(Uoe(t)))}if(t.content){let n={type:`message`,role:`assistant`,content:[{type:`output_text`,text:t.content}]};e?.phase&&(n.phase=e.phase),r.push(n)}for(let e of t.toolCalls??[])r.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.args??{})})}let a=KS(t,n??[]);return a.length&&r.push({type:`message`,role:`user`,content:a}),r}toFunctionCallOutput(e){let t=e.toolResult,n=t.attachments??[];return{type:`function_call_output`,call_id:t.toolCallId,output:[{type:`input_text`,text:t.content},...n.map(GS)]}}markHistoryBreakpoints(e){let t=0;for(let n=e.length-1;n>=0&&t<49;--n){let r=e[n];if(r.role===`developer`)continue;let i=r.type===`function_call_output`?`output`:r.type===`message`&&r.role!==`assistant`?`content`:void 0;if(!i)continue;let a=[...r[i]],o=-1;for(let e=a.length-1;e>=0;--e)if(a[e].type===`input_text`){o=e;break}o<0||(a[o]=Object.assign(Object.assign({},a[o]),{prompt_cache_breakpoint:WS}),e[n]=Object.assign(Object.assign({},r),{[i]:a}),t+=1)}}usageFromResponse(t){if(!t)return{};let n=t,r=n.input_tokens_details?.cached_tokens??0,i=n.input_tokens_details?.cache_write_tokens??0,{costUsd:a,savedUsd:o}=Tx(this.model,{inputTokens:n.input_tokens??0,outputTokens:n.output_tokens??0,cacheReadTokens:r,cacheWriteTokens:i,cacheWrite12hTokens:n.input_tokens_details?.cache_write_tokens_details?.ttl_12h_tokens??0});this.lifetimeCostUsd+=a,this.lifetimeSavingsUsd+=o;let s=e.COST_DECIMAL_PLACES;return console.log(`--- OpenAI Token Usage (${this.model}) ---`),console.log(`Input Tokens: ${n.input_tokens??0} (${r} cached, ${i} written)`),console.log(`Output Tokens: ${n.output_tokens??0} (incl. ${n.output_tokens_details?.reasoning_tokens??0} reasoning)`),console.log(`Total Cost: $${a.toFixed(s)}`),console.log(`Cache Saved: $${o.toFixed(s)} (lifetime $${this.lifetimeSavingsUsd.toFixed(s)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(s)}`),console.log(`--------------------------`),{inputTokens:n.input_tokens,outputTokens:n.output_tokens,thoughtsTokens:n.output_tokens_details?.reasoning_tokens,cacheReadTokens:n.input_tokens_details?.cached_tokens,cacheWriteTokens:n.input_tokens_details?.cache_write_tokens,cost:a}}fromResponse(e,t){let n=this.usageFromResponse(e.usage),r=e.output??[],{reasoning:i,summaryParts:a,textParts:o,refusals:s,toolCalls:c,phase:l}=Voe(r),u={model:this.model};i.length&&(u.reasoning=i),l&&(u.phase=l);let d={[US]:u};c.length&&(c[0].providerMetadata=d);let f=o.join(``),p=a.join(`
@@ -254,7 +254,7 @@ function cy(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r
254
254
  &#x2715;
255
255
  </button></span>`)}</div>`)}<${e}-button class="criteria-toggle-button" appearance="outline" title=${e=>e.showingChips?`Add more criteria`:`View active filters`}?disabled=${e=>e.activeGroups.length===0||e.isInterpreting}@click=${e=>e.toggleCriteriaView()}><${e}-icon name="pen" size="sm"></${e}-icon></${e}-button><${e}-button class="criteria-clear-button" appearance="outline" title="Clear all filters" ?disabled=${e=>e.activeGroups.length===0||e.isInterpreting}@click=${e=>e.clearChips()}><${e}-icon name="trash-alt" size="sm"></${e}-icon></${e}-button>${A(e=>e.speechAvailable,T`<${e}-button class="mic-button" appearance="${e=>e.isRecording?`accent`:`outline`}" ?disabled=${e=>e.disabled||e.isInterpreting}@click=${e=>e.toggleSpeechInput()}title=${e=>e.isRecording?`Stop recording`:`Start voice input`}><${e}-icon class="mic-icon" name="microphone" size="lg" variant="solid"></${e}-icon></${e}-button>`)}</div></div>`)} `,tC=T` ${e=>qoe(Tb(e))} `,Joe={contains:Ib.containsIgnoreCase,equals:Ib.EQ,startsWith:Ib.startsWith,endsWith:Ib.endsWith,greaterThan:Ib.GT,lessThan:Ib.LT,greaterThanOrEqual:Ib.GE,lessThanOrEqual:Ib.LE,notEqual:Ib.NE,dateIsToday:Ib.dateIsToday,dateIsAfter:Ib.dateIsGreaterEqual,dateIsGreaterEqual:Ib.dateIsGreaterEqual,dateIsBefore:Ib.dateIsLessEqual,dateIsLessEqual:Ib.dateIsLessEqual,dateIsEqual:Ib.dateIsEqual,dateTimeIsAfter:Ib.dateTimeIsGreaterEqual,dateTimeIsGreaterEqual:Ib.dateTimeIsGreaterEqual,dateTimeIsBefore:Ib.dateTimeIsLessEqual,dateTimeIsLessEqual:Ib.dateTimeIsLessEqual};function Yoe(e){let t=Joe[e.operator];if(!t)throw Error(`Unknown criteria operator '${e.operator}'`);return new Vb().withField(e.field).withValue(e.value??null).withSerialiser(t).withGroup(`default`).build()}function Xoe(e,t){return e.length===1?e[0]:e.reduce((e,n,r)=>r===0?[n]:[...e,t,n],[])}function nC(e){let t=new Bb,n=!1;for(let r of e){if(!r.clauses?.length)continue;let e=r.clauses.map(Yoe),i=r.logic===`or`?kb.Or():kb.And(),a=Xoe(e,i),o=e.length>1?{join:i}:{};r.negated?t.And([kb.Not(),a]):t.And(e.length===1?e[0]:e,o),n=!0}return n?t.build():``}let Zoe=[`contains`,`equals`,`startsWith`,`notEqual`],rC=[`equals`,`greaterThan`,`lessThan`,`greaterThanOrEqual`,`lessThanOrEqual`,`notEqual`],iC=[`dateIsToday`,`dateIsAfter`,`dateIsBefore`,`dateIsEqual`,`dateIsGreaterEqual`,`dateIsLessEqual`],aC=[`dateTimeIsAfter`,`dateTimeIsBefore`,`dateTimeIsGreaterEqual`,`dateTimeIsLessEqual`],Qoe={contains:`contains`,equals:`=`,startsWith:`starts with`,endsWith:`ends with`,notEqual:`≠`,greaterThan:`>`,lessThan:`<`,greaterThanOrEqual:`≥`,lessThanOrEqual:`≤`,dateIsToday:`is today`,dateIsAfter:`after`,dateIsBefore:`before`,dateIsEqual:`=`,dateIsGreaterEqual:`≥`,dateIsLessEqual:`≤`,dateTimeIsAfter:`after`,dateTimeIsBefore:`before`,dateTimeIsGreaterEqual:`≥`,dateTimeIsLessEqual:`≤`},$oe=/* @__PURE__ */ new Set([`DATE`,`LOCALDATE`]),ese=/* @__PURE__ */ new Set([`DATETIME`,`NANO_TIMESTAMP`,`LOCALDATETIME`,`TIMESTAMP`]),oC=/* @__PURE__ */ new Set([`INT`,`INTEGER`,`LONG`,`SHORT`,`DOUBLE`,`BIGDECIMAL`,`DECIMAL`]);function sC(e){return(e||``).toUpperCase().trim().split(`(`)[0].trim()}function tse(e){let t=sC(e);return $oe.has(t)?iC:ese.has(t)?aC:oC.has(t)?rC:Zoe}function nse(e){return oC.has(sC(e))}function rse(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e)&&e>0:typeof e==`string`?/^\d{8}$/.test(e)||/^\d{4}-\d{2}-\d{2}$/.test(e)||/^\d{8}-\d{2}:\d{2}(:\d{2})?$/.test(e):!1}function ise(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e):typeof e==`string`&&!Number.isNaN(Number(e))}function ase(e,t){let n=[],r=[],i=/* @__PURE__ */ new Map;Array.isArray(t)&&t.length>0&&(typeof t[0]==`string`?t.forEach(e=>i.set(e,void 0)):t.forEach(e=>i.set(e.NAME,e)));for(let t of e){let{field:e,operator:a,value:o}=t;if(!e||typeof e!=`string`){r.push({field:String(e),message:`Field name is required`});continue}let s=i.get(e),c=s&&`TYPE`in s?s.TYPE:`STRING`;if(!tse(c).includes(a)){r.push({field:e,operator:a,value:o,message:`Operator '${a}' is not allowed for field type ${c}`});continue}if((iC.includes(a)||aC.includes(a))&&a!==`dateIsToday`&&!rse(o)){r.push({field:e,operator:a,value:o,message:`Invalid date/datetime value; use yyyyMMdd, yyyy-MM-dd, or epoch`});continue}if(nse(c)&&rC.includes(a)&&!ise(o)){r.push({field:e,operator:a,value:o,message:`Invalid numeric value`});continue}if(i.size>0&&!i.has(e)){r.push({field:e,operator:a,value:o,message:`Unknown field '${e}'`});continue}n.push(t)}return{valid:n,invalid:r}}function ose(e,t){let n=[],r=[];for(let i of e){if(!i?.clauses||!Array.isArray(i.clauses)){r.push({field:``,message:`Group must have a clauses array`});continue}let{valid:e,invalid:a}=ase(i.clauses,t);r.push(...a),e.length>0&&n.push({logic:i.logic??`and`,negated:i.negated,clauses:e})}return{valid:n,invalid:r}}let cC=kd(`foundation-notifications`),lC=null,uC=/* @__PURE__ */ new Map,dC=e=>`${e?.title??`Error`}: ${e?.body??`Something went wrong`}`,sse=e=>e?.logLevel||e?.config?.logLevel||_d.debug,fC=e=>{cC.log({message:dC(e),level:sse(e)})},pC=(e,t)=>{let n=document.querySelector(`#${e}`);if(!n){if(uC.has(e))n=uC.get(e);else{let t=zd(document).find(t=>t.id===e);t&&(n=t,uC.set(e,t))}}if(!n){n=document.createElement(`div`),n.setAttribute(`id`,e),n.style.zIndex=`9999`;let{element:t,prefix:r}=Hd(document.body,`rapid`);if(t)t.appendChild(n),lC=t;else if(lC)lC.appendChild(n);else{let e=document.createElement(`${r}-design-system-provider`);e.appendChild(n),document.body.appendChild(e),lC=e}}return n},cse=e=>{for(;e&&!(e instanceof ShadowRoot);){let t=(e?.getRootNode())?.getElementById(`banner-anchor`);if(t)return t.style.position=`relative`,t;e=e?.getRootNode()?.host}return lse()},lse=()=>{let e=document.createElement(`div`);return e.setAttribute(`id`,`banner-anchor`),e.style.position=`relative`,document.body.insertBefore(e,document.body.firstChild),e},use=e=>{fC(e),alert(dC(e))},dse=(e,t,n)=>{fC(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-banner`),a=cse(n);a?.children?.length>0&&(i.style.position=`absolute`,i.style.top=`0`,i.style.left=`0`,i.style.width=`100%`),a.appendChild(i),i.notification=e},fse=e=>{let t=e.querySelector(`#dialog-container`);return t||(t=document.createElement(`div`),t.setAttribute(`id`,`dialog-container`),t.style.position=`relative`,e.appendChild(t)),t},pse=(e,t,n)=>{fC(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-dialog`);(n?fse(n):pC(`dialog-container`,t)).appendChild(i),i.notification=e,i.show()};var mC;(function(e){e.NOTIFICATION_EVENT=`notification-event`})(mC||(mC={}));var hC;(function(e){e.Top=`top`,e.Bottom=`bottom`})(hC||(hC={}));var gC;(function(e){e.Left=`left`,e.Right=`right`})(gC||(gC={}));let _C=`12px`,mse=(e,t,n)=>{e.style.position=`fixed`,e.style.top=t===hC.Top?_C:``,e.style.bottom=t===hC.Bottom?_C:``,e.style.left=n===gC.Left?_C:``,e.style.right=n===gC.Right?_C:``},hse=(e,t)=>{fC(e);let n=t.split(`-`)[0],r=document.createElement(`${n}-snackbar`),i=e.config?.snackbar?.verticalEdge??hC.Bottom,a=e.config?.snackbar?.horizontalEdge??gC.Left,o=pC(`snack-container-${i}-${a}`,t);o&&mse(o,i,a),o.appendChild(r),r.notification=e},gse=e=>zd(document.body).find(t=>t.tagName.toLowerCase()===`notify-container`&&t.position===e);function _se(e,t){switch(t.style.position=`fixed`,e?.config?.toast?.position){case`top-left`:t.style.top=`var(--nav-height, 0)`,t.style.left=`0`;break;case`bottom-left`:t.style.bottom=`0`,t.style.left=`0`;break;case`bottom-right`:t.style.bottom=`0`,t.style.right=`0`;break;default:t.style.top=`var(--nav-height, 0)`,t.style.right=`0`}}let vC=(e,t,n)=>{var r,i;fC(e);let a=t.split(`-`)[0],o=e?.config?.toast?.position||`top-right`,s=n??gse(o)??pC(`notify-container`,t);s&&s.tagName.toLowerCase()!==`notify-container`&&_se(e,s);let c=document.createElement(`${a}-toast`),l=document.createElement(`div`);l.setAttribute(`slot`,`top`),l.textContent=e.title;let u=document.createElement(`div`);u.setAttribute(`slot`,`content`),u.textContent=e?.body||``;let d=document.createElement(`div`);d.setAttribute(`slot`,`date`),d.textContent=(e?.createdAt)?.toLocaleTimeString()||``;let f;e?.config?.toast?.buttons&&e?.config?.toast?.buttons?.length&&(f=document.createElement(`div`),f.setAttribute(`slot`,`bottom`),e.config.toast.buttons.forEach(t=>{let n=document.createElement(`${a}-button`);n.textContent=t.placeholder||`example placeholder`,n.addEventListener(`click`,()=>{let{details:r}=e.config.toast;if(t.action)return t.action({details:r,buttonElement:n,toastElement:c})}),t.appearance&&n.setAttribute(`appearance`,t.appearance),f.appendChild(n)})),c.setAttribute(`notify`,e?.config?.toast?.type||``),e.iconName&&c.setAttribute(`notification-icon`,e.iconName),(r=e?.config?.toast)!=null&&r.autoClose&&c.setAttribute(`auto-close`,`${e?.config?.toast?.autoClose}`),(i=e?.config?.toast)!=null&&i.closeTimeout&&c.setAttribute(`close-timeout`,`${e?.config?.toast?.closeTimeout}`),c.appendChild(l),c.appendChild(u),c.appendChild(d),f&&c.appendChild(f),s.prepend(c)},yC=(e,t,n)=>{if(!e.title)throw Error(`Title is required`);if(!e.body)throw Error(`Missing required param 'body'`);let r={title:e.title,body:e.body,iconName:e.iconName},i={};e.createdAt&&(r=Object.assign({createdAt:e.createdAt},r)),e.logLevel!=null&&(r=Object.assign({logLevel:e.logLevel},r)),e.toast&&(i=Object.assign({toast:e.toast},i),r=Object.assign({config:i},r)),vC(r,t,n)},vse=O` :host{position: fixed;z-index: 9999;display: flex;flex-direction: column;gap: 4px;box-sizing: border-box;pointer-events: none;/* Allow clicks to pass through empty space */ width: 415px}.toast-container{padding: 0 8px 12px 12px;position: relative}/* Expanded / List State: Allow scrolling if too many items */ :host(:not([stack-collapsed])){max-height: calc(100% - var(--nav-height));overflow: hidden;pointer-events: auto;/* Enable pointer events for scrolling */ slot{display: block;height: calc(100vh - var(--nav-height) - 54px);position: relative}.toast-container{flex: 1;height: 100%;overflow: hidden auto;scrollbar-color: var(--neutral-layer-3) transparent;&:hover{scrollbar-color: var(--neutral-layer-4) transparent}}}.header{display: flex;gap: 12px;pointer-events: none;margin: 5px 24px;justify-content: space-between;visibility: hidden;align-items: center;box-sizing: border-box;.header-title{text-shadow: 0 0 10px #000}.notification-header-buttons{display: flex;gap: 4px;rapid-icon{color: var(--neutral-foreground-hint);margin-left: 4px;display: inline-flex;font-size: 14px;&.chevron-up.collapse{transform: rotate(180deg);transition: transform 0.3s ease}}}--base-height-multiplier: 8;*[appearance='neutral']{font-size: 11px;cursor: pointer;background: var(--neutral-fill-rest)}}.header.visible{visibility: visible;pointer-events: auto;/* Enable clicks on header buttons */}:host([position$='left']) .header{justify-content: space-between}:host([position^='bottom']) .header{margin-bottom: 0;margin-top: 4px}/* Ensure children (toasts) are clickable */ ::slotted(*){pointer-events: auto}:host([position='top-right']){top: var(--nav-height, 0);right: 0}:host([position='top-left']){top: var(--nav-height, 0);left: 0}:host([position='bottom-right']){bottom: 0;right: 0;flex-direction: column-reverse}:host([position='bottom-left']){bottom: 0;left: 0;flex-direction: column-reverse}/* Stacked / Collapsed State */ :host([stack-collapsed]){height: min-content;/* Host allows pointer events so they can reach the slot */ pointer-events: auto;cursor: pointer}/* Apply the grid layout to the slot itself so it acts as the container and click target */ :host([stack-collapsed]) slot{display: grid;grid-template-columns: auto;grid-template-rows: auto;place-items: end center;/* Default to bottom-up stacking */ /* The slot catches the click */ pointer-events: auto}/* Rotate when the collapse class is present */ :host([stack-collapsed][position^='top']) slot{align-items: start}:host([stack-collapsed][position$='right']) slot{justify-items: end}:host([stack-collapsed][position$='left']) slot{justify-items: start}:host([stack-collapsed]) ::slotted(*){grid-area: 1 / 1;transition: transform 0.3s ease, top 0.3s ease, opacity 0.3s ease;opacity: 0%;pointer-events: none !important;/* Disable interaction with toasts in collapsed state */ transform: scale(0.9);top: 0 !important}/* Show and offset the top 3 items in the stack */ :host([stack-collapsed]) ::slotted([data-stack-index='0']){opacity: 100%;pointer-events: auto;transform: translateY(0) scale(1);z-index: 3;position: relative !important}:host([stack-collapsed]) ::slotted([data-stack-index='1']){opacity: 100%;transform: translateY(var(--stack-offset-y, 8px)) scale(0.95);z-index: 2;position: relative !important}:host([stack-collapsed]) ::slotted([data-stack-index='2']){opacity: 100%;transform: translateY(var(--stack-offset-y-2, 16px)) scale(0.9);z-index: 1;position: relative !important}/* Adjust offset direction based on position */ :host([stack-collapsed][position^='top']){--stack-offset-y: 8px;--stack-offset-y-2: 16px}:host([stack-collapsed][position^='bottom']){--stack-offset-y: -8px;--stack-offset-y-2: -16px}`,yse=e=>T`<div class="header ${e=>fn([`visible`,e.slottedNodes.length>1])}">${A(e=>e.showCount,T`<span class="header-title">${e=>e.slottedNodes.length}Notifications</span>`)}<div class="notification-header-buttons">${A(e=>e.allowManualCollapse,T`<${e}-button @click=${e=>e.handleToggleCollapse()}>${e=>e.stackCollapsed?`Expand`:`Collapse`}<${e}-icon class="chevron-up ${e=>fn([`collapse`,e.stackCollapsed])}" name="chevron-up"></${e}-icon></${e}-button>`)} ${A(e=>e.allowCloseAll,T`<${e}-button @click=${e=>e.handleCloseAll()}>
256
256
  Close All <${e}-icon name="xmark"></${e}-icon></${e}-button>`)}</div></div>`,bse=T` ${A(e=>e.allowCloseAll||e.allowManualCollapse,T` ${e=>yse(e.designSystemPrefix)} `)}<div class="toast-container"><slot ${bt(`slottedNodes`)}@click="${e=>e.handleContainerClick()}"></slot></div>`,bC=class extends Qe{constructor(){super(...arguments),this.position=`top-right`,this.stackThreshold=5,this.allowManualCollapse=!0,this.allowCloseAll=!0,this.designSystemPrefix=`rapid`,this.showCount=!0,this.stackCollapsed=!1,this.notificationInterval=0,this.manuallyExpanded=!1,this.pendingQueue=[],this.queueTimer=null,this.queuedNodes=/* @__PURE__ */ new Set,this.mutationObserver=null,this.knownNodes=/* @__PURE__ */ new Set,this.peekingNode=null,this.peekTimer=null,this.routeSubscriber={handleChange:()=>this.checkRoute(Uf.shared.pathName)},this.slottedNodes=[]}connectedCallback(){super.connectedCallback(),(this.position===`bottom-left`||this.position===`bottom-right`)&&cC.error(`NotifyContainer doesn't currently support bottom corner placements`),S.getNotifier(Uf.shared).subscribe(this.routeSubscriber,`pathName`),this.checkRoute(Uf.shared.pathName),this.mutationObserver=new MutationObserver(e=>this.handleMutation(e)),this.mutationObserver.observe(this,{childList:!0})}disconnectedCallback(){var e;super.disconnectedCallback(),S.getNotifier(Uf.shared).unsubscribe(this.routeSubscriber,`pathName`),(e=this.mutationObserver)==null||e.disconnect(),this.mutationObserver=null}checkRoute(e){(e.includes(`/login`)||e.includes(`/logout`))&&(this.pendingQueue=[],this.queuedNodes.clear(),clearTimeout(this.queueTimer),this.queueTimer=null,this.handleCloseAll())}slottedNodesChanged(){if(!this.manuallyExpanded&&!this.stackCollapsed&&this.slottedNodes.length>this.stackThreshold&&(this.stackCollapsed=!0),this.stackCollapsed&&this.slottedNodes.length<=1&&(this.stackCollapsed=!1,this.manuallyExpanded=!1,this.cancelPeek()),this.stackCollapsed){let e=this.slottedNodes.filter(e=>e instanceof HTMLElement&&!this.knownNodes.has(e)).shift();e&&this.maybePeek(e)}this.knownNodes=new Set(this.slottedNodes),this.applySort()}handleContainerClick(){this.stackCollapsed&&(this.stackCollapsed=!1,this.manuallyExpanded=!0,this.cancelPeek())}handleToggleCollapse(){this.stackCollapsed=!this.stackCollapsed,this.manuallyExpanded=!this.stackCollapsed,this.stackCollapsed||this.cancelPeek()}handleCloseAll(){for(this.cancelPeek();this.firstChild;)this.removeChild(this.firstChild);this.stackCollapsed=!1,this.manuallyExpanded=!1}notificationIntervalChanged(e,t){!t&&this.pendingQueue&&this.flushQueue()}handleMutation(e){this.notificationInterval&&(e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&(this.queuedNodes.has(e)?this.queuedNodes.delete(e):(this.removeChild(e),this.pendingQueue.push(e)))})}),this.queueTimer||this.processQueue())}processQueue(){if(!this.pendingQueue.length){this.queueTimer=null;return}let e=this.pendingQueue.shift();this.queuedNodes.add(e),this.prepend(e),this.queueTimer=setTimeout(()=>{this.queueTimer=null,this.processQueue()},this.notificationInterval)}flushQueue(){for(clearTimeout(this.queueTimer),this.queueTimer=null;this.pendingQueue.length;){let e=this.pendingQueue.shift();this.queuedNodes.add(e),this.prepend(e)}}sortFnChanged(){this.applySort()}applySort(){let e=this.slottedNodes.filter(e=>e instanceof HTMLElement);if(!e.length)return;let t=this.sortFn&&e.length>1?[...e].sort(this.sortFn):e;this.peekingNode&&t.includes(this.peekingNode)?this.handlePosition([this.peekingNode,...t.filter(e=>e!==this.peekingNode)]):this.handlePosition(t)}maybePeek(e){let t=this.slottedNodes.filter(e=>e instanceof HTMLElement);if((this.sortFn&&t.length>1?[...t].sort(this.sortFn):t).indexOf(e)===0)return;this.cancelPeek(),this.peekingNode=e;let n=this.notificationInterval?this.notificationInterval/2:1500;this.peekTimer=setTimeout(()=>{this.peekingNode=null,this.peekTimer=null,this.applySort()},n)}cancelPeek(){clearTimeout(this.peekTimer),this.peekTimer=null,this.peekingNode=null}handlePosition(e){if(!e.length)return;e.forEach((t,n)=>{t.style.position=`absolute`,t.style.transition=`all 0.3s ease-in`,t.style.right=`0px`,t.style.zIndex=(e.length-n).toString(),t.dataset.stackIndex=n.toString()});let t=e.map(e=>e.offsetHeight);e.reduce((e,n,r)=>(n.style.top=`${e}px`,e+t[r]),0)}};q([D],bC.prototype,`position`,void 0),q([D({attribute:`stack-threshold`})],bC.prototype,`stackThreshold`,void 0),q([D({attribute:`allow-manual-collapse`,mode:`boolean`})],bC.prototype,`allowManualCollapse`,void 0),q([D({attribute:`allow-close-all`,mode:`boolean`})],bC.prototype,`allowCloseAll`,void 0),q([D({attribute:`design-system-prefix`})],bC.prototype,`designSystemPrefix`,void 0),q([D({attribute:`show-count`,mode:`boolean`})],bC.prototype,`showCount`,void 0),q([D({attribute:`stack-collapsed`,mode:`boolean`})],bC.prototype,`stackCollapsed`,void 0),q([D({attribute:`notification-interval`})],bC.prototype,`notificationInterval`,void 0),q([C],bC.prototype,`sortFn`,void 0),q([C],bC.prototype,`slottedNodes`,void 0),bC=q([$e({name:`notify-container`,template:bse,styles:vse})],bC);let xC={alert:use,toast:vC,dialog:pse,snackbar:hse,banner:dse},SC=(e,t,n)=>{Object.keys(e?.config||{}).forEach(r=>{xC[r]&&xC[r](e,t,n)})};function xse(e){return e.length===0?``:e.length===1?e[0].message:e.map(e=>e.message).join(`; `)}function CC(e,t,n){t?.trim()&&SC({title:e,body:t,config:{toast:{autoClose:!0,closeTimeout:4e3,type:`error`}}},n)}var wC=class extends P{constructor(){super(...arguments),this.placeholder=`Describe your search criteria in natural language...`,this.inputValue=``,this.isInterpreting=!1,this.lastValidCriteria=null,this.activeGroups=[],this.showingChips=!1,this.fieldMetadata=[],this.isRecording=!1,this.stopRecording=null,this.speechApplyDebounceTimer=null}get speechAvailable(){return ox()}get criteriaChips(){return this.activeGroups.flatMap((e,t)=>e.clauses.map((e,n)=>({groupIndex:t,clauseIndex:n,fieldLabel:this.getFieldLabel(e.field),operatorLabel:Qoe[e.operator]??e.operator,valueLabel:e.operator===`dateIsToday`?``:String(e.value??``)})))}getFieldLabel(e){if(!Array.isArray(this.fieldMetadata)||this.fieldMetadata.length===0||typeof this.fieldMetadata[0]==`string`)return e;let t=this.fieldMetadata.find(t=>t.NAME===e);return t?.UI_LABEL??t?.NAME??e}toggleCriteriaView(){this.showingChips?(this.inputValue=``,this.showingChips=!1):this.showingChips=!0}removeChip(e,t){var n;let r=this.activeGroups.map(e=>Object.assign(Object.assign({},e),{clauses:[...e.clauses]}));(n=r[e])==null||n.clauses.splice(t,1);let i=r.filter(e=>e.clauses.length>0);if(this.activeGroups=i,i.length===0)this.showingChips=!1,this.lastValidCriteria=null,this.$emit(`criteria-changed`,null);else{let e=nC(i);this.lastValidCriteria=e,this.$emit(`criteria-changed`,e)}}clearChips(){this.activeGroups=[],this.showingChips=!1,this.lastValidCriteria=null,this.$emit(`criteria-changed`,null)}handleSubmit(){return J(this,void 0,void 0,function*(){let e=this.inputValue?.trim();if(!e||this.isInterpreting)return;let t=this.providerRegistry?.default();if(!t?.interpretCriteria){CC(`AI criteria search`,`AI provider not configured`,Tb(this));return}this.isInterpreting=!0;try{let n=Array.isArray(this.fieldMetadata)?this.fieldMetadata:[],r=yield t.interpretCriteria(e,{fields:n});if(!(r?.groups)?.some(e=>e.clauses?.length)){CC(`AI criteria search`,`AI could not interpret the criteria`,Tb(this)),this.isInterpreting=!1;return}let{valid:i,invalid:a}=ose(r.groups,this.fieldMetadata);if(a.length>0&&(CC(`Criteria validation error`,xse(a),Tb(this)),this.$emit(`validation-errors`,a)),i.length>0){let e=[...this.activeGroups,...i],t=nC(e);this.lastValidCriteria=t,this.activeGroups=e,this.inputValue=``,this.showingChips=!0,this.$emit(`criteria-changed`,t)}}catch(e){CC(`AI criteria search`,e instanceof Error?e.message:`Interpretation failed`,Tb(this))}finally{this.isInterpreting=!1}})}handleBlur(){this.isRecording||(this.inputValue?.trim()?this.handleSubmit():this.activeGroups.length>0&&(this.showingChips=!0))}clear(){this.inputValue=``,this.lastValidCriteria=null,this.activeGroups=[],this.showingChips=!1,this.$emit(`criteria-changed`,null)}toggleSpeechInput(){if(this.isRecording&&this.stopRecording){this.clearSpeechApplyDebounce(),this.stopRecording(),this.stopRecording=null,this.isRecording=!1;return}this.inputValue=``,this.showingChips=!1,this.stopRecording=sx((e,t)=>{this.inputValue=e,t&&e?.trim()&&(this.clearSpeechApplyDebounce(),this.stopRecording&&(this.stopRecording(),this.stopRecording=null,this.isRecording=!1),this.speechApplyDebounceTimer=setTimeout(()=>{this.speechApplyDebounceTimer=null,this.handleSubmit()},700))},()=>{this.clearSpeechApplyDebounce(),this.isRecording=!1,this.stopRecording=null}),this.stopRecording&&(this.isRecording=!0)}clearSpeechApplyDebounce(){this.speechApplyDebounceTimer&&(clearTimeout(this.speechApplyDebounceTimer),this.speechApplyDebounceTimer=null)}};q([ZS],wC.prototype,`providerRegistry`,void 0),q([D],wC.prototype,`placeholder`,void 0),q([D({mode:`boolean`})],wC.prototype,`disabled`,void 0),q([C],wC.prototype,`inputValue`,void 0),q([C],wC.prototype,`isInterpreting`,void 0),q([C],wC.prototype,`lastValidCriteria`,void 0),q([C],wC.prototype,`activeGroups`,void 0),q([C],wC.prototype,`showingChips`,void 0),q([C],wC.prototype,`fieldMetadata`,void 0),q([C],wC.prototype,`isRecording`,void 0),q([w],wC.prototype,`speechAvailable`,null),q([w],wC.prototype,`criteriaChips`,null);let TC={};wC.compose(Object.assign({baseName:`ai-criteria-search`,template:tC,styles:eC,shadowOptions:void 0},TC));let EC=(e,t)=>O` :host{display: flex;justify-content: center;align-items: center;width: 100%;margin: calc(var(--design-unit) * 2px) 0;position: relative;/* Same as connection indicator */ --green: 50 164 49;--trafic-light-green: rgb(var(--green));--red: 187 30 16;--trafic-light-red: rgb(var(--red));--amber: 230 160 20;--trafic-light-amber: rgb(var(--amber))}.ai-indicator-container{display: flex;flex-direction: column;align-items: center;position: relative}.ai-indicator-badge{display: inline-flex;align-items: center;gap: calc(var(--design-unit) * 1.4px);font-size: 12px;line-height: 1;font-weight: 600;text-transform: uppercase;height: calc(var(--design-unit) * 6px);padding: calc(var(--design-unit) * 0.5px) calc(var(--design-unit) * 2px);border-radius: calc(var(--design-unit) * 1px);cursor: pointer;color: #fff}.ai-indicator-badge:hover{opacity: 90%}.ai-indicator-badge.green{background: var(--trafic-light-green)}.ai-indicator-badge.amber{background: var(--trafic-light-amber)}.ai-indicator-badge.red{background: var(--trafic-light-red)}.ai-indicator-badge .ai-indicator-icon{flex-shrink: 0;color: inherit}.ai-indicator-badge.pulsing{animation: ai-indicator-pulse 1.5s ease-in-out infinite}@keyframes ai-indicator-pulse{0%, 100%{opacity: 100%}50%{opacity: 50%}}.ai-indicator-dropdown{position: absolute;top: 100%;right: 0;margin-top: calc(var(--design-unit) * 2px);min-width: 200px;padding: calc(var(--design-unit) * 4px);background: var(--neutral-layer-floating, #fff);border: 1px solid var(--neutral-stroke-rest, #e0e0e0);border-radius: calc(var(--design-unit) * 2px);box-shadow: 0 calc(var(--design-unit) * 1px) calc(var(--design-unit) * 4px) rgb(0 0 0 / 12%);z-index: 1000}.ai-indicator-info{display: flex;flex-direction: column;gap: 0;margin: 0;padding: 0}.ai-indicator-info .info-row{display: grid;grid-template-columns: 72px 1fr;gap: calc(var(--design-unit) * 4px);align-items: baseline;padding: calc(var(--design-unit) * 1.5px) 0;border-bottom: 1px solid var(--neutral-stroke-subtle, #eee)}.ai-indicator-info .info-row:last-child{border-bottom: none}.ai-indicator-info .info-label{margin: 0;font-size: var(--type-ramp-base-font-size);font-weight: 500;color: var(--neutral-foreground-hint, #666)}.ai-indicator-info .info-value{margin: 0;font-size: var(--type-ramp-base-font-size);color: var(--neutral-foreground-rest, #333);text-transform: capitalize;word-break: break-word}.install-button{margin-top: calc(var(--design-unit) * 3px);width: 100%}`,Sse=e=>T` ${A(()=>ix(),T`<div class="ai-indicator-container" part="ai-indicator-container"><div class=${e=>fn(`ai-indicator-badge`,[`green`,e.state===`available`||e.state===`server`],[`amber`,e.state===`downloading`||e.state===`downloadable`],[`red`,e.state===`unavailable`||e.state===`none`],[`pulsing`,e.state===`downloading`||e.isInstalling])}data-test-id="ai-indicator-badge" part="ai-indicator-badge" role="button" tabindex="0" aria-label="AI status" aria-haspopup="true" aria-expanded="${e=>e.open}" @click=${e=>e.toggleDropdown()}@keydown=${(e,t)=>{let n=t.event;(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),e.toggleDropdown())}}><${e}-icon class="ai-indicator-icon" name="wand-magic-sparkles" size="xs" variant="solid" part="ai-indicator-icon"></${e}-icon><span class="ai-indicator-text" data-test-id="ai-indicator-text" part="ai-indicator-text">AI</span></div>${A(e=>e.open,T`<div class="ai-indicator-dropdown" part="ai-indicator-dropdown"><dl class="ai-indicator-info"><div class="info-row"><dt class="info-label">Provider</dt><dd class="info-value">${e=>e.status?.provider??`none`}</dd></div><div class="info-row"><dt class="info-label">Model</dt><dd class="info-value">${e=>e.status?.model||`—`}</dd></div>${A(e=>e.chromeStatusLabel,T`<div class="info-row"><dt class="info-label">Status</dt><dd class="info-value">${e=>e.chromeStatusLabel}</dd></div>`)}</dl>${A(e=>e.canInstall,T`<${e}-button class="install-button" appearance="accent" @click=${(e,t)=>{t.event.preventDefault(),e.onInstall()}}>
257
- Install model </${e}-button>`)}</div>`)}</div>`)} `,DC=T` ${e=>Sse(Tb(e))} `;var OC=class extends P{constructor(){super(...arguments),this.status=null,this.open=!1,this.state=`none`,this.isInstalling=!1,this.pollTimer=null,this.clickOutside=e=>this.handleClickOutside(e)}get aiProvider(){return this.providerRegistry?.default()}get chromeStatusLabel(){if(this.status?.provider!==`chrome`)return null;let e=this.status?.chromeAvailability;return e===`available`?`Installed`:e===`downloading`||this.isInstalling?`Downloading…`:e===`downloadable`?`Downloadable`:e===`unavailable`?`Unavailable`:null}get canInstall(){return!!this.aiProvider?.triggerDownload&&this.status?.provider===`chrome`&&this.status?.chromeAvailability===`downloadable`&&!this.isInstalling}get isDownloading(){return this.status?.chromeAvailability===`downloading`||this.isInstalling}connectedCallback(){let e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});return J(this,void 0,void 0,function*(){e.connectedCallback.call(this),yield this.refreshStatus(),this.maybeStartPolling()})}disconnectedCallback(){this.stopPolling(),document.removeEventListener(`mousedown`,this.clickOutside)}openChanged(){this.open?(document.addEventListener(`mousedown`,this.clickOutside),this.refreshStatus()):document.removeEventListener(`mousedown`,this.clickOutside)}handleClickOutside(e){Cb(e,this)&&(this.open=!1)}toggleDropdown(){this.open=!this.open}refreshStatus(){return J(this,void 0,void 0,function*(){if(!this.aiProvider?.getStatus){this.status=null,this.state=`none`;return}try{let e=yield this.aiProvider.getStatus();this.status=e,this.state=this.deriveState(e),this.state===`available`&&(this.isInstalling=!1)}catch{this.status=null,this.state=`none`,this.isInstalling=!1}})}deriveState(e){if(!e||e.provider===`none`)return`none`;if(e.provider===`chrome`){let t=e.chromeAvailability;return t===`available`?`available`:t===`downloading`?`downloading`:t===`downloadable`?`downloadable`:`unavailable`}return`server`}maybeStartPolling(){this.status?.chromeAvailability===`downloading`||this.isInstalling?this.startPolling():this.stopPolling()}startPolling(){this.pollTimer||(this.pollTimer=setInterval(()=>{this.refreshStatus().then(()=>{this.maybeStartPolling()})},2500))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}onInstall(){return J(this,void 0,void 0,function*(){if(this.canInstall&&this.aiProvider?.triggerDownload){this.isInstalling=!0;try{yield this.aiProvider.triggerDownload(),this.startPolling()}catch{this.isInstalling=!1}finally{yield this.refreshStatus()}}})}};q([ZS],OC.prototype,`providerRegistry`,void 0),q([C],OC.prototype,`status`,void 0),q([C],OC.prototype,`open`,void 0),q([C],OC.prototype,`state`,void 0),q([C],OC.prototype,`isInstalling`,void 0),q([w],OC.prototype,`chromeStatusLabel`,null),q([w],OC.prototype,`canInstall`,null),q([w],OC.prototype,`isDownloading`,null),OC.compose({baseName:`ai-indicator`,template:DC,styles:EC});let kC=(e,t)=>Hn(e,t),AC=(e,t)=>O` ${Fl(e,t)}`;var jC=class extends Il{};let MC={delegatesFocus:!0,mode:`open`},NC={};jC.compose(Object.assign({baseName:`anchor`,template:kC,styles:AC,shadowOptions:MC},NC));let PC=(e,t)=>Kn(e,t),FC=(e,t)=>O` ${Ll(e,t)}`;var IC=class extends Jn{};let LC={delegatesFocus:!0,mode:`open`},RC={};IC.compose(Object.assign({baseName:`anchored-region`,template:PC,styles:FC,shadowOptions:LC},RC));let zC=(e,t)=>tr(e,t),Cse=T` ${A(e=>e.imgSrc,T`<img src="${e=>e.imgSrc}" alt="${e=>e.alt}" slot="media" class="media" part="media" />`)} `,BC=(e,t)=>O` ${Rl(e,t)}`;var VC=class extends zl{};let HC={delegatesFocus:!0,mode:`open`},UC={media:Cse};VC.compose(Object.assign({baseName:`avatar`,template:zC,styles:BC,shadowOptions:HC},UC));let WC=(e,t)=>rr(e,t),GC=(e,t)=>O` ${Bl(e,t)}`;var KC=class extends ir{};let qC={};KC.compose(Object.assign({baseName:`badge`,template:WC,styles:GC,shadowOptions:void 0},qC));let JC=O` @keyframes delete-animate{from{height: 100px;opacity: 100%}to{height: 0;opacity: 0%}}@keyframes append-animate{from{height: 0;opacity: 0%}to{height: var(--banner-height);opacity: 100%}}:host{--banner-width: 100%;--banner-height: 65px;--flow: row}@media screen and (max-width: 640px){:host{--flow: column;--banner-height: 100px}}.banner{animation: append-animate 0.3s linear;width: var(--banner-width);height: var(--banner-height);background-color: var(--fill-color);display: flex;flex-direction: var(--flow);padding: 5px 8px;box-sizing: border-box;overflow: hidden}.banner-delete{animation: delete-animate 0.3s linear;opacity: 0%}.content{display: flex;align-items: center;flex: 2;font-size: 12px;overflow: hidden;white-space: pre-line}.action{display: flex;flex-direction: row-reverse;align-items: center;gap: 10px;flex: 1;overflow: hidden}`,wse=e=>T`<div role="alert" aria-live="polite" class="banner ${e=>e.dismissAnimation}" ${k(`banner`)}><div part="content" class="content"><slot name="content">${A(e=>e.notification,T`<div><div>${e=>e.notification?.body||`Place holder for notification message`}</div></div>`)}</slot></div><div part="action" class="action"><slot name="action" class="action">${A(e=>e.notification,T`<${e}-button slot="action" appearance="lightweight" @click=${e=>e.dismiss()}>${e=>e.notification?.config?.banner?.dismissingAction?.label||`Ignore`}</${e}-button>`)} ${j(e=>(e.notification?.config)?.banner.confirmingActions,T`<${e}-button slot="action" appearance="lightweight" @click=${(e,t)=>{var n;e?.action(),(n=t.parent)==null||n.dismissNotification()}}>${e=>e.label}</${e}-button>`)}</slot></div></div>`,YC=T` ${e=>wse(Tb(e))} `,XC={mode:`open`,delegatesFocus:!0};var ZC=class extends P{constructor(){super(...arguments),this.dismissAnimation=``}connectedCallback(){super.connectedCallback()}dismiss(){return this.dismissAnimation=`banner-delete`,new Promise(e=>{this.banner.onanimationend=()=>{this.remove(),e()}})}dismissNotification(){return J(this,void 0,void 0,function*(){try{yield this.dismiss(),this.remove()}catch(e){xb.error(e)}})}};q([C],ZC.prototype,`dismissAnimation`,void 0),q([C],ZC.prototype,`notification`,void 0),ZC.compose({baseName:`banner`,styles:JC,template:YC,shadowOptions:XC});let QC=(e,t)=>sr(e,t),$C=(e,t)=>O` ${Hl(e,t)}`;var ew=class extends cr{};ew.compose(Object.assign({baseName:`breadcrumb`,template:QC,styles:$C,shadowOptions:void 0},{}));let tw=(e,t)=>ar(e,t),nw=(e,t)=>O` ${Vl(e,t)}`;var rw=class extends or{};let iw={separator:`/`};rw.compose(Object.assign({baseName:`breadcrumb-item`,template:tw,styles:nw,shadowOptions:void 0},iw));let aw=(e,t)=>lr(e,t),ow=(e,t)=>O` ${Ul(e,t)}`;var sw=class extends Wl{};let cw={delegatesFocus:!0,mode:`open`},lw={};sw.compose(Object.assign({baseName:`button`,template:aw,styles:ow,shadowOptions:cw},lw));let uw=()=>O` ${Gl}`,dw=(e,t)=>jr(e,t);var fw=class extends xr{};let pw={delegatesFocus:!0,mode:`open`},mw={};fw.compose(Object.assign({baseName:`calendar`,template:dw,styles:uw,shadowOptions:pw},mw));let hw=(e,t)=>Mr(e,t),gw=(e,t)=>O` ${Kl(e,t)} :host{background-color: var(--fui-card-fill-color);color: var(--fui-card-foreground-color)}`;var _w=class extends ql{};let vw={};_w.compose(Object.assign({baseName:`card`,template:hw,styles:gw,shadowOptions:void 0},vw));var yw;(function(e){e.BELOW=`below`,e.ABOVE=`above`})(yw||(yw={}));var bw=/* @__PURE__ */ u((/* @__PURE__ */ s(((e,t)=>{var n=NaN,r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,o=/^0o[0-7]+$/i,s=parseInt,c=typeof global==`object`&&global&&global.Object===Object&&global,l=typeof self==`object`&&self&&self.Object===Object&&self,u=c||l||Function(`return this`)(),d=Object.prototype.toString,f=Math.max,p=Math.min,m=function(){return u.Date.now()};function h(e,t,n){var r,i,a,o,s,c,l=0,u=!1,d=!1,h=!0;if(typeof e!=`function`)throw TypeError(`Expected a function`);t=y(t)||0,g(n)&&(u=!!n.leading,d=`maxWait`in n,a=d?f(y(n.maxWait)||0,t):a,h=`trailing`in n?!!n.trailing:h);function _(t){var n=r,a=i;return r=i=void 0,l=t,o=e.apply(a,n),o}function v(e){return l=e,s=setTimeout(x,t),u?_(e):o}function b(e){var n=e-c,r=e-l,i=t-n;return d?p(i,a-r):i}function ee(e){var n=e-c,r=e-l;return c===void 0||n>=t||n<0||d&&r>=a}function x(){var e=m();if(ee(e))return te(e);s=setTimeout(x,b(e))}function te(e){return s=void 0,h&&r?_(e):(r=i=void 0,o)}function ne(){s!==void 0&&clearTimeout(s),l=0,r=c=i=s=void 0}function S(){return s===void 0?o:te(m())}function C(){var e=m(),n=ee(e);if(r=arguments,i=this,c=e,n){if(s===void 0)return v(c);if(d)return s=setTimeout(x,t),_(c)}return s===void 0&&(s=setTimeout(x,t)),o}return C.cancel=ne,C.flush=S,C}function g(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function _(e){return!!e&&typeof e==`object`}function v(e){return typeof e==`symbol`||_(e)&&d.call(e)==`[object Symbol]`}function y(e){if(typeof e==`number`)return e;if(v(e))return n;if(g(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=g(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(r,``);var c=a.test(e);return c||o.test(e)?s(e.slice(2),c?2:8):i.test(e)?n:+e}t.exports=h})))());let xw=O` :host{--scrollbar-width: 12px;--scrollbar-thumb-width: 8px}.root{position: relative;width: inherit;min-width: 250px}.control{cursor: pointer;position: relative;display: flex;align-items: center;width: 100%;border-radius: calc(var(--control-corner-radius) * 1px)}#display-field{width: 100%;cursor: pointer;color: var(--neutral-foreground-rest);min-height: 40px;padding: 0 calc(var(--design-unit) * 2.25px);border-width: 0;background-color: var(--neutral-fill-input-rest);border-radius: calc(var(--control-corner-radius) * 1px)}#display-field[disabled]{cursor: not-allowed;opacity: 30%}#display-field:focus{outline: 1px solid var(--accent-fill-rest);background: var(--neutral-fill-input-rest);border-style: none;box-shadow: none}#display-field:hover:not(:focus):not([disabled]){outline: 1px solid var(--neutral-stroke-hover)}button{pointer-events: none}.indicator{position: absolute;left: calc(100% - 26px);padding: 0;cursor: pointer}#arrow-icon{width: 16px;fill: white;transform: rotate(0deg);transition: transform 0.2s linear 0s}#arrow-icon.flipped{transform: rotate(180deg)}.disabled-svg{pointer-events: none;opacity: 30%}.position-above{bottom: 100%}::-webkit-scrollbar{width: var(--scrollbar-width)}::-webkit-scrollbar-track{background: var(--neutral-layer-4)}::-webkit-scrollbar-thumb{width: var(--scrollbar-thumb-width);border-radius: 10px;box-shadow: inset 0 0 6px rgba(0 0 0 / 30%);background-color: var(--neutral-layer-2);border: 3px solid var(--neutral-layer-4)}::-webkit-scrollbar-corner{background: var(--neutral-layer-4)}.multiselect-dropdown{display: flex;flex-direction: column;position: absolute;height: max-content;overflow: hidden;margin-top: calc(var(--design-unit) * 1px);border: calc(var(--stroke-width) * 1px) solid var(--neutral-layer-2);border-radius: 4px;background: var(--neutral-fill-input-rest);width: 100%;max-height: 0;visibility: hidden;z-index: 999}.multiselect-dropdown:not(.is-resizing){transition: max-height 0.4s ease 0s, visibility 0.4s ease 0s}.checkbox-container{display: flex;flex-direction: column;list-style: none;overflow-y: auto;height: 100%}.is-resizing .checkbox-container{overflow-y: hidden}.checkbox-container foundation-checkbox[disabled]{cursor: not-allowed}.visible{visibility: visible;max-height: var(--custom-max-height, ${`230`}px);overflow: hidden}::slotted(foundation-checkbox), foundation-checkbox{border-bottom: 1px solid var(--neutral-layer-4);padding: 5px 0 5px 5px;margin: 0}::slotted(foundation-checkbox:hover), foundation-checkbox:hover{background-color: var(--neutral-layer-3);cursor: pointer}::slotted(foundation-checkbox)::part(label), foundation-checkbox::part(label){overflow-x: hidden;text-overflow: ellipsis;white-space: nowrap}.label{display: block;cursor: pointer;font-size: var(--type-ramp-base-font-size);line-height: var(--type-ramp-base-line-height);font-style: normal;margin: calc(var(--design-unit) * 2px) 0}.label-hidden{display: none}ol, li{margin: 0;padding: 0}.checkbox{width: 100%}.select-all{width: 100%;margin-left: 0;margin-right: 0}.display-value{position: absolute;right: 40px;color: var(--neutral-foreground-rest);font-size: var(--type-ramp-base-font-size);line-height: var(--type-ramp-base-line-height);font-family: var(--body-font)}.options-header-item-hidden{display: none}.resize-button{position: absolute;bottom: 0;right: 0;width: 12px;height: 12px;cursor: nw-resize;background: linear-gradient( -45deg, transparent 30%, var(--neutral-foreground-rest) 30%, var(--neutral-foreground-rest) 40%, transparent 40%, transparent 60%, var(--neutral-foreground-rest) 60%, var(--neutral-foreground-rest) 70%, transparent 70% );z-index: 1000;opacity: 60%;transition: opacity 0.2s ease}.resize-button:hover{opacity: 100%}.multiselect-dropdown.resizable{resize: none;overflow: hidden}`;var Sw;let Cw=Sw=class extends Sb{constructor(){super(...arguments),this.emptyDataLabel=`No matching records`,this.allowCustomOptions=!1,this.infiniteScroll=!1,this.pageSize=Sw.defaultPageSize,this.initalSelectedValueInitialized=!1,this.isSnapshot=!0,this.baseCriteria=``,this.listboxElement=null,this.loadingMoreRows=!1,this.renderedOptionsCount=0,this.lastTopUpScrollHeight=-1,this.emptyDataOption=null,this.selectOpenChangeHandler=e=>{e.detail?.open&&(this.listboxElement||this.attachListboxScrollListener(),this.topUpVisibleListbox())},this.listboxScrollHandler=()=>{let e=this.listboxElement;e&&this.isNearListboxBottom(e)&&this.loadNextPage()},this.resizeObserverCallback=e=>{e.forEach(e=>{this.checkOverflow(e.target)})},this.selectChangeHandler=e=>{let t=e.target.value,n=this.options?.find(e=>String(e.label)===t);!n&&this.allowCustomOptions&&this.select instanceof Ql?this.select.$emit(`value-change`,{label:t,value:t}):this.select.$emit(`value-change`,n)}}initialSelectedValueChanged(e,t){if(t!==e){if(!t){this.select&&(this.initalSelectedValueInitialized=!1,this.clearData(),this.resetCombobox(),this.fetchData());return}this.select&&this.getDisplayForValue(t)===String(this.select.value||``)||(this.initalSelectedValueInitialized=!1,this.clearData(),this.fetchData())}}connectedCallback(){let e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});return J(this,void 0,void 0,function*(){if(e.connectedCallback.call(this),this.baseCriteria=this.criteria,this.fields=this.labelField?this.valueField?.concat(` `,this.labelField):this.valueField,this.select=this.parentElement,this.optionElement=this.optionElement??`${Tb(this.select)}-option`,this.select.addEventListener(`change`,this.selectChangeHandler),this.resizeObserver=new ResizeObserver(this.resizeObserverCallback),this.infiniteScroll){if(this.isSnapshot=!0,this.maxRows=this.pageSize>0?this.pageSize:Sw.defaultPageSize,this.select.addEventListener(`open-change`,this.selectOpenChangeHandler),yield this.applyInfiniteScrollFetchMode(),!this.isConnected)return;x.queueUpdate(()=>this.attachListboxScrollListener())}this.fetchData(),this.valueField||xb.warn(`Specify field for values in options (e.g value-field="VALUE") and optionally field for label (e.g label-field="NAME")`)})}disconnectedCallback(){var e;super.disconnectedCallback(),this.resizeObserver.disconnect(),(e=this.listboxElement)==null||e.removeEventListener(`scroll`,this.listboxScrollHandler),this.listboxElement=null,this.select.removeEventListener(`open-change`,this.selectOpenChangeHandler),this.select.removeEventListener(`change`,this.selectChangeHandler)}applyInfiniteScrollFetchMode(){return J(this,void 0,void 0,function*(){if(this.resourceName&&this.connect.isConnected)try{let e=yield this.resources.getResourceTypeFor(this.resourceName);this.isSnapshot=e!==ag.DATASERVER}catch(e){xb.warn(`Unable to determine the resource type for ${this.resourceName}`,e)}})}attachListboxScrollListener(){var e;if(this.isConnected){if((e=this.listboxElement)==null||e.removeEventListener(`scroll`,this.listboxScrollHandler),this.listboxElement=this.select?.scrollableListbox??this.select?.listbox??(this.select?.shadowRoot)?.querySelector(`.listbox`),!this.listboxElement){xb.warn(`Unable to locate listbox element, infinite scroll will not be available.`);return}this.listboxElement.addEventListener(`scroll`,this.listboxScrollHandler)}}isNearListboxBottom(e){return e.scrollTop+e.clientHeight>=e.scrollHeight-Sw.scrollLoadThresholdPx}loadNextPage(){return J(this,void 0,void 0,function*(){if(this.loadingMoreRows||!this.canRequestMoreRows())return;this.loadingMoreRows=!0;let e=this.datasource.resourceType===ag.REQUEST_SERVER;try{yield this.requestMoreRows()}catch{this.loadingMoreRows=!1;return}e&&(this.loadingMoreRows=!1)})}topUpVisibleListbox(){this.infiniteScroll&&requestAnimationFrame(()=>{if(!this.isConnected)return;let e=this.listboxElement;e&&e.clientHeight!==0&&this.isNearListboxBottom(e)&&e.scrollHeight!==this.lastTopUpScrollHeight&&(this.lastTopUpScrollHeight=e.scrollHeight,this.loadNextPage())})}fetchData(){this.select&&this.valueField&&(this.resourceName&&this.connect.isConnected||this.data)&&(this.select instanceof Ql&&this.select.async&&this.initialSelectedValue?this.asyncModeIntialization():this.fetchGenesisData())}asyncModeIntialization(){return J(this,void 0,void 0,function*(){if(!(yield this.datasource.init(this.datasourceOptions(),!0))){this.handleError({message:`Genesis Datasource async mode initialization failed for ${this.resourceName}`,loggerType:`error`});return}Gb(this,this.initialSelectedValue)})}clearData(){this.rowsSyncedWithStream.clear(),this.options=[],this.renderedOptionsCount=0,this.lastTopUpScrollHeight=-1,this.emptyDataOption=null,this.loadingMoreRows=!1,this.select&&(Array.from(this.select.children).forEach(e=>{e instanceof Sw||this.select.removeChild(e)}),this.select.value=``,this.select.initialValue=``)}checkOverflow(e){let t=e.shadowRoot.querySelector(`.content`);t&&(t.scrollWidth>t.clientWidth?e.setAttribute(`title`,e.textContent):e.removeAttribute(`title`))}rowToOption(e){return{value:e[this.valueField],label:this.labelRowFormatter?this.labelRowFormatter(e):this.labelFormatter?this.labelFormatter(e[this.labelField]):this.getDefaultLabelFormat(e[this.labelField],this.getFieldMetadata(this.labelField)?.type)}}renderListboxOptions(e){e.forEach(({value:e,label:t})=>{let n=document.createElement(this.optionElement);n.textContent=t||e,n.value=e,this.select.appendChild(n),this.resizeObserver.observe(n)})}removeEmptyDataOption(){this.emptyDataOption&&(this.emptyDataOption.remove(),this.emptyDataOption=null)}syncComponentData(e){this.loadingMoreRows=!1;let t=e??Array.from(this.rowsSyncedWithStream.values());if(t.length>0){this.removeEmptyDataOption(),this.options=t.map(e=>this.rowToOption(e));let e=this.renderedOptionsCount===0;if(this.renderListboxOptions(this.options.slice(this.renderedOptionsCount)),this.renderedOptionsCount=this.options.length,this.nextRequestOffset=Math.max(this.nextRequestOffset,this.renderedOptionsCount),this.topUpVisibleListbox(),!this.initalSelectedValueInitialized||this.select instanceof Ql&&!this.select.async&&e){this.resetCombobox();let e=this.getInitialLabel();x.queueUpdate(()=>{this.select.value=String(e),e&&this.select instanceof Ql&&this.select.async&&this.selectChangeHandler({target:{value:e}})}),this.initalSelectedValueInitialized=!0}}else if(this.allowCustomOptions&&this.initialSelectedValue&&(!this.initalSelectedValueInitialized||this.select instanceof Ql&&!this.select.async)&&(this.resetCombobox(),x.queueUpdate(()=>{this.select.value=String(this.initialSelectedValue)}),this.initalSelectedValueInitialized=!0),this.select&&!this.emptyDataOption){let e=document.createElement(this.optionElement);e.textContent=this.emptyDataLabel,e.value=``,e.disabled=!0,this.select.appendChild(e),this.emptyDataOption=e}}getInitialLabel(){return this.getDisplayForValue(this.initialSelectedValue)}getDisplayForValue(e){if(e==null||e!==0&&!e)return``;let t=this.options?.find(t=>t.value===e);return this.allowCustomOptions&&this.select instanceof Ql?String(t?t.label:e):t?String(t.label):``}resetCombobox(){this.select&&this.select instanceof Ql&&this.select.resetCombobox()}handleStreamInserts(e){if(this.loadingMoreRows=!1,!e?.length)return;this.removeEmptyDataOption();let t=new Set((this.options??[]).map(e=>String(e.value))),n=e.filter(e=>!t.has(String(e[this.valueField])));if(!n.length){xb.warn(`Infinite scroll for ${this.resourceName} received a page of options that were all already loaded, so paging has stopped. Request Server resources only honour OFFSET when declared with criteriaOnlyRequest; otherwise every page returns the same rows. Also set a stable order-by so pages cannot overlap.`),this.moreRowsAvailable=!1;return}let r=n.map(e=>this.rowToOption(e));this.options=[...this.options??[],...r],this.renderListboxOptions(r),this.renderedOptionsCount=this.options.length,this.nextRequestOffset=Math.max(this.nextRequestOffset,this.renderedOptionsCount),this.topUpVisibleListbox()}handleStreamDeletes(e){xb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){xb.debug(`handleStreamUpdates - Method not implemented.`)}};Cw.defaultPageSize=20,Cw.scrollLoadThresholdPx=32,q([Xy],Cw.prototype,`resources`,void 0),q([D({attribute:`label-field`})],Cw.prototype,`labelField`,void 0),q([D({attribute:`option-element`})],Cw.prototype,`optionElement`,void 0),q([D({attribute:`value-field`})],Cw.prototype,`valueField`,void 0),q([D({attribute:`empty-data-label`})],Cw.prototype,`emptyDataLabel`,void 0),q([D({mode:`boolean`,attribute:`allow-custom-options`})],Cw.prototype,`allowCustomOptions`,void 0),q([D({mode:`boolean`,attribute:`infinite-scroll`})],Cw.prototype,`infiniteScroll`,void 0),q([D({attribute:`page-size`,converter:E})],Cw.prototype,`pageSize`,void 0),q([C],Cw.prototype,`labelFormatter`,void 0),q([C],Cw.prototype,`labelRowFormatter`,void 0),q([C],Cw.prototype,`initialSelectedValue`,void 0),Cw=Sw=q([$e({name:`options-datasource`})],Cw);let ww=class extends Sb{constructor(){super(...arguments),this.isSnapshot=!0,this.baseCriteria=``}connectedCallback(){let e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});return J(this,void 0,void 0,function*(){e.connectedCallback.call(this),this.baseCriteria=this.criteria,this.fields=this.labelField?this.valueField?.concat(` `,this.labelField):this.valueField,this.select=this.parentElement,this.select&&this.valueField&&(this.resourceName&&this.connect.isConnected||this.data)&&this.fetchGenesisData(),this.valueField||xb.warn(`Specify field for values in options (e.g value-field="VALUE") and optionally field for label which is supported only in select and combobox (e.g label-field="NAME")`)})}clearData(){this.select.options=[]}syncComponentData(e){let t=(e??Array.from(this.rowsSyncedWithStream.values())).map(e=>({value:e[this.valueField],label:this.getDefaultLabelFormat(e[this.labelField],this.getFieldMetadata(this.labelField)?.type)}));this.select?.async&&(this.select.loading=!1),this.select.options=t}handleStreamInserts(e){xb.debug(`handleStreamInserts - Method not implemented.`)}handleStreamDeletes(e){xb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){xb.debug(`handleStreamUpdates - Method not implemented.`)}};q([D({attribute:`value-field`})],ww.prototype,`valueField`,void 0),q([D({attribute:`label-field`})],ww.prototype,`labelField`,void 0),ww=q([$e({name:`multiselect-datasource`})],ww);let Tw=(e=`foundation`)=>T`<label part="label" for="display-field" class=${e=>fn(`label`,[`label-hidden`,!e.defaultSlottedNodes?.length])}><slot name="label" ${bt({property:`defaultSlottedNodes`,filter:ga})}></slot></label><div class="root" part="root" @keydown="${(e,t)=>e.keydownHandler(t.event)}"><div class="control" part="control"><input id="display-field" part="filter-search" role="combobox" aria-haspopup="listbox" aria-controls="checkbox-container" aria-expanded=${e=>e.open?`true`:`false`}tabindex="${e=>e.tabindex}" ?readonly=${e=>!e.search}@click=${e=>e.toggle()}?disabled="${e=>e.disabled}" ${k(`filterSearchInput`)}value=${df(e=>e.filterSearchValue,`string`,`input`)}placeholder="${e=>e.getDisplayValue}" autocomplete="off" @input=${(e,t)=>e.inputHandler()}@change=${(e,t)=>e.changeHandler(t.event)}/><div part="indicator" class="indicator" @click=${e=>!e.disabled&&e.toggle()}><svg viewBox="0 0 12 7" ${k(`arrowIcon`)}id="arrow-icon" class="${e=>fn([`disabled-svg`,e.disabled])}" xmlns="http://www.w3.org/2000/svg"><path d="${`M11.85.65c.2.2.2.5 0 .7L6.4 6.84a.55.55 0 01-.78 0L.14 1.35a.5.5 0 11.71-.7L6 5.8 11.15.65c.2-.2.5-.2.7 0z`}" /></svg></div>${A(e=>e.filterSearchValue&&e.selectedOptions.length,T`<div class="display-value">${e=>e.getDisplayValue}</div>`)}</div>${A(e=>e.loading,T`<${e}-progress slot="indicator"></${e}-progress>`)}<section class=${e=>fn(`multiselect-dropdown`,[`resizable`,e.resizable])} ${k(`multiselectDropdown`)}part="multiselect-dropdown">${A(e=>e.resizable,T`<div class="resize-button" @mousedown=${(e,t)=>e.handleResizeStart(t.event)}></div>`)} ${A(e=>e.all,T`<${e}-button class="select-all" @click=${e=>e.selectCheckboxAll()}?disabled="${(e,t)=>e.isAllOptionsDisabled}">${e=>e.areAllOptionsSelected?`Deselect All`:`Select All`} ${e=>e.name}</${e}-button>`)}<ol id="checkbox-container" class="checkbox-container options" aria-multiselectable="true" part="options-ol"><li part="options-header-item" class=${e=>fn(`options-header-item`,[`options-header-item-hidden`,!e.optionsHeaderSlottedNodes?.length])}><slot name="options-header" ${bt({property:`optionsHeaderSlottedNodes`,filter:ga})}></slot></li>${j(e=>e.filteredAvailableOptions,T`<li role="option" value=${(e,t)=>t.parent.getItemLabel(e)}part="option"><${e}-checkbox part="checkbox" class="checkbox" exportparts="label:checkbox-label" @keydown=${(e,t)=>t.parent.checkboxKeyDown(e,t.event)}@click=${(e,t)=>t.parent.selectCheckboxOne(e)}@change=${(e,t)=>t.parent.changeHandler(t.event)}?current-checked="${(e,t)=>t.parent.isOptionSelected(e)}" ?disabled="${(e,t)=>t.parent.isOptionDisabled(e)}">${(e,t)=>{var n;return((n=t.parent)?.itemRenderer)?.call(n,e,t.parent)}}</${e}-checkbox></li>`)}</ol>${A(e=>e.showCreatable,T`<${e}-button @click=${e=>e.addOption()}>Create&nbsp;"${e=>e.filterSearchValue}"</${e}-button>`)}</section></div><slot ${bt({property:`slottedDatasource`,filter:e=>e instanceof ww})}></slot>`,Tse=T` ${Tw()} `,Ew={};var Dw=class extends P{constructor(){super(...arguments),this.name=``,this.autoPosition=!0,this.all=!0,this.allSelected=!1,this.search=!0,this.disabled=!1,this.creatable=!1,this.async=!1,this.debounce=500,this.resizable=!1,this.filterByContains=!1,this.filterSearchValue=``,this.clickOutside=e=>this.handleClickOutside(e),this.open=!1,this.options=[],this.selectedOptions=[],this.filteredAvailableOptions=[...this.options],this.position=yw.BELOW,this.itemRenderer=this.defaultItemRenderer,this.initialisedOptions=!1,this.isResizing=!1,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.handleResizeStart=e=>{this.resizable&&this.multiselectDropdown&&(e.preventDefault(),e.stopPropagation(),this.isResizing=!0,this.startX=e.clientX,this.startY=e.clientY,this.startWidth=this.multiselectDropdown.offsetWidth,this.startHeight=this.multiselectDropdown.offsetHeight,this.multiselectDropdown.classList.add(`is-resizing`),document.addEventListener(`mousemove`,this.handleResizeMove),document.addEventListener(`mouseup`,this.handleResizeEnd))},this.handleResizeMove=e=>{if(!this.isResizing||!this.multiselectDropdown)return;e.preventDefault();let t=e.clientX-this.startX,n=e.clientY-this.startY,r=Math.max(250,this.startWidth+t),i=Math.max(100,this.startHeight+n);this.multiselectDropdown&&(this.multiselectDropdown.style.width=`${r}px`,this.multiselectDropdown.style.maxHeight=`${i}px`)},this.handleResizeEnd=()=>{this.isResizing=!1,document.removeEventListener(`mousemove`,this.handleResizeMove),document.removeEventListener(`mouseup`,this.handleResizeEnd),this.multiselectDropdown&&(this.multiselectDropdown.classList.remove(`is-resizing`),this.multiselectDropdown.style.setProperty(`--custom-max-height`,this.multiselectDropdown.style.maxHeight),this.multiselectDropdown.style.removeProperty(`max-height`))}}debounceChanged(e,t){this.debouncedInputHandler=(0,bw.default)(this.asyncSetFilter,t)}openChanged(e,t){var n,r,i,a;t?(document.addEventListener(`mousedown`,this.clickOutside),(n=this.arrowIcon)==null||n.classList.add(`flipped`),(r=this.multiselectDropdown)==null||r.classList.add(`visible`)):(document.removeEventListener(`mousedown`,this.clickOutside),(i=this.arrowIcon)==null||i.classList.remove(`flipped`),(a=this.multiselectDropdown)==null||a.classList.remove(`visible`))}connectedCallback(){var e;super.connectedCallback(),this.position===yw.ABOVE&&((e=this.multiselectDropdown)==null||e.classList.add(`position-above`))}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`mousedown`,this.clickOutside),document.removeEventListener(`mousemove`,this.handleResizeMove),document.removeEventListener(`mouseup`,this.handleResizeEnd)}defaultItemRenderer(e,t){return T` ${typeof e==`string`?T`<span part="option-label">${()=>t.getItemLabel(e)}</span>`:T`<span data-option-label-text=${()=>e.optionLabelText}style=${()=>e.labelStyle}part="option-label">${()=>t.getItemLabel(e)}</span>`} `}toggle(){this.open||this.setDropdownPosition(),this.open=!this.open}optionsChanged(){this.allSelected&&!this.initialisedOptions&&(this.selectedOptions=this.options.map(e=>this.optionValueGetter(e))),this.filteredAvailableOptions=[...this.options]}selectedOptionsChanged(){if(this.$fastController.isConnected){this.initialisedOptions=!0;return}}setDropdownPosition(){let e=this.position;if(this.autoPosition){let t=this.getBoundingClientRect(),n=window.innerHeight,r=t.top,i=n-t.bottom;e=i<230&&r>i?yw.ABOVE:yw.BELOW}this.multiselectDropdown.classList.toggle(`position-above`,e===yw.ABOVE),this.multiselectDropdown.classList.toggle(`position-below`,e===yw.BELOW)}optionValueGetter(e){return typeof e==`string`?e:e.value}optionLabelGetter(e){return typeof e==`string`?e:e.label}getItemLabel(e){let t;return e?(t=typeof e==`string`?e:this.optionLabelGetter(e)||this.optionValueGetter(e)||``,this.valueFormatter?this.valueFormatter(t):t):``}isOptionDisabled(e){return!e||typeof e==`string`?!1:e.disabled||!1}get getDisplayValue(){let e=this.selectedOptions.length;if(e===0)return this.getPlaceholder;if(e===1){let e=this.options.find(e=>this.isOptionSelected(e));if(e)return this.getItemLabel(e);let[t]=this.selectedOptions;return typeof t==`string`?this.getItemLabel(t):`1 Selected`}return e===this.options.length&&this.options.every(e=>this.isOptionSelected(e))?`All ${this.name}`.trim():`${e} Selected`}get getPlaceholder(){return`Search ${this.name}`.trim().concat(`...`)}get isAllOptionsDisabled(){return this.options.length===this.options.filter(this.isOptionDisabled).length}get areAllOptionsSelected(){let e=this.options.filter(e=>!this.isOptionDisabled(e));return e.length>0&&e.every(e=>this.isOptionSelected(e))}get showCreatable(){return this.creatable&&this.filterSearchValue.trim().length>0&&this.findExactMatchOptions().length===0}isOptionSelected(e){let t=this.optionValueGetter(e);return this.selectedOptions.some(n=>{if(typeof e==`object`&&typeof e.value==`object`)try{return JSON.stringify(n)===JSON.stringify(t)}catch{return n===t}return n===t})}selectCheckboxOne(e){let t=this.optionValueGetter(e);this.selectedOptions=this.selectedOptions.includes(t)?this.selectedOptions.filter(e=>e!==t):[...this.selectedOptions,t],this.updateSelection(this.selectedOptions)}checkboxKeyDown(e,t){return t.key===` `&&(t.preventDefault(),this.selectCheckboxOne(e)),!0}getEnabledOptionsCount(){return this.options.length-this.options.filter(this.isOptionDisabled).length}selectCheckboxAll(){let e=this.areAllOptionsSelected;this.selectedOptions=e?[]:this.options.filter(e=>!this.isOptionDisabled(e)).map(e=>this.optionValueGetter(e)),this.onAllSelectedCallback&&this.onAllSelectedCallback(!e),this.updateSelection(this.selectedOptions)}inputHandler(){this.open||(this.open=!0),this.async?(this.loading=!0,this.filteredAvailableOptions=[],this.debouncedInputHandler()):this.setFilter()}findExactMatchOptions(){let e=this.filterSearchValue.toLowerCase();return this.filteredAvailableOptions.filter(t=>((typeof t==`string`?t:this.optionLabelGetter(t)??this.optionValueGetter(t))?.toLowerCase()??``)===e)}setFilter(){let e=this.filterSearchValue.toLowerCase();this.filteredAvailableOptions=this.options.filter(t=>{if(!e)return!0;if(typeof t==`string`)return t.toLowerCase().includes(e);let n=t.label.toLowerCase(),r=typeof t.value==`object`?(t=>Object.values(t).some(t=>t.toLowerCase().includes(e)))(t.value):String(t.value).toLowerCase().includes(e);return n.includes(e)||r})}updateSelection(e){this.selectedOptions=e,this.$emit(`selectionChange`,this.selectedOptions)}addOption(){let e=this.filterSearchValue.trim();if(!e||this.options.some(t=>this.optionValueGetter(t)===e))return;let t={value:e,label:e};this.$emit(`optionCreated`,t)!==!1&&(this.options=[t,...this.options],this.setFilter(),this.updateSelection([...this.selectedOptions,e]))}asyncSetFilter(){this.slottedDatasource.length>0?Wb(this.slottedDatasource[0],this.filterSearchValue):(this.loading=!1,xb.warn(`Multiselect-datasource is not connected. Please add a datasource to use this functionality.`))}changeHandler(e){e.preventDefault(),e.stopImmediatePropagation()}handleClickOutside(e){Cb(e,this)&&(this.open=!1)}keydownHandler(e){let t=e.key;if(e.ctrlKey||e.shiftKey)return!0;switch(t){case`Escape`:if(this.open){this.open=!1;break}break;case`ArrowUp`:case`ArrowDown`:if(!this.open){this.open=!0;break}break;default:return!0}}clear(e={}){let{clearSelectedValues:t=!0,clearFilterText:n=!0}=e;t&&this.updateSelection([]),n&&(this.filterSearchValue=``,this.setFilter(),this.filterSearchInput&&(this.filterSearchInput.value=``)),this.$emit(`clear`,{clearSelectedValues:t,clearFilterText:n})}};q([D],Dw.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],Dw.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],Dw.prototype,`all`,void 0),q([D({mode:`boolean`})],Dw.prototype,`allSelected`,void 0),q([D({mode:`boolean`})],Dw.prototype,`search`,void 0),q([D({mode:`boolean`})],Dw.prototype,`disabled`,void 0),q([D({mode:`boolean`})],Dw.prototype,`creatable`,void 0),q([D({mode:`boolean`})],Dw.prototype,`async`,void 0),q([D],Dw.prototype,`debounce`,void 0),q([D({mode:`boolean`})],Dw.prototype,`resizable`,void 0),q([D],Dw.prototype,`tabindex`,void 0),q([D({mode:`boolean`,attribute:`filter-by-contains`})],Dw.prototype,`filterByContains`,void 0),q([C],Dw.prototype,`defaultSlottedNodes`,void 0),q([C],Dw.prototype,`slottedDatasource`,void 0),q([C],Dw.prototype,`valueFormatter`,void 0),q([C],Dw.prototype,`loading`,void 0),q([C],Dw.prototype,`filterSearchValue`,void 0),q([C],Dw.prototype,`open`,void 0),q([C],Dw.prototype,`options`,void 0),q([C],Dw.prototype,`selectedOptions`,void 0),q([C],Dw.prototype,`filteredAvailableOptions`,void 0),q([C],Dw.prototype,`scrollContainer`,void 0),q([D],Dw.prototype,`position`,void 0),q([C],Dw.prototype,`onAllSelectedCallback`,void 0),q([C],Dw.prototype,`itemRenderer`,void 0),q([w],Dw.prototype,`getDisplayValue`,null),q([w],Dw.prototype,`getPlaceholder`,null),q([w],Dw.prototype,`isAllOptionsDisabled`,null),q([w],Dw.prototype,`areAllOptionsSelected`,null),q([w],Dw.prototype,`showCreatable`,null),q([C],Dw.prototype,`optionsHeaderSlottedNodes`,void 0),Dw.compose(Object.assign({baseName:`multiselect`,template:Tse,styles:xw,shadowOptions:void 0},Ew));let Ow=O` .root{position: relative;width: 100%;min-width: 250px}.control-button{display: flex;justify-content: center;min-width: 31px;width: 31px;height: 31px;margin-left: calc(var(--design-unit) * 2px);color: var(--neutral-foreground-hint)}.control{cursor: pointer;position: relative;display: flex;justify-content: end;align-items: center;width: 100%;border-radius: calc(var(--control-corner-radius) * 1px)}.label{display: block;cursor: pointer;font-size: var(--type-ramp-base-font-size);line-height: var(--type-ramp-base-line-height);font-style: normal;font-weight: 700;margin: calc(var(--design-unit) * 2px) 0}.label-hidden{display: none}.control:hover .control-button, .control:hover .label{color: var(--neutral-foreground-rest)}button{pointer-events: none}.options{display: flex;flex-direction: column;position: absolute;height: max-content;overflow-y: hidden;margin-top: 5px;padding: calc((var(--design-unit) + 3) * 2px) calc((var(--design-unit) + 3) * 1px);border: 1px solid rgba(46 51 57 / 100%);border-radius: 4px;background: var(--neutral-fill-input-rest);width: 100%;max-height: 0;visibility: hidden;transition: max-height 0.4s ease 0s, visibility 0.4s ease 0s;z-index: 999}.option-content{display: flex;align-items: center;gap: calc(var(--design-unit) * 4px);width: 100%}.icon-container{display: flex;align-items: center;justify-content: center;width: calc( ((var(--base-height-multiplier) * var(--design-unit)) + (var(--design-unit) * 2)) * 1px + 4px );height: calc( ((var(--base-height-multiplier) * var(--design-unit)) + (var(--design-unit) * 2)) * 1px );border-radius: calc((var(--control-corner-radius) - 1) * 2px);background: var(--neutral-layer-2);box-sizing: border-box;box-shadow: 0 0 5px 0 rgba(0 0 0 / 35%);flex-shrink: 0}.text-content{display: flex;flex-direction: column;flex: 1}.svg-icon{height: 2em}.position-above{bottom: 100%}.checkbox-container{display: flex;flex-direction: column;overflow-y: scroll;scrollbar-width: thin;scrollbar-color: rgb(46 48 53) rgb(31 33 38)}span{border-bottom: calc(var(--stroke-width) * 1px) solid;border-color: color-mix(in srgb, var(--neutral-fill-rest), transparent 50%);padding: calc((var(--design-unit) + 2) * 2px) calc((var(--design-unit) + 3) * 1px);font-size: calc((var(--type-ramp-base-font-size) - 1px));color: var(--neutral-foreground-hint)}.multiselect-checkbox{min-width: fit-content;flex-direction: row-reverse;justify-content: space-between;align-items: flex-start;border-bottom: 1px solid;border-color: color-mix(in srgb, var(--neutral-fill-rest), transparent 50%);padding: calc((var(--design-unit) + 3) * 1px) calc((var(--design-unit) + 3) * 1px) calc((var(--design-unit) + 3) * 1px) 0;margin: 0}.multiselect-checkbox:hover{background-color: rgb(45 47 51);cursor: pointer}.multiselect-checkbox::part(label){overflow-x: hidden;text-overflow: ellipsis}.multiselect-checkbox::part(control){min-width: calc( ((var(--base-height-multiplier) + var(--density)) * var(--design-unit) / 2 + var(--design-unit)) * 1px )}.checkbox-container .multiselect-checkbox[disabled]{cursor: not-allowed}.description{text-wrap: wrap;font-size: calc((var(--type-ramp-base-font-size) - 1px));margin: calc((var(--design-unit) + 3) * 1px) 0}#filter-search{padding: 5px}::-webkit-scrollbar{width: 12px}::-webkit-scrollbar-track{background: rgb(31 33 38)}::-webkit-scrollbar-thumb{width: 8px;border-radius: 10px;box-shadow: inset 0 0 6px rgba(0 0 0 / 30%);background-color: rgb(46 48 53);border: 3px solid rgb(31 33 38)}.visible{visibility: visible;max-height: ${`450`}px}`,kw=(e=`foundation`)=>T`<div class="root" part="root"><div class="control" part="control" @click=${e=>!e.disabled&&e.toggle()}><label part="label" for="control" class=${e=>fn(`label`,[`label-hidden`,!e.defaultSlottedNodes?.length])}><slot ${bt({property:`defaultSlottedNodes`,filter:ga})}></slot></label><${e}-button class="control-button" part="control-button"><slot name="button-content"><${e}-icon name="plus" variant="solid" size="lg"></${e}-icon></slot></${e}-button></div><div ${k(`optionsElement`)}class="options" part="options">${A(e=>e.search,T`<${e}-text-field id="filter-search" part="filter-search" value=${df(e=>e.filterSearchValue,`string`,`input`)}placeholder="${e=>e.getPlaceholder}" @input=${(e,t)=>e.setFilter()}@change=${(e,t)=>e.changeHandler(t.event)}></${e}-text-field>`)}<div class="checkbox-container" part="checkbox-container">${j(e=>e.filteredAvailableOptions,T`<span>${e=>e.type}</span>${j(e=>e.options,T`<${e}-checkbox class="multiselect-checkbox" part="multiselect-checkbox" @click=${(e,t)=>t.parentContext.parent.selectCheckboxOne(e)}@change=${(e,t)=>t.parentContext.parent.changeHandler(t.event)}?current-checked="${(e,t)=>t.parentContext.parent.isOptionSelected(e)}" ?disabled="${(e,t)=>t.parentContext.parent.isOptionDisabled(e)}"><div class="option-content">${A(e=>e.icon||e.svg,T`<div class="icon-container">${A(e=>e.icon,T`<${e}-icon style="color:${e=>e.iconColor||`#fff`}" name="${e=>e.icon}" size="xl"></${e}-icon>`)} ${A(e=>e.svg,T`<img class="svg-icon" src="${e=>e.svg}" alt="${e=>e.label}" />`)}</div>`)}<div class="text-content"><div class="option-label">${(e,t)=>t.parentContext.parent.getItemLabel(e)}</div>${A(e=>e.description,T`<p class="description">${e=>e.description}</p>`)}</div></div></${e}-checkbox>`)} `)}</div></div></div>`,Ese=T` ${kw()} `,Aw={};var jw=class extends P{constructor(){super(...arguments),this.name=``,this.autoPosition=!0,this.search=!0,this.disabled=!1,this.clickOutside=e=>this.handleClickOutside(e),this.open=!1,this.options=[],this.selectedOptions=[],this.position=yw.BELOW}openChanged(e,t){var n,r;t?(document.addEventListener(`mousedown`,this.clickOutside),(n=this.optionsElement)==null||n.classList.add(`visible`)):(document.removeEventListener(`mousedown`,this.clickOutside),(r=this.optionsElement)==null||r.classList.remove(`visible`))}connectedCallback(){var e;super.connectedCallback(),this.position===yw.ABOVE&&((e=this.optionsElement)==null||e.classList.add(`position-above`))}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`mousedown`,this.clickOutside)}toggle(){this.open||this.setDropdownPosition(),this.open=!this.open}sortFilteredOptions(e){let t=(e??this.options).reduce((e,t)=>{let n=t.type||`Other`;return e[n]?e[n].options.push(t):e[n]={type:n,options:[t]},e},{});return Object.values(t)}optionsChanged(){this.filteredAvailableOptions=this.sortFilteredOptions()}setDropdownPosition(){let e=this.position;if(this.autoPosition){let t=this.assignedSlot?this.assignedSlot.parentElement:this.parentElement;for(;t&&!t.classList.contains(`content-wrapper`);)t=t.parentElement;if(t){let n=t.getBoundingClientRect(),r=this.getBoundingClientRect(),i=n.top+n.height/2;e=r.top<i?yw.BELOW:yw.ABOVE}else{let t=this.getBoundingClientRect(),n=window.innerHeight,r=t.top,i=n-t.bottom;e=i<t.height&&r>i?yw.ABOVE:yw.BELOW}}e===yw.ABOVE?(this.optionsElement.classList.add(`position-above`),this.optionsElement.classList.remove(`position-below`)):e===yw.BELOW&&(this.optionsElement.classList.add(`position-below`),this.optionsElement.classList.remove(`position-above`))}optionGetter(e){return e.value}getItemLabel(e){let t;if(e)t=e.label||e.value||``;else return``;return this.valueFormatter?this.valueFormatter(t):t}isOptionDisabled(e){return!e||typeof e==`string`?!1:e.disabled||!1}get getPlaceholder(){return`Search ${this.name}`.trim().concat(`...`)}isOptionSelected(e){return this.selectedOptions.includes(this.optionGetter(e))}selectCheckboxOne(e){let t=this.optionGetter(e);this.selectedOptions.includes(t)?(this.selectedOptions=[...this.selectedOptions],this.selectedOptions.splice(this.selectedOptions.indexOf(t),1)):this.selectedOptions=[...this.selectedOptions,t],this.$emit(`selectionChange`,this.selectedOptions)}setFilter(){let e=this.options.filter(e=>{let t=e.description,n=e.label??e.value;if(t?.toLowerCase().includes(this.filterSearchValue.toLowerCase())||n.toLowerCase().includes(this.filterSearchValue.toLowerCase()))return e});this.filteredAvailableOptions=this.sortFilteredOptions(e)}changeHandler(e){e.preventDefault(),e.stopImmediatePropagation()}handleClickOutside(e){Cb(e,this)&&(this.open=!1)}};q([D],jw.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],jw.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],jw.prototype,`search`,void 0),q([D({mode:`boolean`})],jw.prototype,`disabled`,void 0),q([C],jw.prototype,`defaultSlottedNodes`,void 0),q([C],jw.prototype,`valueFormatter`,void 0),q([C],jw.prototype,`filterSearchValue`,void 0),q([C],jw.prototype,`open`,void 0),q([C],jw.prototype,`options`,void 0),q([C],jw.prototype,`selectedOptions`,void 0),q([C],jw.prototype,`filteredAvailableOptions`,void 0),q([C],jw.prototype,`position`,void 0),q([w],jw.prototype,`getPlaceholder`,null),jw.compose(Object.assign({baseName:`categorized-multiselect`,template:Ese,styles:Ow,shadowOptions:void 0},Aw));let Mw=(e,t)=>Pr(e,t),Nw=(e,t)=>O` ${Jl(e,t)}`;var Pw=class extends Fr{};let Fw={checkedIndicator:`
257
+ Install model </${e}-button>`)}</div>`)}</div>`)} `,DC=T` ${e=>Sse(Tb(e))} `;var OC=class extends P{constructor(){super(...arguments),this.status=null,this.open=!1,this.state=`none`,this.isInstalling=!1,this.pollTimer=null,this.clickOutside=e=>this.handleClickOutside(e)}get aiProvider(){return this.providerRegistry?.default()}get chromeStatusLabel(){if(this.status?.provider!==`chrome`)return null;let e=this.status?.chromeAvailability;return e===`available`?`Installed`:e===`downloading`||this.isInstalling?`Downloading…`:e===`downloadable`?`Downloadable`:e===`unavailable`?`Unavailable`:null}get canInstall(){return!!this.aiProvider?.triggerDownload&&this.status?.provider===`chrome`&&this.status?.chromeAvailability===`downloadable`&&!this.isInstalling}get isDownloading(){return this.status?.chromeAvailability===`downloading`||this.isInstalling}connectedCallback(){let e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});return J(this,void 0,void 0,function*(){e.connectedCallback.call(this),yield this.refreshStatus(),this.maybeStartPolling()})}disconnectedCallback(){this.stopPolling(),document.removeEventListener(`mousedown`,this.clickOutside)}openChanged(){this.open?(document.addEventListener(`mousedown`,this.clickOutside),this.refreshStatus()):document.removeEventListener(`mousedown`,this.clickOutside)}handleClickOutside(e){Cb(e,this)&&(this.open=!1)}toggleDropdown(){this.open=!this.open}refreshStatus(){return J(this,void 0,void 0,function*(){if(!this.aiProvider?.getStatus){this.status=null,this.state=`none`;return}try{let e=yield this.aiProvider.getStatus();this.status=e,this.state=this.deriveState(e),this.state===`available`&&(this.isInstalling=!1)}catch{this.status=null,this.state=`none`,this.isInstalling=!1}})}deriveState(e){if(!e||e.provider===`none`)return`none`;if(e.provider===`chrome`){let t=e.chromeAvailability;return t===`available`?`available`:t===`downloading`?`downloading`:t===`downloadable`?`downloadable`:`unavailable`}return`server`}maybeStartPolling(){this.status?.chromeAvailability===`downloading`||this.isInstalling?this.startPolling():this.stopPolling()}startPolling(){this.pollTimer||(this.pollTimer=setInterval(()=>{this.refreshStatus().then(()=>{this.maybeStartPolling()})},2500))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}onInstall(){return J(this,void 0,void 0,function*(){if(this.canInstall&&this.aiProvider?.triggerDownload){this.isInstalling=!0;try{yield this.aiProvider.triggerDownload(),this.startPolling()}catch{this.isInstalling=!1}finally{yield this.refreshStatus()}}})}};q([ZS],OC.prototype,`providerRegistry`,void 0),q([C],OC.prototype,`status`,void 0),q([C],OC.prototype,`open`,void 0),q([C],OC.prototype,`state`,void 0),q([C],OC.prototype,`isInstalling`,void 0),q([w],OC.prototype,`chromeStatusLabel`,null),q([w],OC.prototype,`canInstall`,null),q([w],OC.prototype,`isDownloading`,null),OC.compose({baseName:`ai-indicator`,template:DC,styles:EC});let kC=(e,t)=>Hn(e,t),AC=(e,t)=>O` ${Fl(e,t)}`;var jC=class extends Il{};let MC={delegatesFocus:!0,mode:`open`},NC={};jC.compose(Object.assign({baseName:`anchor`,template:kC,styles:AC,shadowOptions:MC},NC));let PC=(e,t)=>Kn(e,t),FC=(e,t)=>O` ${Ll(e,t)}`;var IC=class extends Jn{};let LC={delegatesFocus:!0,mode:`open`},RC={};IC.compose(Object.assign({baseName:`anchored-region`,template:PC,styles:FC,shadowOptions:LC},RC));let zC=(e,t)=>tr(e,t),Cse=T` ${A(e=>e.imgSrc,T`<img src="${e=>e.imgSrc}" alt="${e=>e.alt}" slot="media" class="media" part="media" />`)} `,BC=(e,t)=>O` ${Rl(e,t)}`;var VC=class extends zl{};let HC={delegatesFocus:!0,mode:`open`},UC={media:Cse};VC.compose(Object.assign({baseName:`avatar`,template:zC,styles:BC,shadowOptions:HC},UC));let WC=(e,t)=>rr(e,t),GC=(e,t)=>O` ${Bl(e,t)}`;var KC=class extends ir{};let qC={};KC.compose(Object.assign({baseName:`badge`,template:WC,styles:GC,shadowOptions:void 0},qC));let JC=O` @keyframes delete-animate{from{height: 100px;opacity: 100%}to{height: 0;opacity: 0%}}@keyframes append-animate{from{height: 0;opacity: 0%}to{height: var(--banner-height);opacity: 100%}}:host{--banner-width: 100%;--banner-height: 65px;--flow: row}@media screen and (max-width: 640px){:host{--flow: column;--banner-height: 100px}}.banner{animation: append-animate 0.3s linear;width: var(--banner-width);height: var(--banner-height);background-color: var(--fill-color);display: flex;flex-direction: var(--flow);padding: 5px 8px;box-sizing: border-box;overflow: hidden}.banner-delete{animation: delete-animate 0.3s linear;opacity: 0%}.content{display: flex;align-items: center;flex: 2;font-size: 12px;overflow: hidden;white-space: pre-line}.action{display: flex;flex-direction: row-reverse;align-items: center;gap: 10px;flex: 1;overflow: hidden}`,wse=e=>T`<div role="alert" aria-live="polite" class="banner ${e=>e.dismissAnimation}" ${k(`banner`)}><div part="content" class="content"><slot name="content">${A(e=>e.notification,T`<div><div>${e=>e.notification?.body||`Place holder for notification message`}</div></div>`)}</slot></div><div part="action" class="action"><slot name="action" class="action">${A(e=>e.notification,T`<${e}-button slot="action" appearance="lightweight" @click=${e=>e.dismiss()}>${e=>e.notification?.config?.banner?.dismissingAction?.label||`Ignore`}</${e}-button>`)} ${j(e=>(e.notification?.config)?.banner.confirmingActions,T`<${e}-button slot="action" appearance="lightweight" @click=${(e,t)=>{var n;e?.action(),(n=t.parent)==null||n.dismissNotification()}}>${e=>e.label}</${e}-button>`)}</slot></div></div>`,YC=T` ${e=>wse(Tb(e))} `,XC={mode:`open`,delegatesFocus:!0};var ZC=class extends P{constructor(){super(...arguments),this.dismissAnimation=``}connectedCallback(){super.connectedCallback()}dismiss(){return this.dismissAnimation=`banner-delete`,new Promise(e=>{this.banner.onanimationend=()=>{this.remove(),e()}})}dismissNotification(){return J(this,void 0,void 0,function*(){try{yield this.dismiss(),this.remove()}catch(e){xb.error(e)}})}};q([C],ZC.prototype,`dismissAnimation`,void 0),q([C],ZC.prototype,`notification`,void 0),ZC.compose({baseName:`banner`,styles:JC,template:YC,shadowOptions:XC});let QC=(e,t)=>sr(e,t),$C=(e,t)=>O` ${Hl(e,t)}`;var ew=class extends cr{};ew.compose(Object.assign({baseName:`breadcrumb`,template:QC,styles:$C,shadowOptions:void 0},{}));let tw=(e,t)=>ar(e,t),nw=(e,t)=>O` ${Vl(e,t)}`;var rw=class extends or{};let iw={separator:`/`};rw.compose(Object.assign({baseName:`breadcrumb-item`,template:tw,styles:nw,shadowOptions:void 0},iw));let aw=(e,t)=>lr(e,t),ow=(e,t)=>O` ${Ul(e,t)}`;var sw=class extends Wl{};let cw={delegatesFocus:!0,mode:`open`},lw={};sw.compose(Object.assign({baseName:`button`,template:aw,styles:ow,shadowOptions:cw},lw));let uw=()=>O` ${Gl}`,dw=(e,t)=>jr(e,t);var fw=class extends xr{};let pw={delegatesFocus:!0,mode:`open`},mw={};fw.compose(Object.assign({baseName:`calendar`,template:dw,styles:uw,shadowOptions:pw},mw));let hw=(e,t)=>Mr(e,t),gw=(e,t)=>O` ${Kl(e,t)} :host{background-color: var(--fui-card-fill-color);color: var(--fui-card-foreground-color)}`;var _w=class extends ql{};let vw={};_w.compose(Object.assign({baseName:`card`,template:hw,styles:gw,shadowOptions:void 0},vw));var yw;(function(e){e.BELOW=`below`,e.ABOVE=`above`})(yw||(yw={}));var bw=/* @__PURE__ */ u((/* @__PURE__ */ s(((e,t)=>{var n=NaN,r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,o=/^0o[0-7]+$/i,s=parseInt,c=typeof global==`object`&&global&&global.Object===Object&&global,l=typeof self==`object`&&self&&self.Object===Object&&self,u=c||l||Function(`return this`)(),d=Object.prototype.toString,f=Math.max,p=Math.min,m=function(){return u.Date.now()};function h(e,t,n){var r,i,a,o,s,c,l=0,u=!1,d=!1,h=!0;if(typeof e!=`function`)throw TypeError(`Expected a function`);t=y(t)||0,g(n)&&(u=!!n.leading,d=`maxWait`in n,a=d?f(y(n.maxWait)||0,t):a,h=`trailing`in n?!!n.trailing:h);function _(t){var n=r,a=i;return r=i=void 0,l=t,o=e.apply(a,n),o}function v(e){return l=e,s=setTimeout(x,t),u?_(e):o}function b(e){var n=e-c,r=e-l,i=t-n;return d?p(i,a-r):i}function ee(e){var n=e-c,r=e-l;return c===void 0||n>=t||n<0||d&&r>=a}function x(){var e=m();if(ee(e))return te(e);s=setTimeout(x,b(e))}function te(e){return s=void 0,h&&r?_(e):(r=i=void 0,o)}function ne(){s!==void 0&&clearTimeout(s),l=0,r=c=i=s=void 0}function S(){return s===void 0?o:te(m())}function C(){var e=m(),n=ee(e);if(r=arguments,i=this,c=e,n){if(s===void 0)return v(c);if(d)return s=setTimeout(x,t),_(c)}return s===void 0&&(s=setTimeout(x,t)),o}return C.cancel=ne,C.flush=S,C}function g(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function _(e){return!!e&&typeof e==`object`}function v(e){return typeof e==`symbol`||_(e)&&d.call(e)==`[object Symbol]`}function y(e){if(typeof e==`number`)return e;if(v(e))return n;if(g(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=g(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(r,``);var c=a.test(e);return c||o.test(e)?s(e.slice(2),c?2:8):i.test(e)?n:+e}t.exports=h})))());let xw=O` :host{--scrollbar-width: 12px;--scrollbar-thumb-width: 8px}.root{position: relative;width: inherit;min-width: 250px}.control{cursor: pointer;position: relative;display: flex;align-items: center;width: 100%;border-radius: calc(var(--control-corner-radius) * 1px)}#display-field{width: 100%;cursor: pointer;color: var(--neutral-foreground-rest);min-height: 40px;padding: 0 calc(var(--design-unit) * 2.25px);border-width: 0;background-color: var(--neutral-fill-input-rest);border-radius: calc(var(--control-corner-radius) * 1px)}#display-field[disabled]{cursor: not-allowed;opacity: 30%}#display-field:focus{outline: 1px solid var(--accent-fill-rest);background: var(--neutral-fill-input-rest);border-style: none;box-shadow: none}#display-field:hover:not(:focus):not([disabled]){outline: 1px solid var(--neutral-stroke-hover)}button{pointer-events: none}.indicator{position: absolute;left: calc(100% - 26px);padding: 0;cursor: pointer}#arrow-icon{width: 16px;fill: white;transform: rotate(0deg);transition: transform 0.2s linear 0s}#arrow-icon.flipped{transform: rotate(180deg)}.disabled-svg{pointer-events: none;opacity: 30%}.position-above{bottom: 100%}::-webkit-scrollbar{width: var(--scrollbar-width)}::-webkit-scrollbar-track{background: var(--neutral-layer-4)}::-webkit-scrollbar-thumb{width: var(--scrollbar-thumb-width);border-radius: 10px;box-shadow: inset 0 0 6px rgba(0 0 0 / 30%);background-color: var(--neutral-layer-2);border: 3px solid var(--neutral-layer-4)}::-webkit-scrollbar-corner{background: var(--neutral-layer-4)}.multiselect-dropdown{display: flex;flex-direction: column;position: absolute;height: max-content;overflow: hidden;margin-top: calc(var(--design-unit) * 1px);border: calc(var(--stroke-width) * 1px) solid var(--neutral-layer-2);border-radius: 4px;background: var(--neutral-fill-input-rest);width: 100%;max-height: 0;visibility: hidden;z-index: 999}.multiselect-dropdown:not(.is-resizing){transition: max-height 0.4s ease 0s, visibility 0.4s ease 0s}.checkbox-container{display: flex;flex-direction: column;list-style: none;overflow-y: auto;height: 100%}.is-resizing .checkbox-container{overflow-y: hidden}.checkbox-container foundation-checkbox[disabled]{cursor: not-allowed}.visible{visibility: visible;max-height: var(--custom-max-height, ${`230`}px);overflow: hidden}::slotted(foundation-checkbox), foundation-checkbox{border-bottom: 1px solid var(--neutral-layer-4);padding: 5px 0 5px 5px;margin: 0}::slotted(foundation-checkbox:hover), foundation-checkbox:hover{background-color: var(--neutral-layer-3);cursor: pointer}::slotted(foundation-checkbox)::part(label), foundation-checkbox::part(label){overflow-x: hidden;text-overflow: ellipsis;white-space: nowrap}.label{display: block;cursor: pointer;font-size: var(--type-ramp-base-font-size);line-height: var(--type-ramp-base-line-height);font-style: normal;margin: calc(var(--design-unit) * 2px) 0}.label-hidden{display: none}ol, li{margin: 0;padding: 0}.checkbox{width: 100%}.select-all{width: 100%;margin-left: 0;margin-right: 0}.display-value{position: absolute;right: 40px;color: var(--neutral-foreground-rest);font-size: var(--type-ramp-base-font-size);line-height: var(--type-ramp-base-line-height);font-family: var(--body-font)}.options-header-item-hidden{display: none}.resize-button{position: absolute;bottom: 0;right: 0;width: 12px;height: 12px;cursor: nw-resize;background: linear-gradient( -45deg, transparent 30%, var(--neutral-foreground-rest) 30%, var(--neutral-foreground-rest) 40%, transparent 40%, transparent 60%, var(--neutral-foreground-rest) 60%, var(--neutral-foreground-rest) 70%, transparent 70% );z-index: 1000;opacity: 60%;transition: opacity 0.2s ease}.resize-button:hover{opacity: 100%}.multiselect-dropdown.resizable{resize: none;overflow: hidden}`;var Sw;let Cw=Sw=class extends Sb{constructor(){super(...arguments),this.emptyDataLabel=`No matching records`,this.allowCustomOptions=!1,this.infiniteScroll=!1,this.pageSize=Sw.defaultPageSize,this.initalSelectedValueInitialized=!1,this.isSnapshot=!0,this.baseCriteria=``,this.listboxElement=null,this.loadingMoreRows=!1,this.renderedOptionsCount=0,this.lastTopUpScrollHeight=-1,this.emptyDataOption=null,this.selectOpenChangeHandler=e=>{e.detail?.open&&(this.listboxElement||this.attachListboxScrollListener(),this.topUpVisibleListbox())},this.listboxScrollHandler=()=>{let e=this.listboxElement;e&&this.isNearListboxBottom(e)&&this.loadNextPage()},this.resizeObserverCallback=e=>{e.forEach(e=>{this.checkOverflow(e.target)})},this.selectChangeHandler=e=>{let t=e.target.value,n=this.options?.find(e=>String(e.label)===t);!n&&this.allowCustomOptions&&this.select instanceof Ql?this.select.$emit(`value-change`,{label:t,value:t}):this.select.$emit(`value-change`,n)}}initialSelectedValueChanged(e,t){if(t!==e){if(!t){this.select&&(this.initalSelectedValueInitialized=!1,this.clearData(),this.resetCombobox(),this.fetchData());return}this.select&&this.getDisplayForValue(t)===String(this.select.value||``)||(this.initalSelectedValueInitialized=!1,this.clearData(),this.fetchData())}}connectedCallback(){let e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});return J(this,void 0,void 0,function*(){if(e.connectedCallback.call(this),this.baseCriteria=this.criteria,this.fields=this.labelField?this.valueField?.concat(` `,this.labelField):this.valueField,this.select=this.parentElement,this.optionElement=this.optionElement??`${Tb(this.select)}-option`,this.select.addEventListener(`change`,this.selectChangeHandler),this.resizeObserver=new ResizeObserver(this.resizeObserverCallback),this.infiniteScroll){if(this.isSnapshot=!0,this.maxRows=this.pageSize>0?this.pageSize:Sw.defaultPageSize,this.select.addEventListener(`open-change`,this.selectOpenChangeHandler),yield this.applyInfiniteScrollFetchMode(),!this.isConnected)return;x.queueUpdate(()=>this.attachListboxScrollListener())}this.fetchData(),this.valueField||xb.warn(`Specify field for values in options (e.g value-field="VALUE") and optionally field for label (e.g label-field="NAME")`)})}disconnectedCallback(){var e;super.disconnectedCallback(),this.resizeObserver.disconnect(),(e=this.listboxElement)==null||e.removeEventListener(`scroll`,this.listboxScrollHandler),this.listboxElement=null,this.select.removeEventListener(`open-change`,this.selectOpenChangeHandler),this.select.removeEventListener(`change`,this.selectChangeHandler)}applyInfiniteScrollFetchMode(){return J(this,void 0,void 0,function*(){if(this.resourceName&&this.connect.isConnected)try{let e=yield this.resources.getResourceTypeFor(this.resourceName);this.isSnapshot=e!==ag.DATASERVER}catch(e){xb.warn(`Unable to determine the resource type for ${this.resourceName}`,e)}})}attachListboxScrollListener(){var e;if(this.isConnected){if((e=this.listboxElement)==null||e.removeEventListener(`scroll`,this.listboxScrollHandler),this.listboxElement=this.select?.scrollableListbox??this.select?.listbox??(this.select?.shadowRoot)?.querySelector(`.listbox`),!this.listboxElement){xb.warn(`Unable to locate listbox element, infinite scroll will not be available.`);return}this.listboxElement.addEventListener(`scroll`,this.listboxScrollHandler)}}isNearListboxBottom(e){return e.scrollTop+e.clientHeight>=e.scrollHeight-Sw.scrollLoadThresholdPx}loadNextPage(){return J(this,void 0,void 0,function*(){if(this.loadingMoreRows||!this.canRequestMoreRows())return;this.loadingMoreRows=!0;let e=this.datasource.resourceType===ag.REQUEST_SERVER;try{yield this.requestMoreRows()}catch{this.loadingMoreRows=!1;return}e&&(this.loadingMoreRows=!1)})}topUpVisibleListbox(){this.infiniteScroll&&requestAnimationFrame(()=>{if(!this.isConnected)return;let e=this.listboxElement;e&&e.clientHeight!==0&&this.isNearListboxBottom(e)&&e.scrollHeight!==this.lastTopUpScrollHeight&&(this.lastTopUpScrollHeight=e.scrollHeight,this.loadNextPage())})}fetchData(){this.select&&this.valueField&&(this.resourceName&&this.connect.isConnected||this.data)&&(this.select instanceof Ql&&this.select.async&&this.initialSelectedValue?this.asyncModeIntialization():this.fetchGenesisData())}asyncModeIntialization(){return J(this,void 0,void 0,function*(){let e=yield this.datasource.init(this.datasourceOptions(),!0);if(this.isConnected){if(!e){this.handleError({message:`Genesis Datasource async mode initialization failed for ${this.resourceName}`,loggerType:`error`});return}Gb(this,this.initialSelectedValue)}})}clearData(){this.rowsSyncedWithStream.clear(),this.options=[],this.renderedOptionsCount=0,this.lastTopUpScrollHeight=-1,this.emptyDataOption=null,this.loadingMoreRows=!1,this.select&&(Array.from(this.select.children).forEach(e=>{e instanceof Sw||this.select.removeChild(e)}),this.select.value=``,this.select.initialValue=``)}checkOverflow(e){let t=e.shadowRoot.querySelector(`.content`);t&&(t.scrollWidth>t.clientWidth?e.setAttribute(`title`,e.textContent):e.removeAttribute(`title`))}rowToOption(e){return{value:e[this.valueField],label:this.labelRowFormatter?this.labelRowFormatter(e):this.labelFormatter?this.labelFormatter(e[this.labelField]):this.getDefaultLabelFormat(e[this.labelField],this.getFieldMetadata(this.labelField)?.type)}}renderListboxOptions(e){e.forEach(({value:e,label:t})=>{let n=document.createElement(this.optionElement);n.textContent=t||e,n.value=e,this.select.appendChild(n),this.resizeObserver.observe(n)})}removeEmptyDataOption(){this.emptyDataOption&&(this.emptyDataOption.remove(),this.emptyDataOption=null)}syncComponentData(e){this.loadingMoreRows=!1;let t=e??Array.from(this.rowsSyncedWithStream.values());if(t.length>0){this.removeEmptyDataOption(),this.options=t.map(e=>this.rowToOption(e));let e=this.renderedOptionsCount===0;if(this.renderListboxOptions(this.options.slice(this.renderedOptionsCount)),this.renderedOptionsCount=this.options.length,this.nextRequestOffset=Math.max(this.nextRequestOffset,this.renderedOptionsCount),this.topUpVisibleListbox(),!this.initalSelectedValueInitialized||this.select instanceof Ql&&!this.select.async&&e){this.resetCombobox();let e=this.getInitialLabel();x.queueUpdate(()=>{this.select.value=String(e),e&&this.select instanceof Ql&&this.select.async&&this.selectChangeHandler({target:{value:e}})}),this.initalSelectedValueInitialized=!0}}else if(this.allowCustomOptions&&this.initialSelectedValue&&(!this.initalSelectedValueInitialized||this.select instanceof Ql&&!this.select.async)&&(this.resetCombobox(),x.queueUpdate(()=>{this.select.value=String(this.initialSelectedValue)}),this.initalSelectedValueInitialized=!0),this.select&&!this.emptyDataOption){let e=document.createElement(this.optionElement);e.textContent=this.emptyDataLabel,e.value=``,e.disabled=!0,this.select.appendChild(e),this.emptyDataOption=e}}getInitialLabel(){return this.getDisplayForValue(this.initialSelectedValue)}getDisplayForValue(e){if(e==null||e!==0&&!e)return``;let t=this.options?.find(t=>t.value===e);return this.allowCustomOptions&&this.select instanceof Ql?String(t?t.label:e):t?String(t.label):``}resetCombobox(){this.select&&this.select instanceof Ql&&this.select.resetCombobox()}handleStreamInserts(e){if(this.loadingMoreRows=!1,!e?.length)return;this.removeEmptyDataOption();let t=new Set((this.options??[]).map(e=>String(e.value))),n=e.filter(e=>!t.has(String(e[this.valueField])));if(!n.length){xb.warn(`Infinite scroll for ${this.resourceName} received a page of options that were all already loaded, so paging has stopped. Request Server resources only honour OFFSET when declared with criteriaOnlyRequest; otherwise every page returns the same rows. Also set a stable order-by so pages cannot overlap.`),this.moreRowsAvailable=!1;return}let r=n.map(e=>this.rowToOption(e));this.options=[...this.options??[],...r],this.renderListboxOptions(r),this.renderedOptionsCount=this.options.length,this.nextRequestOffset=Math.max(this.nextRequestOffset,this.renderedOptionsCount),this.topUpVisibleListbox()}handleStreamDeletes(e){xb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){xb.debug(`handleStreamUpdates - Method not implemented.`)}};Cw.defaultPageSize=20,Cw.scrollLoadThresholdPx=32,q([Xy],Cw.prototype,`resources`,void 0),q([D({attribute:`label-field`})],Cw.prototype,`labelField`,void 0),q([D({attribute:`option-element`})],Cw.prototype,`optionElement`,void 0),q([D({attribute:`value-field`})],Cw.prototype,`valueField`,void 0),q([D({attribute:`empty-data-label`})],Cw.prototype,`emptyDataLabel`,void 0),q([D({mode:`boolean`,attribute:`allow-custom-options`})],Cw.prototype,`allowCustomOptions`,void 0),q([D({mode:`boolean`,attribute:`infinite-scroll`})],Cw.prototype,`infiniteScroll`,void 0),q([D({attribute:`page-size`,converter:E})],Cw.prototype,`pageSize`,void 0),q([C],Cw.prototype,`labelFormatter`,void 0),q([C],Cw.prototype,`labelRowFormatter`,void 0),q([C],Cw.prototype,`initialSelectedValue`,void 0),Cw=Sw=q([$e({name:`options-datasource`})],Cw);let ww=class extends Sb{constructor(){super(...arguments),this.isSnapshot=!0,this.baseCriteria=``}connectedCallback(){let e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});return J(this,void 0,void 0,function*(){e.connectedCallback.call(this),this.baseCriteria=this.criteria,this.fields=this.labelField?this.valueField?.concat(` `,this.labelField):this.valueField,this.select=this.parentElement,this.select&&this.valueField&&(this.resourceName&&this.connect.isConnected||this.data)&&this.fetchGenesisData(),this.valueField||xb.warn(`Specify field for values in options (e.g value-field="VALUE") and optionally field for label which is supported only in select and combobox (e.g label-field="NAME")`)})}clearData(){this.select.options=[]}syncComponentData(e){let t=(e??Array.from(this.rowsSyncedWithStream.values())).map(e=>({value:e[this.valueField],label:this.getDefaultLabelFormat(e[this.labelField],this.getFieldMetadata(this.labelField)?.type)}));this.select?.async&&(this.select.loading=!1),this.select.options=t}handleStreamInserts(e){xb.debug(`handleStreamInserts - Method not implemented.`)}handleStreamDeletes(e){xb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){xb.debug(`handleStreamUpdates - Method not implemented.`)}};q([D({attribute:`value-field`})],ww.prototype,`valueField`,void 0),q([D({attribute:`label-field`})],ww.prototype,`labelField`,void 0),ww=q([$e({name:`multiselect-datasource`})],ww);let Tw=(e=`foundation`)=>T`<label part="label" for="display-field" class=${e=>fn(`label`,[`label-hidden`,!e.defaultSlottedNodes?.length])}><slot name="label" ${bt({property:`defaultSlottedNodes`,filter:ga})}></slot></label><div class="root" part="root" @keydown="${(e,t)=>e.keydownHandler(t.event)}"><div class="control" part="control"><input id="display-field" part="filter-search" role="combobox" aria-haspopup="listbox" aria-controls="checkbox-container" aria-expanded=${e=>e.open?`true`:`false`}tabindex="${e=>e.tabindex}" ?readonly=${e=>!e.search}@click=${e=>e.toggle()}?disabled="${e=>e.disabled}" ${k(`filterSearchInput`)}value=${df(e=>e.filterSearchValue,`string`,`input`)}placeholder="${e=>e.getDisplayValue}" autocomplete="off" @input=${(e,t)=>e.inputHandler()}@change=${(e,t)=>e.changeHandler(t.event)}/><div part="indicator" class="indicator" @click=${e=>!e.disabled&&e.toggle()}><svg viewBox="0 0 12 7" ${k(`arrowIcon`)}id="arrow-icon" class="${e=>fn([`disabled-svg`,e.disabled])}" xmlns="http://www.w3.org/2000/svg"><path d="${`M11.85.65c.2.2.2.5 0 .7L6.4 6.84a.55.55 0 01-.78 0L.14 1.35a.5.5 0 11.71-.7L6 5.8 11.15.65c.2-.2.5-.2.7 0z`}" /></svg></div>${A(e=>e.filterSearchValue&&e.selectedOptions.length,T`<div class="display-value">${e=>e.getDisplayValue}</div>`)}</div>${A(e=>e.loading,T`<${e}-progress slot="indicator"></${e}-progress>`)}<section class=${e=>fn(`multiselect-dropdown`,[`resizable`,e.resizable])} ${k(`multiselectDropdown`)}part="multiselect-dropdown">${A(e=>e.resizable,T`<div class="resize-button" @mousedown=${(e,t)=>e.handleResizeStart(t.event)}></div>`)} ${A(e=>e.all,T`<${e}-button class="select-all" @click=${e=>e.selectCheckboxAll()}?disabled="${(e,t)=>e.isAllOptionsDisabled}">${e=>e.areAllOptionsSelected?`Deselect All`:`Select All`} ${e=>e.name}</${e}-button>`)}<ol id="checkbox-container" class="checkbox-container options" aria-multiselectable="true" part="options-ol"><li part="options-header-item" class=${e=>fn(`options-header-item`,[`options-header-item-hidden`,!e.optionsHeaderSlottedNodes?.length])}><slot name="options-header" ${bt({property:`optionsHeaderSlottedNodes`,filter:ga})}></slot></li>${j(e=>e.filteredAvailableOptions,T`<li role="option" value=${(e,t)=>t.parent.getItemLabel(e)}part="option"><${e}-checkbox part="checkbox" class="checkbox" exportparts="label:checkbox-label" @keydown=${(e,t)=>t.parent.checkboxKeyDown(e,t.event)}@click=${(e,t)=>t.parent.selectCheckboxOne(e)}@change=${(e,t)=>t.parent.changeHandler(t.event)}?current-checked="${(e,t)=>t.parent.isOptionSelected(e)}" ?disabled="${(e,t)=>t.parent.isOptionDisabled(e)}">${(e,t)=>{var n;return((n=t.parent)?.itemRenderer)?.call(n,e,t.parent)}}</${e}-checkbox></li>`)}</ol>${A(e=>e.showCreatable,T`<${e}-button @click=${e=>e.addOption()}>Create&nbsp;"${e=>e.filterSearchValue}"</${e}-button>`)}</section></div><slot ${bt({property:`slottedDatasource`,filter:e=>e instanceof ww})}></slot>`,Tse=T` ${Tw()} `,Ew={};var Dw=class extends P{constructor(){super(...arguments),this.name=``,this.autoPosition=!0,this.all=!0,this.allSelected=!1,this.search=!0,this.disabled=!1,this.creatable=!1,this.async=!1,this.debounce=500,this.resizable=!1,this.filterByContains=!1,this.filterSearchValue=``,this.clickOutside=e=>this.handleClickOutside(e),this.open=!1,this.options=[],this.selectedOptions=[],this.filteredAvailableOptions=[...this.options],this.position=yw.BELOW,this.itemRenderer=this.defaultItemRenderer,this.initialisedOptions=!1,this.isResizing=!1,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.handleResizeStart=e=>{this.resizable&&this.multiselectDropdown&&(e.preventDefault(),e.stopPropagation(),this.isResizing=!0,this.startX=e.clientX,this.startY=e.clientY,this.startWidth=this.multiselectDropdown.offsetWidth,this.startHeight=this.multiselectDropdown.offsetHeight,this.multiselectDropdown.classList.add(`is-resizing`),document.addEventListener(`mousemove`,this.handleResizeMove),document.addEventListener(`mouseup`,this.handleResizeEnd))},this.handleResizeMove=e=>{if(!this.isResizing||!this.multiselectDropdown)return;e.preventDefault();let t=e.clientX-this.startX,n=e.clientY-this.startY,r=Math.max(250,this.startWidth+t),i=Math.max(100,this.startHeight+n);this.multiselectDropdown&&(this.multiselectDropdown.style.width=`${r}px`,this.multiselectDropdown.style.maxHeight=`${i}px`)},this.handleResizeEnd=()=>{this.isResizing=!1,document.removeEventListener(`mousemove`,this.handleResizeMove),document.removeEventListener(`mouseup`,this.handleResizeEnd),this.multiselectDropdown&&(this.multiselectDropdown.classList.remove(`is-resizing`),this.multiselectDropdown.style.setProperty(`--custom-max-height`,this.multiselectDropdown.style.maxHeight),this.multiselectDropdown.style.removeProperty(`max-height`))}}debounceChanged(e,t){this.debouncedInputHandler=(0,bw.default)(this.asyncSetFilter,t)}openChanged(e,t){var n,r,i,a;t?(document.addEventListener(`mousedown`,this.clickOutside),(n=this.arrowIcon)==null||n.classList.add(`flipped`),(r=this.multiselectDropdown)==null||r.classList.add(`visible`)):(document.removeEventListener(`mousedown`,this.clickOutside),(i=this.arrowIcon)==null||i.classList.remove(`flipped`),(a=this.multiselectDropdown)==null||a.classList.remove(`visible`))}connectedCallback(){var e;super.connectedCallback(),this.position===yw.ABOVE&&((e=this.multiselectDropdown)==null||e.classList.add(`position-above`))}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`mousedown`,this.clickOutside),document.removeEventListener(`mousemove`,this.handleResizeMove),document.removeEventListener(`mouseup`,this.handleResizeEnd)}defaultItemRenderer(e,t){return T` ${typeof e==`string`?T`<span part="option-label">${()=>t.getItemLabel(e)}</span>`:T`<span data-option-label-text=${()=>e.optionLabelText}style=${()=>e.labelStyle}part="option-label">${()=>t.getItemLabel(e)}</span>`} `}toggle(){this.open||this.setDropdownPosition(),this.open=!this.open}optionsChanged(){this.allSelected&&!this.initialisedOptions&&(this.selectedOptions=this.options.map(e=>this.optionValueGetter(e))),this.filteredAvailableOptions=[...this.options]}selectedOptionsChanged(){if(this.$fastController.isConnected){this.initialisedOptions=!0;return}}setDropdownPosition(){let e=this.position;if(this.autoPosition){let t=this.getBoundingClientRect(),n=window.innerHeight,r=t.top,i=n-t.bottom;e=i<230&&r>i?yw.ABOVE:yw.BELOW}this.multiselectDropdown.classList.toggle(`position-above`,e===yw.ABOVE),this.multiselectDropdown.classList.toggle(`position-below`,e===yw.BELOW)}optionValueGetter(e){return typeof e==`string`?e:e.value}optionLabelGetter(e){return typeof e==`string`?e:e.label}getItemLabel(e){let t;return e?(t=typeof e==`string`?e:this.optionLabelGetter(e)||this.optionValueGetter(e)||``,this.valueFormatter?this.valueFormatter(t):t):``}isOptionDisabled(e){return!e||typeof e==`string`?!1:e.disabled||!1}get getDisplayValue(){let e=this.selectedOptions.length;if(e===0)return this.getPlaceholder;if(e===1){let e=this.options.find(e=>this.isOptionSelected(e));if(e)return this.getItemLabel(e);let[t]=this.selectedOptions;return typeof t==`string`?this.getItemLabel(t):`1 Selected`}return e===this.options.length&&this.options.every(e=>this.isOptionSelected(e))?`All ${this.name}`.trim():`${e} Selected`}get getPlaceholder(){return`Search ${this.name}`.trim().concat(`...`)}get isAllOptionsDisabled(){return this.options.length===this.options.filter(this.isOptionDisabled).length}get areAllOptionsSelected(){let e=this.options.filter(e=>!this.isOptionDisabled(e));return e.length>0&&e.every(e=>this.isOptionSelected(e))}get showCreatable(){return this.creatable&&this.filterSearchValue.trim().length>0&&this.findExactMatchOptions().length===0}isOptionSelected(e){let t=this.optionValueGetter(e);return this.selectedOptions.some(n=>{if(typeof e==`object`&&typeof e.value==`object`)try{return JSON.stringify(n)===JSON.stringify(t)}catch{return n===t}return n===t})}selectCheckboxOne(e){let t=this.optionValueGetter(e);this.selectedOptions=this.selectedOptions.includes(t)?this.selectedOptions.filter(e=>e!==t):[...this.selectedOptions,t],this.updateSelection(this.selectedOptions)}checkboxKeyDown(e,t){return t.key===` `&&(t.preventDefault(),this.selectCheckboxOne(e)),!0}getEnabledOptionsCount(){return this.options.length-this.options.filter(this.isOptionDisabled).length}selectCheckboxAll(){let e=this.areAllOptionsSelected;this.selectedOptions=e?[]:this.options.filter(e=>!this.isOptionDisabled(e)).map(e=>this.optionValueGetter(e)),this.onAllSelectedCallback&&this.onAllSelectedCallback(!e),this.updateSelection(this.selectedOptions)}inputHandler(){this.open||(this.open=!0),this.async?(this.loading=!0,this.filteredAvailableOptions=[],this.debouncedInputHandler()):this.setFilter()}findExactMatchOptions(){let e=this.filterSearchValue.toLowerCase();return this.filteredAvailableOptions.filter(t=>((typeof t==`string`?t:this.optionLabelGetter(t)??this.optionValueGetter(t))?.toLowerCase()??``)===e)}setFilter(){let e=this.filterSearchValue.toLowerCase();this.filteredAvailableOptions=this.options.filter(t=>{if(!e)return!0;if(typeof t==`string`)return t.toLowerCase().includes(e);let n=t.label.toLowerCase(),r=typeof t.value==`object`?(t=>Object.values(t).some(t=>t.toLowerCase().includes(e)))(t.value):String(t.value).toLowerCase().includes(e);return n.includes(e)||r})}updateSelection(e){this.selectedOptions=e,this.$emit(`selectionChange`,this.selectedOptions)}addOption(){let e=this.filterSearchValue.trim();if(!e||this.options.some(t=>this.optionValueGetter(t)===e))return;let t={value:e,label:e};this.$emit(`optionCreated`,t)!==!1&&(this.options=[t,...this.options],this.setFilter(),this.updateSelection([...this.selectedOptions,e]))}asyncSetFilter(){this.slottedDatasource.length>0?Wb(this.slottedDatasource[0],this.filterSearchValue):(this.loading=!1,xb.warn(`Multiselect-datasource is not connected. Please add a datasource to use this functionality.`))}changeHandler(e){e.preventDefault(),e.stopImmediatePropagation()}handleClickOutside(e){Cb(e,this)&&(this.open=!1)}keydownHandler(e){let t=e.key;if(e.ctrlKey||e.shiftKey)return!0;switch(t){case`Escape`:if(this.open){this.open=!1;break}break;case`ArrowUp`:case`ArrowDown`:if(!this.open){this.open=!0;break}break;default:return!0}}clear(e={}){let{clearSelectedValues:t=!0,clearFilterText:n=!0}=e;t&&this.updateSelection([]),n&&(this.filterSearchValue=``,this.setFilter(),this.filterSearchInput&&(this.filterSearchInput.value=``)),this.$emit(`clear`,{clearSelectedValues:t,clearFilterText:n})}};q([D],Dw.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],Dw.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],Dw.prototype,`all`,void 0),q([D({mode:`boolean`})],Dw.prototype,`allSelected`,void 0),q([D({mode:`boolean`})],Dw.prototype,`search`,void 0),q([D({mode:`boolean`})],Dw.prototype,`disabled`,void 0),q([D({mode:`boolean`})],Dw.prototype,`creatable`,void 0),q([D({mode:`boolean`})],Dw.prototype,`async`,void 0),q([D],Dw.prototype,`debounce`,void 0),q([D({mode:`boolean`})],Dw.prototype,`resizable`,void 0),q([D],Dw.prototype,`tabindex`,void 0),q([D({mode:`boolean`,attribute:`filter-by-contains`})],Dw.prototype,`filterByContains`,void 0),q([C],Dw.prototype,`defaultSlottedNodes`,void 0),q([C],Dw.prototype,`slottedDatasource`,void 0),q([C],Dw.prototype,`valueFormatter`,void 0),q([C],Dw.prototype,`loading`,void 0),q([C],Dw.prototype,`filterSearchValue`,void 0),q([C],Dw.prototype,`open`,void 0),q([C],Dw.prototype,`options`,void 0),q([C],Dw.prototype,`selectedOptions`,void 0),q([C],Dw.prototype,`filteredAvailableOptions`,void 0),q([C],Dw.prototype,`scrollContainer`,void 0),q([D],Dw.prototype,`position`,void 0),q([C],Dw.prototype,`onAllSelectedCallback`,void 0),q([C],Dw.prototype,`itemRenderer`,void 0),q([w],Dw.prototype,`getDisplayValue`,null),q([w],Dw.prototype,`getPlaceholder`,null),q([w],Dw.prototype,`isAllOptionsDisabled`,null),q([w],Dw.prototype,`areAllOptionsSelected`,null),q([w],Dw.prototype,`showCreatable`,null),q([C],Dw.prototype,`optionsHeaderSlottedNodes`,void 0),Dw.compose(Object.assign({baseName:`multiselect`,template:Tse,styles:xw,shadowOptions:void 0},Ew));let Ow=O` .root{position: relative;width: 100%;min-width: 250px}.control-button{display: flex;justify-content: center;min-width: 31px;width: 31px;height: 31px;margin-left: calc(var(--design-unit) * 2px);color: var(--neutral-foreground-hint)}.control{cursor: pointer;position: relative;display: flex;justify-content: end;align-items: center;width: 100%;border-radius: calc(var(--control-corner-radius) * 1px)}.label{display: block;cursor: pointer;font-size: var(--type-ramp-base-font-size);line-height: var(--type-ramp-base-line-height);font-style: normal;font-weight: 700;margin: calc(var(--design-unit) * 2px) 0}.label-hidden{display: none}.control:hover .control-button, .control:hover .label{color: var(--neutral-foreground-rest)}button{pointer-events: none}.options{display: flex;flex-direction: column;position: absolute;height: max-content;overflow-y: hidden;margin-top: 5px;padding: calc((var(--design-unit) + 3) * 2px) calc((var(--design-unit) + 3) * 1px);border: 1px solid rgba(46 51 57 / 100%);border-radius: 4px;background: var(--neutral-fill-input-rest);width: 100%;max-height: 0;visibility: hidden;transition: max-height 0.4s ease 0s, visibility 0.4s ease 0s;z-index: 999}.option-content{display: flex;align-items: center;gap: calc(var(--design-unit) * 4px);width: 100%}.icon-container{display: flex;align-items: center;justify-content: center;width: calc( ((var(--base-height-multiplier) * var(--design-unit)) + (var(--design-unit) * 2)) * 1px + 4px );height: calc( ((var(--base-height-multiplier) * var(--design-unit)) + (var(--design-unit) * 2)) * 1px );border-radius: calc((var(--control-corner-radius) - 1) * 2px);background: var(--neutral-layer-2);box-sizing: border-box;box-shadow: 0 0 5px 0 rgba(0 0 0 / 35%);flex-shrink: 0}.text-content{display: flex;flex-direction: column;flex: 1}.svg-icon{height: 2em}.position-above{bottom: 100%}.checkbox-container{display: flex;flex-direction: column;overflow-y: scroll;scrollbar-width: thin;scrollbar-color: rgb(46 48 53) rgb(31 33 38)}span{border-bottom: calc(var(--stroke-width) * 1px) solid;border-color: color-mix(in srgb, var(--neutral-fill-rest), transparent 50%);padding: calc((var(--design-unit) + 2) * 2px) calc((var(--design-unit) + 3) * 1px);font-size: calc((var(--type-ramp-base-font-size) - 1px));color: var(--neutral-foreground-hint)}.multiselect-checkbox{min-width: fit-content;flex-direction: row-reverse;justify-content: space-between;align-items: flex-start;border-bottom: 1px solid;border-color: color-mix(in srgb, var(--neutral-fill-rest), transparent 50%);padding: calc((var(--design-unit) + 3) * 1px) calc((var(--design-unit) + 3) * 1px) calc((var(--design-unit) + 3) * 1px) 0;margin: 0}.multiselect-checkbox:hover{background-color: rgb(45 47 51);cursor: pointer}.multiselect-checkbox::part(label){overflow-x: hidden;text-overflow: ellipsis}.multiselect-checkbox::part(control){min-width: calc( ((var(--base-height-multiplier) + var(--density)) * var(--design-unit) / 2 + var(--design-unit)) * 1px )}.checkbox-container .multiselect-checkbox[disabled]{cursor: not-allowed}.description{text-wrap: wrap;font-size: calc((var(--type-ramp-base-font-size) - 1px));margin: calc((var(--design-unit) + 3) * 1px) 0}#filter-search{padding: 5px}::-webkit-scrollbar{width: 12px}::-webkit-scrollbar-track{background: rgb(31 33 38)}::-webkit-scrollbar-thumb{width: 8px;border-radius: 10px;box-shadow: inset 0 0 6px rgba(0 0 0 / 30%);background-color: rgb(46 48 53);border: 3px solid rgb(31 33 38)}.visible{visibility: visible;max-height: ${`450`}px}`,kw=(e=`foundation`)=>T`<div class="root" part="root"><div class="control" part="control" @click=${e=>!e.disabled&&e.toggle()}><label part="label" for="control" class=${e=>fn(`label`,[`label-hidden`,!e.defaultSlottedNodes?.length])}><slot ${bt({property:`defaultSlottedNodes`,filter:ga})}></slot></label><${e}-button class="control-button" part="control-button"><slot name="button-content"><${e}-icon name="plus" variant="solid" size="lg"></${e}-icon></slot></${e}-button></div><div ${k(`optionsElement`)}class="options" part="options">${A(e=>e.search,T`<${e}-text-field id="filter-search" part="filter-search" value=${df(e=>e.filterSearchValue,`string`,`input`)}placeholder="${e=>e.getPlaceholder}" @input=${(e,t)=>e.setFilter()}@change=${(e,t)=>e.changeHandler(t.event)}></${e}-text-field>`)}<div class="checkbox-container" part="checkbox-container">${j(e=>e.filteredAvailableOptions,T`<span>${e=>e.type}</span>${j(e=>e.options,T`<${e}-checkbox class="multiselect-checkbox" part="multiselect-checkbox" @click=${(e,t)=>t.parentContext.parent.selectCheckboxOne(e)}@change=${(e,t)=>t.parentContext.parent.changeHandler(t.event)}?current-checked="${(e,t)=>t.parentContext.parent.isOptionSelected(e)}" ?disabled="${(e,t)=>t.parentContext.parent.isOptionDisabled(e)}"><div class="option-content">${A(e=>e.icon||e.svg,T`<div class="icon-container">${A(e=>e.icon,T`<${e}-icon style="color:${e=>e.iconColor||`#fff`}" name="${e=>e.icon}" size="xl"></${e}-icon>`)} ${A(e=>e.svg,T`<img class="svg-icon" src="${e=>e.svg}" alt="${e=>e.label}" />`)}</div>`)}<div class="text-content"><div class="option-label">${(e,t)=>t.parentContext.parent.getItemLabel(e)}</div>${A(e=>e.description,T`<p class="description">${e=>e.description}</p>`)}</div></div></${e}-checkbox>`)} `)}</div></div></div>`,Ese=T` ${kw()} `,Aw={};var jw=class extends P{constructor(){super(...arguments),this.name=``,this.autoPosition=!0,this.search=!0,this.disabled=!1,this.clickOutside=e=>this.handleClickOutside(e),this.open=!1,this.options=[],this.selectedOptions=[],this.position=yw.BELOW}openChanged(e,t){var n,r;t?(document.addEventListener(`mousedown`,this.clickOutside),(n=this.optionsElement)==null||n.classList.add(`visible`)):(document.removeEventListener(`mousedown`,this.clickOutside),(r=this.optionsElement)==null||r.classList.remove(`visible`))}connectedCallback(){var e;super.connectedCallback(),this.position===yw.ABOVE&&((e=this.optionsElement)==null||e.classList.add(`position-above`))}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`mousedown`,this.clickOutside)}toggle(){this.open||this.setDropdownPosition(),this.open=!this.open}sortFilteredOptions(e){let t=(e??this.options).reduce((e,t)=>{let n=t.type||`Other`;return e[n]?e[n].options.push(t):e[n]={type:n,options:[t]},e},{});return Object.values(t)}optionsChanged(){this.filteredAvailableOptions=this.sortFilteredOptions()}setDropdownPosition(){let e=this.position;if(this.autoPosition){let t=this.assignedSlot?this.assignedSlot.parentElement:this.parentElement;for(;t&&!t.classList.contains(`content-wrapper`);)t=t.parentElement;if(t){let n=t.getBoundingClientRect(),r=this.getBoundingClientRect(),i=n.top+n.height/2;e=r.top<i?yw.BELOW:yw.ABOVE}else{let t=this.getBoundingClientRect(),n=window.innerHeight,r=t.top,i=n-t.bottom;e=i<t.height&&r>i?yw.ABOVE:yw.BELOW}}e===yw.ABOVE?(this.optionsElement.classList.add(`position-above`),this.optionsElement.classList.remove(`position-below`)):e===yw.BELOW&&(this.optionsElement.classList.add(`position-below`),this.optionsElement.classList.remove(`position-above`))}optionGetter(e){return e.value}getItemLabel(e){let t;if(e)t=e.label||e.value||``;else return``;return this.valueFormatter?this.valueFormatter(t):t}isOptionDisabled(e){return!e||typeof e==`string`?!1:e.disabled||!1}get getPlaceholder(){return`Search ${this.name}`.trim().concat(`...`)}isOptionSelected(e){return this.selectedOptions.includes(this.optionGetter(e))}selectCheckboxOne(e){let t=this.optionGetter(e);this.selectedOptions.includes(t)?(this.selectedOptions=[...this.selectedOptions],this.selectedOptions.splice(this.selectedOptions.indexOf(t),1)):this.selectedOptions=[...this.selectedOptions,t],this.$emit(`selectionChange`,this.selectedOptions)}setFilter(){let e=this.options.filter(e=>{let t=e.description,n=e.label??e.value;if(t?.toLowerCase().includes(this.filterSearchValue.toLowerCase())||n.toLowerCase().includes(this.filterSearchValue.toLowerCase()))return e});this.filteredAvailableOptions=this.sortFilteredOptions(e)}changeHandler(e){e.preventDefault(),e.stopImmediatePropagation()}handleClickOutside(e){Cb(e,this)&&(this.open=!1)}};q([D],jw.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],jw.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],jw.prototype,`search`,void 0),q([D({mode:`boolean`})],jw.prototype,`disabled`,void 0),q([C],jw.prototype,`defaultSlottedNodes`,void 0),q([C],jw.prototype,`valueFormatter`,void 0),q([C],jw.prototype,`filterSearchValue`,void 0),q([C],jw.prototype,`open`,void 0),q([C],jw.prototype,`options`,void 0),q([C],jw.prototype,`selectedOptions`,void 0),q([C],jw.prototype,`filteredAvailableOptions`,void 0),q([C],jw.prototype,`position`,void 0),q([w],jw.prototype,`getPlaceholder`,null),jw.compose(Object.assign({baseName:`categorized-multiselect`,template:Ese,styles:Ow,shadowOptions:void 0},Aw));let Mw=(e,t)=>Pr(e,t),Nw=(e,t)=>O` ${Jl(e,t)}`;var Pw=class extends Fr{};let Fw={checkedIndicator:`
258
258
  <svg
259
259
  aria-hidden="true"
260
260
  part="checked-indicator"