@genesislcap/foundation-rapid-cdn 15.98.2 → 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 dy(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 fy={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 py(e,t){function n(n,r,i){if(typeof document<`u`){i=dy({},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,``,dy({},t,{expires:-1}))},withAttributes:function(e){return py(this.converter,dy({},this.attributes,e))},withConverter:function(e){return py(dy({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var my=py(fy,{path:`/`});let hy=N.createInterface();function gy(){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 _y(e=``,t=`:`,n){return e.split(t,n).map(e=>e.trim()).filter(e=>e!==``)}function vy(e,t=`:`){let n=typeof e==`string`&&e.trim();return n?n.includes(t):!1}function yy(e,t=`:`){return typeof e==`string`&&e.trim()?(e.match(new RegExp(t,`g`))||[]).length:0}function by(e,t=`:`){for(let n of e)if(vy(n,t))return n;return e.find(e=>typeof e==`string`&&e.trim()!==``)}function xy(e,t,n){let r=typeof e==`string`&&e.trim();return!r||n&&!r.includes(n)||yy(r)>1?n&&t&&n!==t?`${t}:${n}`:t||n:r}function Sy(e=`credential`){Y.warn(`Unable to migrate legacy ${e} to latest format. Please remove from your browser.`)}let Cy={password:!0,mediation:`optional`},wy={cookie:{path:`/`,name:`credentials`,expires:7300,storePasswords:!1}},Ty=class{constructor(e,t=wy){this.session=e,this.config=t}createBasicCredentials(e){return{type:Mg.BASIC,username:e.username,password:e.password,mfaToken:this.getMFAToken()}}createRefreshCredentials(e){return{type:Mg.REFRESH,username:e?.username??this.getUsername(),refreshToken:e?.refreshToken??this.getRefreshToken(),mfaToken:e?.mfaToken??this.getMFAToken()}}createSSOCredentials(e){return{type:Mg.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(`:`)&&yy(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]=_y(t.name||t.id),[r,i]=_y(by([t.id,t.name]));return[{id:xy(t.id||t.name,n,i),name:n,password:t.password||``},!0]}catch{Sy(`PasswordCredential`)}if(t)try{let e=t,[n]=_y(e.name||e.username||e.organisation),[r,i]=_y(by([e.organisation||e.username||e.name]));return[{id:xy(e.id||e.username||e.name,n,i),name:n,password:e.password||``},!1]}catch{Sy(`cookie`)}return[void 0,!1]}storeCredentialsInContainer(e){return J(this,void 0,void 0,function*(){if(!gy())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=Cy){if(gy())return Y.debug(`Getting credentials from CredentialsContainer`),yield navigator.credentials.get(e)})}storeCredentialsInCookie(e){let{password:t}=e,n=rd(e,[`password`]),r=this.config.cookie.storePasswords?e:n;return Y.debug(`Storing credentials in cookie`),!!my.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=my.get(this.config.cookie.name);return e?JSON.parse(e):void 0}storeCredentials(e){return J(this,void 0,void 0,function*(){if(gy()){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 gy()?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(){my.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 gy()&&navigator.credentials.preventSilentAccess()}};Ty=q([id(0,Dg),id(1,It(hy))],Ty);let Ey=N.createInterface(e=>e.singleton(Ty)),Dy=e=>e?{date:e.DATE}:null,Oy=e=>e?e.map(e=>({name:e.NAME,version:e.VERSION})):[],ky=e=>Array.isArray(e)?e.map(e=>e??``):[],Ay=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:Dy(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:Oy(t.PRODUCT)}:null,permission:ky(e.PERMISSION),profile:ky(e.PROFILE)}}throw Error(`No Entity mapping implementation for provided DTO`)}catch(e){throw Y.error(e),e}},jy=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 Pm(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 Ng(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(Ay(n)),this.session.setAuthResult(n),Y.debug(`Login Authentication Result:`,vg(n))}catch(e){if(Y.error(dg(`Login Authentication Error:`,e?.received),yg(e)),e instanceof Ng&&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===Pg.LOGOUT_NACK;c&&Y.warn(`Unexpected Logout NACK received during logout.`,s),e={success:a===Pg.LOGOUT_ACK||n===Ig.SESSION_NOT_FOUND||!c,error:s},o&&window.open(o,`_self`)}catch(t){let n=new Ng(t.sentMessage,t.receivedMessage);if(Y.error(dg(`Logout Authentication Error:`,n.received),yg(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===Fg.EVENT_LOGIN_AUTH_ACK)return this.session.setAuthResult(t),this.currentUser.set(Ay(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],jy.prototype,`isWorking`,void 0),q([C],jy.prototype,`loggedUserResult`,void 0),jy=q([id(0,Dg),id(1,cy),id(2,Vg),id(3,Ey),id(4,ig)],jy);let My=N.createInterface(e=>e.singleton(jy));function Ny(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 Py={n:`
|
|
246
246
|
`,r:`\r`,t:` `,b:`\b`,f:`\f`};function Fy(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2].replace(/\\([\s\S])/g,(e,t)=>Py[t]??t):t}function Iy(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`]=Fy(r)}break}case`dateTimeIsLessEqual`:{let n=e.match(/Expr\.dateTimeIsLessEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=Fy(r)}break}case`dateIsGreaterEqual`:{let n=e.match(/Expr\.dateIsGreaterEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_FROM`]=Fy(r)}break}case`dateIsLessEqual`:{let n=e.match(/Expr\.dateIsLessEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=Fy(r)}break}case`containsIgnoreCase`:{let n=e.match(/Expr\.containsIgnoreCase\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[e]=`*${Fy(r)}*`}break}}}function Ly(e,t){let n=e.indexOf(`=`),r=e.substr(0,n).trim().replace(/["']/g,``);t[r]=Fy(e.slice(n).replace(/^==?/,``))}function Ry(e){if(!e)return{};let t=e.split(`&&`).map(e=>e.trim()),n={};return t.forEach(e=>{if(e){if(e.startsWith(`Expr`))Iy(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`]=Ny(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`]=Ny(i,o)}}else Ly(e,n)}}),n}function zy(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 By=class{};By.MAX_ROWS_250=250,By.MAX_VIEW_1000=1e3,By.REQ_REP_POLLING_INTERVAL_MS=1e4,By.DATASERVER_ROW_ID=`ROW_REF`,By.REQUEST_SERVER_ROW_ID=`RECORD_ID`,By.DEFAULT_PAGINATION_PAGE_SIZE=25,By.DEFAULT_REQ_REP_OFFSET=0;let Vy={options:{criteria:``,isSnapshot:!1,maxRows:By.MAX_ROWS_250,maxView:By.MAX_VIEW_1000,pollingInterval:By.REQ_REP_POLLING_INTERVAL_MS,movingView:!1,orderBy:``,resourceName:``,reverse:!1,pollTriggerEvents:[]},criteriaToFields:Ry,dataServerResultFilter:zy},Hy=N.createInterface(e=>e.instance(Vy));function Uy(e){let t=e==null?NaN:Number(e);return Number.isFinite(t)?t===0?1/0:t:By.MAX_VIEW_1000}function Wy(e){return e.moreRows===!1?`end`:e.rowsHeld>=Uy(e.maxView)?e.movingView?`more`:`view-full`:e.emptyReply?`stalled`:`more`}function Gy(e){let t=Uy(e.maxView),n=Ky(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 Ky(e){return e==null||!Number.isFinite(Number(e))}let qy=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(cg,this.onDatasourceStatusChanged,{passive:!0,capture:!0})}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(cg,this.onDatasourceStatusChanged,{capture:!0})}}return q([C],t.prototype,`datasourceStatus`,void 0),t},Jy={throwWhenUnavailable:!0,throwWhenUnknown:!1},Yy=N.createInterface(e=>e.instance(Jy)),Xy=Pd(`genesis-resources`);function Zy(){return N.getOrCreateDOMContainer().get(Xy)}let Qy=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=Zy();e.postMessage(`resources-loaded`,this.resources),e.close()}};Qy=q([id(0,cy),id(1,Yy)],Qy);let $y=N.createInterface(e=>e.singleton(Qy)),eb=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 Mm}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 Mm,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=rd(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 sg.DATASERVER:return this.connect.snapshot(this.options.resourceName,Object.assign(Object.assign({},this.dataserverOnlyParams),e));case sg.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(![sg.DATASERVER,sg.REQUEST_SERVER].includes(this.resourceType))throw Error(`Streaming not supported for selected resource type: ${this.resourceType}`);return this.resourceType===sg.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(dg(`${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===sg.REQUEST_SERVER&&this.loadMoreCount>0){let t=(this.options.maxRows||25)*(this.loadMoreCount+1);e.DETAILS.MAX_ROWS=t}return Cie([this.connect.isConnected$,this.auth.isLoggedIn$]).pipe(Dh(()=>this.connect.isConnected&&this.auth.isLoggedIn),Eh(()=>fh(this.snapshot(e))))};return e?this.pollTrigger$.pipe(Th(0),Eh(()=>bh(0,e).pipe(Eh(t)))):this.pollTrigger$.pipe(Th(0),Eh(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=ug(n),this.fieldMetadata=lg(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(dg(`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 '${cg}'`,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],eb.prototype,`status`,void 0),q([C],eb.prototype,`fetchMetadataRequired`,void 0),q([C],eb.prototype,`startStreamRequired`,void 0),q([C],eb.prototype,`originalFieldDef`,void 0),q([C],eb.prototype,`fieldMetadata`,void 0),q([C],eb.prototype,`requestFields`,void 0),q([C],eb.prototype,`customRequestFields`,void 0),q([C],eb.prototype,`availableIndexes`,void 0),q([C],eb.prototype,`availableSortableFields`,void 0),q([C],eb.prototype,`availableCriteriaFields`,void 0),q([C],eb.prototype,`criteriaOnlyRequest`,void 0),q([C],eb.prototype,`loadMoreCount`,void 0),q([C],eb.prototype,`readOnly`,void 0),q([C],eb.prototype,`stream`,void 0),eb=q([id(0,cy),id(1,My),id(2,$y),id(3,Hy),id(4,Tg)],eb);let tb=N.createInterface(e=>e.transient(eb));var nb=class extends eb{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===Pg.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(nb));function rb(e,t=`;`){return e&&e.split(t).map(e=>e.trim()).sort((e,t)=>e.localeCompare(t)).join(t)}let ib=`system-health-changed`,ab={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 ly().getMoreColumns(e),n=Date.now(),r=t;return{isConnected:t.MESSAGE_TYPE===Pg.MORE_COLUMNS_ACK,lastUpdated:n,lastMessage:r}}),resourceDataLogon:({message:e,functions:t})=>{let{onMessage:n,onError:r}=t;ny().sendForStream(e,n,r)}},ob=N.createInterface(e=>e.instance(ab));var sb=/* @__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}})}))})),cb=/* @__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)}}})),lb=/* @__PURE__ */ u(sb()),ub=/* @__PURE__ */ u(cb());let db=Ad(`network-monitor`,{level:vd.info}),fb=Date.now(),pb=window.navigator?.userAgent?lb.default.parse(window.navigator.userAgent):void 0,mb=(e,t={depthLimit:10,edgesLimit:10})=>e instanceof Event?`'${e.type}' Event`:typeof e==`string`?e:(0,ub.default)(e,void 0,2,t);var hb=class{constructor(){this.unsubscribableObservers=[],this.runAllChecks=(e,t)=>J(this,void 0,void 0,function*(){if(!this.isReady||this.isRunningChecks&&!t)return;db.info(`Run health checks, triggered by`,mb(e),`| Active resources`,this.resources.size),this.isRunningChecks=!0,this.synchroniseCheckInterval();let n=this.getFormattedTimestamp(this.getNowTimestamp()),r=yield this.isOnlineCheck();r?db.debug(`Network connected at ${n}`):db.warn(`Network disconnected at ${n}`);let i=this.normaliseSerializedSocketStatus(this.socketStatus.serialize(),r),a=this.preFlightSocketChecks(i);if(a||db.debug(`Socket pre-flight checks failed`),!r||!a){db.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{db.debug(`Running health check against ${r}`);let e=yield Promise.race([c(u,t),Wf(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===Pg.MSG_NACK||zg(p,fg.NOT_FOUND),n=this.getFormattedTimestamp(f??this.getNowTimestamp()),d?db.debug(`${r} is healthy at ${n}`):db.warn(`${r} is not healthy at ${n}`),p&&db.debug(`${r} messaged at ${n}`,mb(p)),m&&db.error(`${r} errored at ${n}`,mb(m)),h&&db.warn(`${r} timed out at ${n}`),g&&(db.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 db.warn(`Unexpected promise rejection occurred. Please check any custom resourceChecks return MonitoredResourceChecksResult.`),e},{});db.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&&(db.level=this.config.logLevel)}create(){if(this.resources){db.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=``;zg(i,fg.NOT_FOUND)?a=`Please check the resource is running.`:zg(i,fg.FORBIDDEN)&&(a=`You are not authorised to access this resource, removing it from monitoring.`,this.removeResource(n)),db.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){db.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?db.debug:db.warn)(`Emitting 'system-health-changed' event`,mb(this.status)),t?.dispatchEvent(new CustomEvent(`system-health-changed`,{detail:this.status,bubbles:t!==document,composed:!0})),this.status.socket.reconnectionLimitReached&&(db.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 db.debug(`User requested report stability to Genesis.`),db.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:pb,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:fb,runAllChecks:()=>{db.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return db.debug(`Socket not configured`),!1;if(e.isReconnecting)return db.debug(`Socket reconnecting`),!1;if(e.isConnecting)return db.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return db.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&db.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return db.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return Pf(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([ob],hb.prototype,`config`,void 0),q([Yv],hb.prototype,`socketStatus`,void 0),q([Tg],hb.prototype,`connectEvents`,void 0),q([ig],hb.prototype,`user`,void 0),q([C],hb.prototype,`status`,void 0);let gb=N.createInterface(e=>e.singleton(hb)),_b={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},vb=N.createInterface();var yb;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(yb||(yb={}));var bb;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(bb||(bb={}));let xb=class{constructor(e,t,n=_b){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(bb.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(yb.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=vf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=vf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=vf(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(yb.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?bf(e.value):e.value}))}},n=yield this.connect.commitEvent(bb.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};xb=q([id(0,cy),id(1,ig),id(2,It(vb))],xb),N.createInterface(e=>e.singleton(xb));var Sb=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Pm(!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 rg,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],Sb.prototype,`isWorking`,void 0),q([C],Sb.prototype,`loggedUserResult`,void 0),q([C],Sb.prototype,`currentUser`,void 0),q([C],Sb.prototype,`isLoggedIn`,void 0);var Cb=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=ug(e),this.fieldMetadata=lg(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=fh(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],Cb.prototype,`status`,void 0),q([C],Cb.prototype,`fetchMetadataRequired`,void 0),q([C],Cb.prototype,`originalFieldDef`,void 0),q([C],Cb.prototype,`fieldMetadata`,void 0),q([C],Cb.prototype,`requestFields`,void 0),q([C],Cb.prototype,`customRequestFields`,void 0),q([C],Cb.prototype,`availableIndexes`,void 0),q([C],Cb.prototype,`availableSortableFields`,void 0),q([C],Cb.prototype,`availableCriteriaFields`,void 0),q([C],Cb.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(ig));let wb=Ad(`foundation-ui`);var Tb=class extends qy(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=By.MAX_ROWS_250,this.maxView=By.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 Pm(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==rb(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===sg.REQUEST_SERVER?By.REQUEST_SERVER_ROW_ID:By.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}wb.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?zy(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Pg.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 sg.REQUEST_SERVER:return!0;case sg.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===sg.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 zy(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==sg.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=Wy({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=Gy({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&wb.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 rb((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&&wb[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===og.DATE||t===og.DATETIME?Ff(e,t===og.DATETIME):e}};q([cy],Tb.prototype,`connect`,void 0),q([tb],Tb.prototype,`datasource`,void 0),q([D({mode:`boolean`})],Tb.prototype,`withGridInit`,void 0),q([D],Tb.prototype,`criteria`,void 0),q([C],Tb.prototype,`data`,void 0),q([D],Tb.prototype,`fields`,void 0),q([D({mode:`boolean`})],Tb.prototype,`isSnapshot`,void 0),q([D],Tb.prototype,`maxRows`,void 0),q([D],Tb.prototype,`maxView`,void 0),q([D],Tb.prototype,`orderBy`,void 0),q([D],Tb.prototype,`request`,void 0),q([D],Tb.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],Tb.prototype,`reverse`,void 0),q([D],Tb.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],Tb.prototype,`withTimestampFormatting`,void 0);let Eb=(e,t)=>!e.composedPath().includes(t),Db=(e,t)=>e.composedPath().includes(t),Ob=e=>e.tagName.toLowerCase().split(`-`)[0];function kb(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let Ab=Ad(`foundation-criteria`);var jb;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(jb||(jb={}));var Mb=class e{constructor(e){this.$$operator=e}static And(){return new e(jb.AND)}static Or(){return new e(jb.OR)}static Not(){return new e(jb.NOT)}static GreaterThan(){return new e(jb.GT)}static GreaterThanOrEqual(){return new e(jb.GE)}static LessThan(){return new e(jb.LT)}static LessThanOrEqual(){return new e(jb.LE)}static NotEqual(){return new e(jb.NE)}static Equal(){return new e(jb.EQ)}get operator(){return this.$$operator}};let Nb=e=>e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`),Pb=e=>`'${Nb(e)}'`,Fb=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?Pb(t):t},Ib=e=>t=>`${t.field} ${e} ${Fb(t)}`,Lb=e=>Ib(jb.NE)(e),Rb=e=>`${e.field}.contains(${Fb(e)})`,zb={AND:e=>Ib(jb.AND)(e),OR:e=>Ib(jb.OR)(e),NOT:Lb,GT:e=>Ib(jb.GT)(e),GE:e=>Ib(jb.GE)(e),LT:e=>Ib(jb.LT)(e),LE:e=>Ib(jb.LE)(e),NE:Lb,EQ:e=>Ib(jb.EQ)(e),equals:e=>`${e.field}.equals(${Fb(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Fb(e)})`,contains:Rb,fieldContains:Rb,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Fb(e)})`,startsWith:e=>`${e.field}.startsWith(${Fb(e)})`,endsWith:e=>`${e.field}.endsWith(${Fb(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Fb(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Fb(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Fb(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Fb(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Fb(e)})`},Bb=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),Vb=e=>Array.isArray(e)?e:[e],Hb=`default`;var Ub=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,Mb.And()),this.Or=(e,t={})=>this.withExpression(e,t,Mb.Or()),this.Not=(e,t={})=>this.withExpression(e,t,Mb.Not())}withExpression(e,t={},n=Mb.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=Hb)=>{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 Mb;return t&&Ab.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Bb(t,i),Hb)}else o(e,Hb)}else typeof e==`string`?o(e,Hb):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 Mb&&n[t-1]instanceof Mb)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof Mb?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Wb=class{constructor(e){this.serialiser=zb.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 Gb=(e=`rapid`)=>T`<${e}-segmented-control :value="${mf(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>`,Kb=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Ub,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(Vb(i).map(e=>Vb(n).map(t=>new Wb().withField(t).withValue(e).withSerialiser(r).build())),{join:Mb.Or()}):t.And(new Wb().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],Kb.prototype,`criteriaOptions`,void 0),q([C],Kb.prototype,`prefix`,void 0),q([C],Kb.prototype,`value`,void 0),q([C],Kb.prototype,`selectedLabel`,void 0),Kb=q([$e({name:`criteria-segmented-control`,template:Gb(),styles:O``})],Kb);function qb(e,t){let n=new Ub;n.withExpression(new Wb().withField(e.labelField??e.valueField).withValue(t).withSerialiser(zb.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Jb(e,t){let n=new Ub;n.withExpression(new Wb().withField(e.valueField).withValue(t).withSerialiser(zb.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let Yb=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,Xb=e=>{let t=/* @__PURE__ */ new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))},Zb=Xb(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>`),Qb=Xb(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>`),$b=Xb(e=>T` ${t=>t.iconName?Zb(e):Qb(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>`),ex=Xb(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>`),tx=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Ob(e))}</div>`;var nx=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}},rx=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 nx(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 $b(e);if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],ex(e)):$b(e)}};q([C],rx.prototype,`actions`,void 0),q([C],rx.prototype,`actionsResolver`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],rx.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],rx.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],rx.prototype,`autoCloseOnAction`,void 0),q([C],rx.prototype,`classNames`,void 0),q([C],rx.prototype,`definition`,void 0),q([D],rx.prototype,`name`,void 0),q([D({attribute:`icon-name`})],rx.prototype,`iconName`,void 0),q([D({attribute:`open`,mode:`boolean`})],rx.prototype,`open`,void 0),q([D],rx.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],rx.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],rx.prototype,`hideMenuSingleOption`,void 0),q([C],rx.prototype,`singleOption`,void 0),rx.compose({baseName:`actions-menu`,styles:qne,template:tx});let ix=()=>{};function ax(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:ix};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 ox=!1;try{typeof GENX_ENABLE_AI<`u`&&(ox=GENX_ENABLE_AI===`true`)}catch{}let sx=()=>ox||Sf(`ai`),cx=Ad(`foundation-ai`);function lx(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function ux(e,t){if(!lx())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 dx=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 fx=[`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`],px=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`],mx=[`gpt-6-astra`,`gpt-6.1-sol`,`gpt-6.1-terra`,`gpt-6-sol`,`gpt-6-luna`];function hx(e){return e===`image/jpg`?`image/jpeg`:e}function gx(e){return e.replace(/^data:[^,]*;base64,/,``)}let _x=.5;function vx(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=_x?r/_x*t:t+(r-_x)/.5*(n-t)}let yx=1e6,bx={"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 xx(e){return bx[e]}function Sx(e,t){let{promptPerMillion:n,candidatePerMillion:r}=xx(e),i=yx,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 Cx={"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 wx(e,t,n=/* @__PURE__ */ new Date){let r=Cx[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 Tx(e,t,n=/* @__PURE__ */ new Date){let{promptPerMillion:r,candidatePerMillion:i}=wx(e,t.promptTokens,n),a=yx,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 Ex={"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 Dx(e,t){let n=Ex[e];return t<=272e3?n:{promptPerMillion:n.promptPerMillion*2,cachedPerMillion:n.cachedPerMillion*2,candidatePerMillion:n.candidatePerMillion*1.5}}function Ox(e,t){let{promptPerMillion:n,cachedPerMillion:r,candidatePerMillion:i}=Dx(e,t.inputTokens),a=yx,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 kx=[`properties`,`patternProperties`,`$defs`,`definitions`],Ax=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],jx=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Mx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Nx(e){if(Array.isArray(e))return e.map(Nx);if(Mx(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nx(r);return t}return e}function Px(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=kx.includes(i)&&Mx(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Mx(r)?t(r,`${e}/${n}`):Nx(r)])):Ax.includes(i)&&Array.isArray(a)?a.map((n,r)=>Mx(n)?t(n,`${e}/${r}`):Nx(n)):jx.includes(i)?Mx(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Mx(n)?t(n,`${e}/${r}`):Nx(n)):Nx(a):Nx(a)}return r}function Fx(e,t,n=``){return t(Px(e,(e,n)=>Fx(e,t,n),n),n)}let Ix=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Lx=[`oneOf`,`not`];function Rx(e){let t=[],n=[],r=[];return{schema:Fx(e,(e,i)=>{for(let n of Ix)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 Lx)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Mx(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function zx(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Rx(e);return r.length&&cx.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&cx.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&&cx.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 Bx=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Vx(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Mx(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Mx(n)?n:void 0}function Hx(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=Vx(e,o);if(!t)break;let{$ref:n}=i,r=rd(i,[`$ref`]);i=Object.assign(Object.assign({},Nx(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),Px(i,t=>Hx(e,t,a,r),``)}function Ux(e){let t=[],n=Hx(e,e,/* @__PURE__ */ new Set,t);return t.length&&cx.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.`),Fx(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(Mx),n=t.filter(e=>e.type!==`null`);if(t.length===2&&n.length===1){let{anyOf:t}=e,r=rd(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 Bx)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}let Wx=[`allOf`,`not`,`if`,`then`,`else`,`oneOf`];function Gx(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=>Mx(e)&&e.type===`null`)?e:Object.assign(Object.assign({},e),{anyOf:[...e.anyOf,{type:`null`}]}):{anyOf:[e,{type:`null`}]}}function Kx(e){let t=[],n=[],r=[];return{schema:Fx(e,(e,i)=>{for(let t of Wx)t in e&&r.push(`${i}/${t}`);if(!(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Mx(e.properties)))return e;if(e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),Mx(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]=Mx(a[e])?Gx(a[e]):{type:`null`},t.push(`${i}/properties/${e}`));e.required=n}return e}),madeNullable:t,overridden:n,undroppable:r}}function qx(e,t){let{schema:n,madeNullable:r,overridden:i,undroppable:a}=Kx(e);return r.length&&cx.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&&cx.warn(`OpenAITransport: tool "${t}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}.`),a.length&&cx.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 Jx=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`,`openai`]),new Map(Object.entries(Jx).map(([e,t])=>[t.toLowerCase(),e]));var Yx=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 Xx=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,Zx=e=>{try{return JSON.parse(e)}catch{return}},Qx=e=>{let t=e?.code;return typeof t==`string`?t:void 0},$x=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,eS=e=>typeof e==`boolean`?e:void 0,tS=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function nS(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 Yx(e,$x(r.budgetUsd)??$x(i.budgetUsd),$x(r.spentUsd)??$x(i.spentUsd),a,{otherVendorAvailable:eS(r.otherVendorAvailable)??eS(i.otherVendorAvailable),serverVendor:tS(r.vendor)??tS(i.vendor)})}function rS(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 iS(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 aS=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`}),oS=new Set(Object.values(aS));function sS(e){return typeof e==`string`&&oS.has(e)?e:void 0}let cS=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),lS=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},uS=e=>e?.code!==void 0;function dS(e,t,n){if(e!==401&&e!==403||uS(t))return;let r=typeof n==`string`&&n.trim()===``;if(lS(t)||r)return e===401?cS.SIGNED_OUT:cS.ACCESS_DENIED}function fS(e,t){return e===413&&t===void 0}function Qae(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let pS=`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:pS,FALLBACKS_NOT_SUPPORTED:pS,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 $ae=e=>e!==aS.VENDOR_UNREACHABLE;var eoe=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 $ae(this.code)}};function mS(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let toe=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]),noe=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var hS=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 roe(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 gS(e,t,n){if(t===400)for(let e of roe(n)){if(!toe.some(t=>t.test(e)))continue;let t=noe.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function ioe(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:pb,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:fb,runAllChecks:()=>{db.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return db.debug(`Socket not configured`),!1;if(e.isReconnecting)return db.debug(`Socket reconnecting`),!1;if(e.isConnecting)return db.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return db.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&db.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return db.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return Pf(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([ob],hb.prototype,`config`,void 0),q([Yv],hb.prototype,`socketStatus`,void 0),q([Tg],hb.prototype,`connectEvents`,void 0),q([ig],hb.prototype,`user`,void 0),q([C],hb.prototype,`status`,void 0);let gb=N.createInterface(e=>e.singleton(hb)),_b={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},vb=N.createInterface();var yb;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(yb||(yb={}));var bb;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(bb||(bb={}));let xb=class{constructor(e,t,n=_b){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(bb.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(yb.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=vf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=vf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=vf(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(yb.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?bf(e.value):e.value}))}},n=yield this.connect.commitEvent(bb.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};xb=q([id(0,cy),id(1,ig),id(2,It(vb))],xb),N.createInterface(e=>e.singleton(xb));var Sb=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Pm(!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 rg,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],Sb.prototype,`isWorking`,void 0),q([C],Sb.prototype,`loggedUserResult`,void 0),q([C],Sb.prototype,`currentUser`,void 0),q([C],Sb.prototype,`isLoggedIn`,void 0);var Cb=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=ug(e),this.fieldMetadata=lg(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=fh(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],Cb.prototype,`status`,void 0),q([C],Cb.prototype,`fetchMetadataRequired`,void 0),q([C],Cb.prototype,`originalFieldDef`,void 0),q([C],Cb.prototype,`fieldMetadata`,void 0),q([C],Cb.prototype,`requestFields`,void 0),q([C],Cb.prototype,`customRequestFields`,void 0),q([C],Cb.prototype,`availableIndexes`,void 0),q([C],Cb.prototype,`availableSortableFields`,void 0),q([C],Cb.prototype,`availableCriteriaFields`,void 0),q([C],Cb.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(ig));let wb=Ad(`foundation-ui`);var Tb=class extends qy(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=By.MAX_ROWS_250,this.maxView=By.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 Pm(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==rb(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===sg.REQUEST_SERVER?By.REQUEST_SERVER_ROW_ID:By.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}wb.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?zy(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Pg.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 sg.REQUEST_SERVER:return!0;case sg.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===sg.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 zy(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==sg.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=Wy({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=Gy({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&wb.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 rb((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&&wb[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===og.DATE||t===og.DATETIME?Ff(e,t===og.DATETIME):e}};q([cy],Tb.prototype,`connect`,void 0),q([tb],Tb.prototype,`datasource`,void 0),q([D({mode:`boolean`})],Tb.prototype,`withGridInit`,void 0),q([D],Tb.prototype,`criteria`,void 0),q([C],Tb.prototype,`data`,void 0),q([D],Tb.prototype,`fields`,void 0),q([D({mode:`boolean`})],Tb.prototype,`isSnapshot`,void 0),q([D],Tb.prototype,`maxRows`,void 0),q([D],Tb.prototype,`maxView`,void 0),q([D],Tb.prototype,`orderBy`,void 0),q([D],Tb.prototype,`request`,void 0),q([D],Tb.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],Tb.prototype,`reverse`,void 0),q([D],Tb.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],Tb.prototype,`withTimestampFormatting`,void 0);let Eb=(e,t)=>!e.composedPath().includes(t),Db=(e,t)=>e.composedPath().includes(t),Ob=e=>e.tagName.toLowerCase().split(`-`)[0];function kb(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let Ab=Ad(`foundation-criteria`);var jb;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(jb||(jb={}));var Mb=class e{constructor(e){this.$$operator=e}static And(){return new e(jb.AND)}static Or(){return new e(jb.OR)}static Not(){return new e(jb.NOT)}static GreaterThan(){return new e(jb.GT)}static GreaterThanOrEqual(){return new e(jb.GE)}static LessThan(){return new e(jb.LT)}static LessThanOrEqual(){return new e(jb.LE)}static NotEqual(){return new e(jb.NE)}static Equal(){return new e(jb.EQ)}get operator(){return this.$$operator}};let Nb=e=>e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`),Pb=e=>`'${Nb(e)}'`,Fb=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?Pb(t):t},Ib=e=>t=>`${t.field} ${e} ${Fb(t)}`,Lb=e=>Ib(jb.NE)(e),Rb=e=>`${e.field}.contains(${Fb(e)})`,zb={AND:e=>Ib(jb.AND)(e),OR:e=>Ib(jb.OR)(e),NOT:Lb,GT:e=>Ib(jb.GT)(e),GE:e=>Ib(jb.GE)(e),LT:e=>Ib(jb.LT)(e),LE:e=>Ib(jb.LE)(e),NE:Lb,EQ:e=>Ib(jb.EQ)(e),equals:e=>`${e.field}.equals(${Fb(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Fb(e)})`,contains:Rb,fieldContains:Rb,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Fb(e)})`,startsWith:e=>`${e.field}.startsWith(${Fb(e)})`,endsWith:e=>`${e.field}.endsWith(${Fb(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Fb(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Fb(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Fb(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Fb(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Fb(e)})`},Bb=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),Vb=e=>Array.isArray(e)?e:[e],Hb=`default`;var Ub=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,Mb.And()),this.Or=(e,t={})=>this.withExpression(e,t,Mb.Or()),this.Not=(e,t={})=>this.withExpression(e,t,Mb.Not())}withExpression(e,t={},n=Mb.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=Hb)=>{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 Mb;return t&&Ab.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Bb(t,i),Hb)}else o(e,Hb)}else typeof e==`string`?o(e,Hb):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 Mb&&n[t-1]instanceof Mb)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof Mb?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Wb=class{constructor(e){this.serialiser=zb.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 Gb=(e=`rapid`)=>T`<${e}-segmented-control :value="${mf(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>`,Kb=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Ub,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(Vb(i).map(e=>Vb(n).map(t=>new Wb().withField(t).withValue(e).withSerialiser(r).build())),{join:Mb.Or()}):t.And(new Wb().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],Kb.prototype,`criteriaOptions`,void 0),q([C],Kb.prototype,`prefix`,void 0),q([C],Kb.prototype,`value`,void 0),q([C],Kb.prototype,`selectedLabel`,void 0),Kb=q([$e({name:`criteria-segmented-control`,template:Gb(),styles:O``})],Kb);function qb(e,t){let n=new Ub;n.withExpression(new Wb().withField(e.labelField??e.valueField).withValue(t).withSerialiser(zb.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Jb(e,t){let n=new Ub;n.withExpression(new Wb().withField(e.valueField).withValue(t).withSerialiser(zb.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let Yb=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,Xb=e=>{let t=/* @__PURE__ */ new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))},Zb=Xb(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>`),Qb=Xb(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>`),$b=Xb(e=>T` ${t=>t.iconName?Zb(e):Qb(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>`),ex=Xb(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>`),tx=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(Ob(e))}</div>`;var nx=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}},rx=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 nx(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 $b(e);if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],ex(e)):$b(e)}};q([C],rx.prototype,`actions`,void 0),q([C],rx.prototype,`actionsResolver`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],rx.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],rx.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],rx.prototype,`autoCloseOnAction`,void 0),q([C],rx.prototype,`classNames`,void 0),q([C],rx.prototype,`definition`,void 0),q([D],rx.prototype,`name`,void 0),q([D({attribute:`icon-name`})],rx.prototype,`iconName`,void 0),q([D({attribute:`open`,mode:`boolean`})],rx.prototype,`open`,void 0),q([D],rx.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],rx.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],rx.prototype,`hideMenuSingleOption`,void 0),q([C],rx.prototype,`singleOption`,void 0),rx.compose({baseName:`actions-menu`,styles:qne,template:tx});let ix=()=>{};function ax(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:ix};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 ox=!1;try{typeof GENX_ENABLE_AI<`u`&&(ox=GENX_ENABLE_AI===`true`)}catch{}let sx=()=>ox||Sf(`ai`),cx=Ad(`foundation-ai`);function lx(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function ux(e,t){if(!lx())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 dx=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 fx=[`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`],px=[`claude-fable-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-4-5-20251001`],mx=[`gpt-6-astra`,`gpt-6.1-sol`,`gpt-6.1-terra`,`gpt-6-sol`,`gpt-6-luna`];function hx(e){return e===`image/jpg`?`image/jpeg`:e}function gx(e){return e.replace(/^data:[^,]*;base64,/,``)}let _x=.5;function vx(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=_x?r/_x*t:t+(r-_x)/.5*(n-t)}let yx=1e6,bx={"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 xx(e){return bx[e]}function Sx(e,t){let{promptPerMillion:n,candidatePerMillion:r}=xx(e),i=yx,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 Cx={"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 wx(e,t,n=/* @__PURE__ */ new Date){let r=Cx[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 Tx(e,t,n=/* @__PURE__ */ new Date){let{promptPerMillion:r,candidatePerMillion:i}=wx(e,t.promptTokens,n),a=yx,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 Ex={"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 Dx(e,t){let n=Ex[e];return t<=272e3?n:{promptPerMillion:n.promptPerMillion*2,cachedPerMillion:n.cachedPerMillion*2,candidatePerMillion:n.candidatePerMillion*1.5}}function Ox(e,t){let{promptPerMillion:n,cachedPerMillion:r,candidatePerMillion:i}=Dx(e,t.inputTokens),a=yx,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 kx=[`properties`,`patternProperties`,`$defs`,`definitions`],Ax=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],jx=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Mx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Nx(e){if(Array.isArray(e))return e.map(Nx);if(Mx(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Nx(r);return t}return e}function Px(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=kx.includes(i)&&Mx(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Mx(r)?t(r,`${e}/${n}`):Nx(r)])):Ax.includes(i)&&Array.isArray(a)?a.map((n,r)=>Mx(n)?t(n,`${e}/${r}`):Nx(n)):jx.includes(i)?Mx(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Mx(n)?t(n,`${e}/${r}`):Nx(n)):Nx(a):Nx(a)}return r}function Fx(e,t,n=``){return t(Px(e,(e,n)=>Fx(e,t,n),n),n)}let Ix=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Lx=[`oneOf`,`not`];function Rx(e){let t=[],n=[],r=[];return{schema:Fx(e,(e,i)=>{for(let n of Ix)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 Lx)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Mx(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function zx(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=Rx(e);return r.length&&cx.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&cx.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&&cx.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 Bx=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Vx(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Mx(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Mx(n)?n:void 0}function Hx(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=Vx(e,o);if(!t)break;let{$ref:n}=i,r=rd(i,[`$ref`]);i=Object.assign(Object.assign({},Nx(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),Px(i,t=>Hx(e,t,a,r),``)}function Ux(e){let t=[],n=Hx(e,e,/* @__PURE__ */ new Set,t);return t.length&&cx.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.`),Fx(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(Mx),n=t.filter(e=>e.type!==`null`);if(t.length===2&&n.length===1){let{anyOf:t}=e,r=rd(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 Bx)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}let Wx=[`allOf`,`not`,`if`,`then`,`else`,`oneOf`];function Gx(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=>Mx(e)&&e.type===`null`)?e:Object.assign(Object.assign({},e),{anyOf:[...e.anyOf,{type:`null`}]}):{anyOf:[e,{type:`null`}]}}function Kx(e){let t=[],n=[],r=[];return{schema:Fx(e,(e,i)=>{for(let t of Wx)t in e&&r.push(`${i}/${t}`);if(!(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Mx(e.properties)))return e;if(e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),Mx(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]=Mx(a[e])?Gx(a[e]):{type:`null`},t.push(`${i}/properties/${e}`));e.required=n}return e}),madeNullable:t,overridden:n,undroppable:r}}function qx(e,t){let{schema:n,madeNullable:r,overridden:i,undroppable:a}=Kx(e);return r.length&&cx.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&&cx.warn(`OpenAITransport: tool "${t}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}.`),a.length&&cx.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 Jx=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`,`openai`]),new Map(Object.entries(Jx).map(([e,t])=>[t.toLowerCase(),e]));var Yx=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 Xx=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,Zx=e=>{try{return JSON.parse(e)}catch{return}},Qx=e=>{let t=e?.code;return typeof t==`string`?t:void 0},$x=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,eS=e=>typeof e==`boolean`?e:void 0,tS=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function nS(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 Yx(e,$x(r.budgetUsd)??$x(i.budgetUsd),$x(r.spentUsd)??$x(i.spentUsd),a,{otherVendorAvailable:eS(r.otherVendorAvailable)??eS(i.otherVendorAvailable),serverVendor:tS(r.vendor)??tS(i.vendor)})}function rS(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 iS(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 aS=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`}),oS=new Set(Object.values(aS));function sS(e){return typeof e==`string`&&oS.has(e)?e:void 0}let cS=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),lS=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},uS=e=>e?.code!==void 0;function dS(e,t,n){if(e!==401&&e!==403||uS(t))return;let r=typeof n==`string`&&n.trim()===``;if(lS(t)||r)return e===401?cS.SIGNED_OUT:cS.ACCESS_DENIED}function fS(e,t){return e===413&&t===void 0}function Qae(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let pS=`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:pS,FALLBACKS_NOT_SUPPORTED:pS,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 $ae=e=>e!==aS.VENDOR_UNREACHABLE;var eoe=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 $ae(this.code)}};function mS(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let toe=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]),noe=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var hS=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 roe(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 gS(e,t,n){if(t===400)for(let e of roe(n)){if(!toe.some(t=>t.test(e)))continue;let t=noe.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function ioe(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 aoe=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 ooe=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),soe=Object.freeze([`authentication_error`,`permission_error`]);function _S(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 coe(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 vS(e){let t=_S(e);if(t?.type){if(soe.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function yS(e,t,n){if(t===`PROVIDER_REFUSED`)return coe(n)??vS(n)??`spend`;if(e!==`anthropic`)return;let r=vS(n);if(r)return r;let i=_S(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(ooe.some(t=>t.test(e)))return`spend`}}function bS(e,t,n,r,i){let a=_S(r);return new aoe(e,t,n,a?.type,a?.message??i)}function loe(e){return Object.entries(Jx).find(([,t])=>t===e)?.[0]}let xS=12e4,SS=1e3;function uoe(e){let t=(e?.get)?.call(e,`x-should-retry`);return typeof t==`string`&&t.trim().toLowerCase()===`false`}function doe(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*SS);let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function CS(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*SS}}}function foe(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 poe(e,t){return Math.max(0,e-t)}function wS(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=loe(o),p=(e,t,n)=>(cx.error(`${o}Transport: the AI service refused the request (${t} ${e})${n?`: ${n}`:``}`),new eoe(o,e,t,n)),m=0,h=(e,t)=>{let n=u*2**e,r=xS-m,i=foe(e,u,t,r);return m+=poe(i,n),t!=null&&i>n?cx.warn(`${o}Transport: honouring the server's requested retry delay (${Math.round(i)}ms, asked ${Math.round(t)}ms)`):t!=null&&t>n&&cx.warn(`${o}Transport: declining the server's requested retry delay (asked ${Math.round(t)}ms; the ${xS}ms sequence allowance is spent) — using the ladder's ${Math.round(i)}ms`),iS(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}=ax([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=Zx(t),r=yS(f,Qx(n),n);if(r)throw bS(o,r,c.status,n,t||void 0);let i=gS(f,c.status,n);if(i)throw new hS(o,i.promptTokens,i.limitTokens,i.message??(t||void 0));if(Xx(c.status,Qx(n)))throw nS(o,n,t||void 0);let a=sS(Qx(n));if(a&&a!==aS.VENDOR_UNREACHABLE)throw p(a,c.status,mS(n));let l=dS(c.status,n,t);if(l)throw p(l,c.status,Qae(n)??(t||void 0));if(fS(c.status,n))throw p(aS.REQUEST_TOO_LARGE,c.status,t||void 0);let u=uoe(c.headers);if(s.includes(c.status)&&!u&&e<5){cx.warn(`${o}Transport: retryable status ${c.status}, retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,doe(c.headers)||CS(n));continue}throw a?p(a,c.status,mS(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 ioe(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=yS(f,t.code,t);if(n)throw bS(o,n,t.status,t,t.error);let r=gS(f,t.status,t);if(r)throw new hS(o,r.promptTokens,r.limitTokens,r.message??t.error);if(Xx(t.status,t.code))throw nS(o,t);let i=sS(t.code);if(i&&i!==aS.VENDOR_UNREACHABLE)throw p(i,t.status,mS(t));if(s.includes(t.status)&&e<5){cx.warn(`${o}Transport: retryable status ${t.status} (err frame), retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,CS(t));continue}throw i?p(i,t.status,mS(t)):Error(`${o} request error ${t.status}: ${t.error??JSON.stringify(t.details)}`)}return yield c.json()}catch(e){throw rS(e,u.signal,d)}finally{clearTimeout(y),x()}}throw Error(`${o} request failed: max retries exceeded`)})}function moe(e){if(e&&e!==`auto`)return e===`required`?{type:`any`}:e===`none`?{type:`none`}:{type:`tool`,name:e.tool}}let hoe={"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},TS=`emit_structured_response`;function goe(e){if(!px.includes(e))throw Error(`AnthropicTransport: unsupported model "${e}". Use one of: ${px.join(`, `)}.`)}function _oe(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-opus-4-7`||e===`claude-sonnet-5`}function ES(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`||e===`claude-haiku-4-5-20251001`}function DS(e){return e!==`claude-haiku-4-5-20251001`}function OS(e){return e===`claude-fable-5`}function voe(e,t){let n=e===`claude-sonnet-5`||OS(e),r={type:`adaptive`,display:`summarized`};return t===`off`?OS(e)?r:n?{type:`disabled`}:void 0:t===`auto`||t!==void 0?DS(e)?r:void 0:n?r:void 0}function kS(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`}let yoe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function boe(e,t){if(t!==void 0&&t!==`auto`&&t!==`off`&&kS(e)&&DS(e))return yoe[t]}let AS=`anthropic`;var jS=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`}},MS=class e{warnIfThinkingUnclampable(e){if(this.warnedThinkingClamped)return;let t=this.clampWarning(e);t&&(this.warnedThinkingClamped=!0,cx.warn(t))}clampWarning(e){switch(e){case void 0:return;case`off`:return OS(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 DS(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!DS(this.model)||!kS(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`;goe(t),this.model=t,t===`claude-sonnet-5`?cx.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`?cx.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`?cx.warn(`AnthropicTransport: using ${t} — significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`):t===`claude-fable-5`&&cx.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:hoe[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&&ES(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:TS,description:`Emit the structured response that matches the required schema.`,input_schema:r}],a.tool_choice={type:`tool`,name:TS}),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===TS);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?zx(e.parameters,e.name):e.parameters},e.enforceSchema?{strict:!0}:{}))),a.tools?.length){let e=moe(n?.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingUnclampable(n?.thinkingPolicy);let o=voe(this.model,n?.thinkingPolicy);o&&(a.thinking=o);let s=boe(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&&!_oe(this.model)&&!c&&(a.temperature=vx(n.temperature,{defaultTemp:1,maxTemp:1})),n?.responseSchema&&ES(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}=Sx(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:hx(r.mimeType),data:gx(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:hx(e.mimeType),data:gx(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?.[AS];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:px.includes(t)?t:(this.warnedUnknownServingModels.has(t)||(this.warnedUnknownServingModels.add(t),cx.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),{[AS]:e})}if(e.stop_reason===`max_tokens`&&l.length>0)throw new jS(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 wS({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:Jx.anthropic,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};MS.TOKENS_PER_MILLION=1e6,MS.COST_DECIMAL_PLACES=6,MS.RATE_LIMIT_STATUS=429,MS.SERVICE_UNAVAILABLE_STATUS=503,MS.OVERLOADED_STATUS=529,MS.RETRYABLE_STATUSES=[MS.RATE_LIMIT_STATUS,MS.SERVICE_UNAVAILABLE_STATUS,MS.OVERLOADED_STATUS],MS.BACKOFF_BASE_MS=1e3;let NS=`default_api.`,xoe=/print\(\s*$/;var Soe=class{constructor(e){this.src=e,this.pos=0}parse(){let e=this.src.indexOf(NS);e===-1&&this.bail();let t=xoe.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(NS);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 Coe(e,t){if(!e)return null;let n;try{n=new Soe(e).parse()}catch{return null}return t.has(n.name)?n:null}let woe=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,Toe={"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 Eoe(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Doe(e){if(!fx.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${fx.join(`, `)}.`)}let Ooe={"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.`},PS=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],koe=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],Aoe=[`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],FS=[`minimal`,`low`,`medium`,`high`],IS={"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 LS(e,t){if(!e?.length||e.includes(t))return t;let n=FS.indexOf(t),r=e=>Math.abs(FS.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let RS={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},zS=e=>e!==void 0&&e!==`auto`&&e!==`off`;function joe(e,t){if(zS(t)){let n=IS[e];if(n)return{includeThoughts:!0,thinkingLevel:LS(n,RS[t])}}return t===`off`&&PS.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&PS.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let BS=`gemini`;function VS(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:hx(r.mimeType),data:gx(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var Moe=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},HS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!PS.includes(this.model)){this.warnedThinkingClamped=!0,cx.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(zS(e)){let t=IS[this.model];if(!t){this.warnedThinkingClamped=!0,cx.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=RS[e],r=LS(t,n);r!==n&&(this.warnedThinkingClamped=!0,cx.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`;Doe(t),this.model=t;let n=Ooe[t];n&&cx.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:Toe[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:Ux(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Eoe(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:joe(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&&koe.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=vx(n.temperature,{defaultTemp:1,maxTemp:2}));let l=new Set((n?.tools??[]).map(e=>e.name)),u=Aoe.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:Ux(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=Tx(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:hx(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?.[BS],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}=VS(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}=VS(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:{[BS]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=Coe(c.finishMessage,t);if(!e)throw new Moe(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 jS(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};cx.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:`${woe(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 wS({url:r,headers:a,body:i,credentials:o,vendorLabel:Jx.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}};HS.TOKENS_PER_MILLION=1e6,HS.COST_DECIMAL_PLACES=6,HS.RATE_LIMIT_STATUS=429,HS.SERVICE_UNAVAILABLE_STATUS=503,HS.BAD_GATEWAY_STATUS=502,HS.RETRYABLE_STATUSES=[HS.RATE_LIMIT_STATUS,HS.SERVICE_UNAVAILABLE_STATUS,HS.BAD_GATEWAY_STATUS],HS.BACKOFF_BASE_MS=1e3;let Noe={"gpt-6-astra":922e3,"gpt-6.1-sol":105e4,"gpt-6.1-terra":105e4,"gpt-6-sol":105e4,"gpt-6-luna":105e4},US=[`gpt-6.1-terra`,`gpt-6-luna`],Poe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Foe(e,t){if(t!==void 0&&t!==`auto`)return t===`off`?US.includes(e)?`none`:`low`:Poe[t]}function Ioe(e){if(e&&e!==`auto`)return e===`required`||e===`none`?e:{type:`function`,name:e.tool}}function Loe(e){let t=e.enforceSchema?qx(e.parameters,e.name):e.parameters;return{type:`function`,name:e.name,description:e.description,parameters:t,strict:!!e.enforceSchema}}function Roe(e){if(!mx.includes(e))throw Error(`OpenAITransport: unsupported model "${e}". Use one of: ${mx.join(`, `)}.`)}let zoe={"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.`},WS=`openai`,GS=Object.freeze({mode:`explicit`});function Boe(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:Goe(s.arguments)});return{reasoning:t,summaryParts:n,textParts:r,refusals:i,toolCalls:a,phase:o}}function KS(e){let t={type:`input_image`,image_url:`data:${hx(e.mimeType)};base64,${gx(e.data)}`};return e.detail&&(t.detail=e.detail===`medium`?`auto`:e.detail),t}function qS(e,t){let n=[];for(let e of t)e.kind===`image`&&n.push(KS(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 Voe(e){return e.providerMetadata?.[WS]??e.toolCalls?.[0]?.providerMetadata?.[WS]}function Hoe(e){let{status:t}=e;return rd(e,[`status`])}var JS=class e{constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=/* @__PURE__ */ new Set;let t=e.model??`gpt-6-luna`;Roe(t),this.model=t;let n=zoe[t];n&&cx.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:Noe[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=Woe(t?.tools);for(let t of e.toolCalls??[]){let e=n.get(t.name);e&&YS(t.args,e)}if(!t?.responseSchema||!e.content)return;let{madeNullable:r}=Kx(t.responseSchema);if(r.length)try{let t=JSON.parse(e.content);YS(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=GS),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(Loe);let e=Ioe(n.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingClamped(n?.thinkingPolicy);let o=Foe(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=vx(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:Kx(n.responseSchema).schema,strict:!0}}),a}warnIfThinkingClamped(e){e&&!this.warnedThinkingClamped.has(e)&&(e===`off`&&!US.includes(this.model)?(this.warnedThinkingClamped.add(e),cx.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),cx.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=qS(t.content,t.attachments??[]);e.length&&r.push({type:`message`,role:`user`,content:e});continue}let e=Voe(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(Hoe(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=qS(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(KS)]}}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:GS}),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}=Ox(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}=Boe(r),u={model:this.model};i.length&&(u.reasoning=i),l&&(u.phase=l);let d={[WS]:u};c.length&&(c[0].providerMetadata=d);let f=o.join(``),p=a.join(`
|
|
@@ -254,7 +254,7 @@ function dy(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r
|
|
|
254
254
|
✕
|
|
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>`)} `,nC=T` ${e=>Koe(Ob(e))} `,qoe={contains:zb.containsIgnoreCase,equals:zb.EQ,startsWith:zb.startsWith,endsWith:zb.endsWith,greaterThan:zb.GT,lessThan:zb.LT,greaterThanOrEqual:zb.GE,lessThanOrEqual:zb.LE,notEqual:zb.NE,dateIsToday:zb.dateIsToday,dateIsAfter:zb.dateIsGreaterEqual,dateIsGreaterEqual:zb.dateIsGreaterEqual,dateIsBefore:zb.dateIsLessEqual,dateIsLessEqual:zb.dateIsLessEqual,dateIsEqual:zb.dateIsEqual,dateTimeIsAfter:zb.dateTimeIsGreaterEqual,dateTimeIsGreaterEqual:zb.dateTimeIsGreaterEqual,dateTimeIsBefore:zb.dateTimeIsLessEqual,dateTimeIsLessEqual:zb.dateTimeIsLessEqual};function Joe(e){let t=qoe[e.operator];if(!t)throw Error(`Unknown criteria operator '${e.operator}'`);return new Wb().withField(e.field).withValue(e.value??null).withSerialiser(t).withGroup(`default`).build()}function Yoe(e,t){return e.length===1?e[0]:e.reduce((e,n,r)=>r===0?[n]:[...e,t,n],[])}function rC(e){let t=new Ub,n=!1;for(let r of e){if(!r.clauses?.length)continue;let e=r.clauses.map(Joe),i=r.logic===`or`?Mb.Or():Mb.And(),a=Yoe(e,i),o=e.length>1?{join:i}:{};r.negated?t.And([Mb.Not(),a]):t.And(e.length===1?e[0]:e,o),n=!0}return n?t.build():``}let Xoe=[`contains`,`equals`,`startsWith`,`notEqual`],iC=[`equals`,`greaterThan`,`lessThan`,`greaterThanOrEqual`,`lessThanOrEqual`,`notEqual`],aC=[`dateIsToday`,`dateIsAfter`,`dateIsBefore`,`dateIsEqual`,`dateIsGreaterEqual`,`dateIsLessEqual`],oC=[`dateTimeIsAfter`,`dateTimeIsBefore`,`dateTimeIsGreaterEqual`,`dateTimeIsLessEqual`],Zoe={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:`≤`},Qoe=/* @__PURE__ */ new Set([`DATE`,`LOCALDATE`]),$oe=/* @__PURE__ */ new Set([`DATETIME`,`NANO_TIMESTAMP`,`LOCALDATETIME`,`TIMESTAMP`]),sC=/* @__PURE__ */ new Set([`INT`,`INTEGER`,`LONG`,`SHORT`,`DOUBLE`,`BIGDECIMAL`,`DECIMAL`]);function cC(e){return(e||``).toUpperCase().trim().split(`(`)[0].trim()}function ese(e){let t=cC(e);return Qoe.has(t)?aC:$oe.has(t)?oC:sC.has(t)?iC:Xoe}function tse(e){return sC.has(cC(e))}function nse(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 rse(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e):typeof e==`string`&&!Number.isNaN(Number(e))}function ise(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(!ese(c).includes(a)){r.push({field:e,operator:a,value:o,message:`Operator '${a}' is not allowed for field type ${c}`});continue}if((aC.includes(a)||oC.includes(a))&&a!==`dateIsToday`&&!nse(o)){r.push({field:e,operator:a,value:o,message:`Invalid date/datetime value; use yyyyMMdd, yyyy-MM-dd, or epoch`});continue}if(tse(c)&&iC.includes(a)&&!rse(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 ase(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}=ise(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 lC=Ad(`foundation-notifications`),uC=null,dC=/* @__PURE__ */ new Map,fC=e=>`${e?.title??`Error`}: ${e?.body??`Something went wrong`}`,ose=e=>e?.logLevel||e?.config?.logLevel||vd.debug,pC=e=>{lC.log({message:fC(e),level:ose(e)})},mC=(e,t)=>{let n=document.querySelector(`#${e}`);if(!n){if(dC.has(e))n=dC.get(e);else{let t=Hd(document).find(t=>t.id===e);t&&(n=t,dC.set(e,t))}}if(!n){n=document.createElement(`div`),n.setAttribute(`id`,e),n.style.zIndex=`9999`;let{element:t,prefix:r}=Gd(document.body,`rapid`);if(t)t.appendChild(n),uC=t;else if(uC)uC.appendChild(n);else{let e=document.createElement(`${r}-design-system-provider`);e.appendChild(n),document.body.appendChild(e),uC=e}}return n},sse=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 cse()},cse=()=>{let e=document.createElement(`div`);return e.setAttribute(`id`,`banner-anchor`),e.style.position=`relative`,document.body.insertBefore(e,document.body.firstChild),e},lse=e=>{pC(e),alert(fC(e))},use=(e,t,n)=>{pC(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-banner`),a=sse(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},dse=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},fse=(e,t,n)=>{pC(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-dialog`);(n?dse(n):mC(`dialog-container`,t)).appendChild(i),i.notification=e,i.show()};var hC;(function(e){e.NOTIFICATION_EVENT=`notification-event`})(hC||(hC={}));var gC;(function(e){e.Top=`top`,e.Bottom=`bottom`})(gC||(gC={}));var _C;(function(e){e.Left=`left`,e.Right=`right`})(_C||(_C={}));let vC=`12px`,pse=(e,t,n)=>{e.style.position=`fixed`,e.style.top=t===gC.Top?vC:``,e.style.bottom=t===gC.Bottom?vC:``,e.style.left=n===_C.Left?vC:``,e.style.right=n===_C.Right?vC:``},mse=(e,t)=>{pC(e);let n=t.split(`-`)[0],r=document.createElement(`${n}-snackbar`),i=e.config?.snackbar?.verticalEdge??gC.Bottom,a=e.config?.snackbar?.horizontalEdge??_C.Left,o=mC(`snack-container-${i}-${a}`,t);o&&pse(o,i,a),o.appendChild(r),r.notification=e},hse=e=>Hd(document.body).find(t=>t.tagName.toLowerCase()===`notify-container`&&t.position===e);function gse(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 yC=(e,t,n)=>{var r,i;pC(e);let a=t.split(`-`)[0],o=e?.config?.toast?.position||`top-right`,s=n??hse(o)??mC(`notify-container`,t);s&&s.tagName.toLowerCase()!==`notify-container`&&gse(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)},bC=(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)),yC(r,t,n)},_se=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}`,vse=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>`,yse=T` ${A(e=>e.allowCloseAll||e.allowManualCollapse,T` ${e=>vse(e.designSystemPrefix)} `)}<div class="toast-container"><slot ${bt(`slottedNodes`)}@click="${e=>e.handleContainerClick()}"></slot></div>`,xC=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(Kf.shared.pathName)},this.slottedNodes=[]}connectedCallback(){super.connectedCallback(),(this.position===`bottom-left`||this.position===`bottom-right`)&&lC.error(`NotifyContainer doesn't currently support bottom corner placements`),S.getNotifier(Kf.shared).subscribe(this.routeSubscriber,`pathName`),this.checkRoute(Kf.shared.pathName),this.mutationObserver=new MutationObserver(e=>this.handleMutation(e)),this.mutationObserver.observe(this,{childList:!0})}disconnectedCallback(){var e;super.disconnectedCallback(),S.getNotifier(Kf.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],xC.prototype,`position`,void 0),q([D({attribute:`stack-threshold`})],xC.prototype,`stackThreshold`,void 0),q([D({attribute:`allow-manual-collapse`,mode:`boolean`})],xC.prototype,`allowManualCollapse`,void 0),q([D({attribute:`allow-close-all`,mode:`boolean`})],xC.prototype,`allowCloseAll`,void 0),q([D({attribute:`design-system-prefix`})],xC.prototype,`designSystemPrefix`,void 0),q([D({attribute:`show-count`,mode:`boolean`})],xC.prototype,`showCount`,void 0),q([D({attribute:`stack-collapsed`,mode:`boolean`})],xC.prototype,`stackCollapsed`,void 0),q([D({attribute:`notification-interval`})],xC.prototype,`notificationInterval`,void 0),q([C],xC.prototype,`sortFn`,void 0),q([C],xC.prototype,`slottedNodes`,void 0),xC=q([$e({name:`notify-container`,template:yse,styles:_se})],xC);let SC={alert:lse,toast:yC,dialog:fse,snackbar:mse,banner:use},CC=(e,t,n)=>{Object.keys(e?.config||{}).forEach(r=>{SC[r]&&SC[r](e,t,n)})};function bse(e){return e.length===0?``:e.length===1?e[0].message:e.map(e=>e.message).join(`; `)}function wC(e,t,n){t?.trim()&&CC({title:e,body:t,config:{toast:{autoClose:!0,closeTimeout:4e3,type:`error`}}},n)}var TC=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 lx()}get criteriaChips(){return this.activeGroups.flatMap((e,t)=>e.clauses.map((e,n)=>({groupIndex:t,clauseIndex:n,fieldLabel:this.getFieldLabel(e.field),operatorLabel:Zoe[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=rC(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){wC(`AI criteria search`,`AI provider not configured`,Ob(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)){wC(`AI criteria search`,`AI could not interpret the criteria`,Ob(this)),this.isInterpreting=!1;return}let{valid:i,invalid:a}=ase(r.groups,this.fieldMetadata);if(a.length>0&&(wC(`Criteria validation error`,bse(a),Ob(this)),this.$emit(`validation-errors`,a)),i.length>0){let e=[...this.activeGroups,...i],t=rC(e);this.lastValidCriteria=t,this.activeGroups=e,this.inputValue=``,this.showingChips=!0,this.$emit(`criteria-changed`,t)}}catch(e){wC(`AI criteria search`,e instanceof Error?e.message:`Interpretation failed`,Ob(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=ux((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([QS],TC.prototype,`providerRegistry`,void 0),q([D],TC.prototype,`placeholder`,void 0),q([D({mode:`boolean`})],TC.prototype,`disabled`,void 0),q([C],TC.prototype,`inputValue`,void 0),q([C],TC.prototype,`isInterpreting`,void 0),q([C],TC.prototype,`lastValidCriteria`,void 0),q([C],TC.prototype,`activeGroups`,void 0),q([C],TC.prototype,`showingChips`,void 0),q([C],TC.prototype,`fieldMetadata`,void 0),q([C],TC.prototype,`isRecording`,void 0),q([w],TC.prototype,`speechAvailable`,null),q([w],TC.prototype,`criteriaChips`,null);let EC={};TC.compose(Object.assign({baseName:`ai-criteria-search`,template:nC,styles:tC,shadowOptions:void 0},EC));let DC=(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%}`,xse=e=>T` ${A(()=>sx(),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>`)} `,OC=T` ${e=>xse(Ob(e))} `;var kC=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){Eb(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([QS],kC.prototype,`providerRegistry`,void 0),q([C],kC.prototype,`status`,void 0),q([C],kC.prototype,`open`,void 0),q([C],kC.prototype,`state`,void 0),q([C],kC.prototype,`isInstalling`,void 0),q([w],kC.prototype,`chromeStatusLabel`,null),q([w],kC.prototype,`canInstall`,null),q([w],kC.prototype,`isDownloading`,null),kC.compose({baseName:`ai-indicator`,template:OC,styles:DC});let AC=(e,t)=>Hn(e,t),jC=(e,t)=>O` ${Il(e,t)}`;var MC=class extends Ll{};let NC={delegatesFocus:!0,mode:`open`},PC={};MC.compose(Object.assign({baseName:`anchor`,template:AC,styles:jC,shadowOptions:NC},PC));let FC=(e,t)=>Kn(e,t),IC=(e,t)=>O` ${Rl(e,t)}`;var LC=class extends Jn{};let RC={delegatesFocus:!0,mode:`open`},zC={};LC.compose(Object.assign({baseName:`anchored-region`,template:FC,styles:IC,shadowOptions:RC},zC));let BC=(e,t)=>tr(e,t),Sse=T` ${A(e=>e.imgSrc,T`<img src="${e=>e.imgSrc}" alt="${e=>e.alt}" slot="media" class="media" part="media" />`)} `,VC=(e,t)=>O` ${zl(e,t)}`;var HC=class extends Bl{};let UC={delegatesFocus:!0,mode:`open`},WC={media:Sse};HC.compose(Object.assign({baseName:`avatar`,template:BC,styles:VC,shadowOptions:UC},WC));let GC=(e,t)=>rr(e,t),KC=(e,t)=>O` ${Vl(e,t)}`;var qC=class extends ir{};let JC={};qC.compose(Object.assign({baseName:`badge`,template:GC,styles:KC,shadowOptions:void 0},JC));let YC=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}`,Cse=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>`,XC=T` ${e=>Cse(Ob(e))} `,ZC={mode:`open`,delegatesFocus:!0};var QC=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){wb.error(e)}})}};q([C],QC.prototype,`dismissAnimation`,void 0),q([C],QC.prototype,`notification`,void 0),QC.compose({baseName:`banner`,styles:YC,template:XC,shadowOptions:ZC});let $C=(e,t)=>sr(e,t),ew=(e,t)=>O` ${Ul(e,t)}`;var tw=class extends cr{};tw.compose(Object.assign({baseName:`breadcrumb`,template:$C,styles:ew,shadowOptions:void 0},{}));let nw=(e,t)=>ar(e,t),rw=(e,t)=>O` ${Hl(e,t)}`;var iw=class extends or{};let aw={separator:`/`};iw.compose(Object.assign({baseName:`breadcrumb-item`,template:nw,styles:rw,shadowOptions:void 0},aw));let ow=(e,t)=>lr(e,t),sw=(e,t)=>O` ${Wl(e,t)}`;var cw=class extends Gl{};let lw={delegatesFocus:!0,mode:`open`},uw={};cw.compose(Object.assign({baseName:`button`,template:ow,styles:sw,shadowOptions:lw},uw));let dw=()=>O` ${Kl}`,fw=(e,t)=>jr(e,t);var pw=class extends xr{};let mw={delegatesFocus:!0,mode:`open`},hw={};pw.compose(Object.assign({baseName:`calendar`,template:fw,styles:dw,shadowOptions:mw},hw));let gw=(e,t)=>Mr(e,t),_w=(e,t)=>O` ${ql(e,t)} :host{background-color: var(--fui-card-fill-color);color: var(--fui-card-foreground-color)}`;var vw=class extends Jl{};let yw={};vw.compose(Object.assign({baseName:`card`,template:gw,styles:_w,shadowOptions:void 0},yw));var bw;(function(e){e.BELOW=`below`,e.ABOVE=`above`})(bw||(bw={}));var xw=/* @__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 Sw=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 Cw;let ww=Cw=class extends Tb{constructor(){super(...arguments),this.emptyDataLabel=`No matching records`,this.allowCustomOptions=!1,this.infiniteScroll=!1,this.pageSize=Cw.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 $l?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??`${Ob(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:Cw.defaultPageSize,this.select.addEventListener(`open-change`,this.selectOpenChangeHandler),yield this.applyInfiniteScrollFetchMode(),!this.isConnected)return;x.queueUpdate(()=>this.attachListboxScrollListener())}this.fetchData(),this.valueField||wb.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!==sg.DATASERVER}catch(e){wb.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){wb.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-Cw.scrollLoadThresholdPx}loadNextPage(){return J(this,void 0,void 0,function*(){if(this.loadingMoreRows||!this.canRequestMoreRows())return;this.loadingMoreRows=!0;let e=this.datasource.resourceType===sg.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 $l&&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}Jb(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 Cw||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 $l&&!this.select.async&&e){this.resetCombobox();let e=this.getInitialLabel();x.queueUpdate(()=>{this.select.value=String(e),e&&this.select instanceof $l&&this.select.async&&this.selectChangeHandler({target:{value:e}})}),this.initalSelectedValueInitialized=!0}}else if(this.allowCustomOptions&&this.initialSelectedValue&&(!this.initalSelectedValueInitialized||this.select instanceof $l&&!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 $l?String(t?t.label:e):t?String(t.label):``}resetCombobox(){this.select&&this.select instanceof $l&&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){wb.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){wb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){wb.debug(`handleStreamUpdates - Method not implemented.`)}};ww.defaultPageSize=20,ww.scrollLoadThresholdPx=32,q([$y],ww.prototype,`resources`,void 0),q([D({attribute:`label-field`})],ww.prototype,`labelField`,void 0),q([D({attribute:`option-element`})],ww.prototype,`optionElement`,void 0),q([D({attribute:`value-field`})],ww.prototype,`valueField`,void 0),q([D({attribute:`empty-data-label`})],ww.prototype,`emptyDataLabel`,void 0),q([D({mode:`boolean`,attribute:`allow-custom-options`})],ww.prototype,`allowCustomOptions`,void 0),q([D({mode:`boolean`,attribute:`infinite-scroll`})],ww.prototype,`infiniteScroll`,void 0),q([D({attribute:`page-size`,converter:E})],ww.prototype,`pageSize`,void 0),q([C],ww.prototype,`labelFormatter`,void 0),q([C],ww.prototype,`labelRowFormatter`,void 0),q([C],ww.prototype,`initialSelectedValue`,void 0),ww=Cw=q([$e({name:`options-datasource`})],ww);let Tw=class extends Tb{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||wb.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){wb.debug(`handleStreamInserts - Method not implemented.`)}handleStreamDeletes(e){wb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){wb.debug(`handleStreamUpdates - Method not implemented.`)}};q([D({attribute:`value-field`})],Tw.prototype,`valueField`,void 0),q([D({attribute:`label-field`})],Tw.prototype,`labelField`,void 0),Tw=q([$e({name:`multiselect-datasource`})],Tw);let Ew=(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=${mf(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 "${e=>e.filterSearchValue}"</${e}-button>`)}</section></div><slot ${bt({property:`slottedDatasource`,filter:e=>e instanceof Tw})}></slot>`,wse=T` ${Ew()} `,Dw={};var Ow=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=bw.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,xw.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===bw.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?bw.ABOVE:bw.BELOW}this.multiselectDropdown.classList.toggle(`position-above`,e===bw.ABOVE),this.multiselectDropdown.classList.toggle(`position-below`,e===bw.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?qb(this.slottedDatasource[0],this.filterSearchValue):(this.loading=!1,wb.warn(`Multiselect-datasource is not connected. Please add a datasource to use this functionality.`))}changeHandler(e){e.preventDefault(),e.stopImmediatePropagation()}handleClickOutside(e){Eb(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],Ow.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],Ow.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],Ow.prototype,`all`,void 0),q([D({mode:`boolean`})],Ow.prototype,`allSelected`,void 0),q([D({mode:`boolean`})],Ow.prototype,`search`,void 0),q([D({mode:`boolean`})],Ow.prototype,`disabled`,void 0),q([D({mode:`boolean`})],Ow.prototype,`creatable`,void 0),q([D({mode:`boolean`})],Ow.prototype,`async`,void 0),q([D],Ow.prototype,`debounce`,void 0),q([D({mode:`boolean`})],Ow.prototype,`resizable`,void 0),q([D],Ow.prototype,`tabindex`,void 0),q([D({mode:`boolean`,attribute:`filter-by-contains`})],Ow.prototype,`filterByContains`,void 0),q([C],Ow.prototype,`defaultSlottedNodes`,void 0),q([C],Ow.prototype,`slottedDatasource`,void 0),q([C],Ow.prototype,`valueFormatter`,void 0),q([C],Ow.prototype,`loading`,void 0),q([C],Ow.prototype,`filterSearchValue`,void 0),q([C],Ow.prototype,`open`,void 0),q([C],Ow.prototype,`options`,void 0),q([C],Ow.prototype,`selectedOptions`,void 0),q([C],Ow.prototype,`filteredAvailableOptions`,void 0),q([C],Ow.prototype,`scrollContainer`,void 0),q([D],Ow.prototype,`position`,void 0),q([C],Ow.prototype,`onAllSelectedCallback`,void 0),q([C],Ow.prototype,`itemRenderer`,void 0),q([w],Ow.prototype,`getDisplayValue`,null),q([w],Ow.prototype,`getPlaceholder`,null),q([w],Ow.prototype,`isAllOptionsDisabled`,null),q([w],Ow.prototype,`areAllOptionsSelected`,null),q([w],Ow.prototype,`showCreatable`,null),q([C],Ow.prototype,`optionsHeaderSlottedNodes`,void 0),Ow.compose(Object.assign({baseName:`multiselect`,template:wse,styles:Sw,shadowOptions:void 0},Dw));let kw=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}`,Aw=(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=${mf(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>`,Tse=T` ${Aw()} `,jw={};var Mw=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=bw.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===bw.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?bw.BELOW:bw.ABOVE}else{let t=this.getBoundingClientRect(),n=window.innerHeight,r=t.top,i=n-t.bottom;e=i<t.height&&r>i?bw.ABOVE:bw.BELOW}}e===bw.ABOVE?(this.optionsElement.classList.add(`position-above`),this.optionsElement.classList.remove(`position-below`)):e===bw.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){Eb(e,this)&&(this.open=!1)}};q([D],Mw.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],Mw.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],Mw.prototype,`search`,void 0),q([D({mode:`boolean`})],Mw.prototype,`disabled`,void 0),q([C],Mw.prototype,`defaultSlottedNodes`,void 0),q([C],Mw.prototype,`valueFormatter`,void 0),q([C],Mw.prototype,`filterSearchValue`,void 0),q([C],Mw.prototype,`open`,void 0),q([C],Mw.prototype,`options`,void 0),q([C],Mw.prototype,`selectedOptions`,void 0),q([C],Mw.prototype,`filteredAvailableOptions`,void 0),q([C],Mw.prototype,`position`,void 0),q([w],Mw.prototype,`getPlaceholder`,null),Mw.compose(Object.assign({baseName:`categorized-multiselect`,template:Tse,styles:kw,shadowOptions:void 0},jw));let Nw=(e,t)=>Pr(e,t),Pw=(e,t)=>O` ${Yl(e,t)}`;var Fw=class extends Fr{};let Iw={checkedIndicator:`
|
|
257
|
+
Install model </${e}-button>`)}</div>`)}</div>`)} `,OC=T` ${e=>xse(Ob(e))} `;var kC=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){Eb(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([QS],kC.prototype,`providerRegistry`,void 0),q([C],kC.prototype,`status`,void 0),q([C],kC.prototype,`open`,void 0),q([C],kC.prototype,`state`,void 0),q([C],kC.prototype,`isInstalling`,void 0),q([w],kC.prototype,`chromeStatusLabel`,null),q([w],kC.prototype,`canInstall`,null),q([w],kC.prototype,`isDownloading`,null),kC.compose({baseName:`ai-indicator`,template:OC,styles:DC});let AC=(e,t)=>Hn(e,t),jC=(e,t)=>O` ${Il(e,t)}`;var MC=class extends Ll{};let NC={delegatesFocus:!0,mode:`open`},PC={};MC.compose(Object.assign({baseName:`anchor`,template:AC,styles:jC,shadowOptions:NC},PC));let FC=(e,t)=>Kn(e,t),IC=(e,t)=>O` ${Rl(e,t)}`;var LC=class extends Jn{};let RC={delegatesFocus:!0,mode:`open`},zC={};LC.compose(Object.assign({baseName:`anchored-region`,template:FC,styles:IC,shadowOptions:RC},zC));let BC=(e,t)=>tr(e,t),Sse=T` ${A(e=>e.imgSrc,T`<img src="${e=>e.imgSrc}" alt="${e=>e.alt}" slot="media" class="media" part="media" />`)} `,VC=(e,t)=>O` ${zl(e,t)}`;var HC=class extends Bl{};let UC={delegatesFocus:!0,mode:`open`},WC={media:Sse};HC.compose(Object.assign({baseName:`avatar`,template:BC,styles:VC,shadowOptions:UC},WC));let GC=(e,t)=>rr(e,t),KC=(e,t)=>O` ${Vl(e,t)}`;var qC=class extends ir{};let JC={};qC.compose(Object.assign({baseName:`badge`,template:GC,styles:KC,shadowOptions:void 0},JC));let YC=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}`,Cse=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>`,XC=T` ${e=>Cse(Ob(e))} `,ZC={mode:`open`,delegatesFocus:!0};var QC=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){wb.error(e)}})}};q([C],QC.prototype,`dismissAnimation`,void 0),q([C],QC.prototype,`notification`,void 0),QC.compose({baseName:`banner`,styles:YC,template:XC,shadowOptions:ZC});let $C=(e,t)=>sr(e,t),ew=(e,t)=>O` ${Ul(e,t)}`;var tw=class extends cr{};tw.compose(Object.assign({baseName:`breadcrumb`,template:$C,styles:ew,shadowOptions:void 0},{}));let nw=(e,t)=>ar(e,t),rw=(e,t)=>O` ${Hl(e,t)}`;var iw=class extends or{};let aw={separator:`/`};iw.compose(Object.assign({baseName:`breadcrumb-item`,template:nw,styles:rw,shadowOptions:void 0},aw));let ow=(e,t)=>lr(e,t),sw=(e,t)=>O` ${Wl(e,t)}`;var cw=class extends Gl{};let lw={delegatesFocus:!0,mode:`open`},uw={};cw.compose(Object.assign({baseName:`button`,template:ow,styles:sw,shadowOptions:lw},uw));let dw=()=>O` ${Kl}`,fw=(e,t)=>jr(e,t);var pw=class extends xr{};let mw={delegatesFocus:!0,mode:`open`},hw={};pw.compose(Object.assign({baseName:`calendar`,template:fw,styles:dw,shadowOptions:mw},hw));let gw=(e,t)=>Mr(e,t),_w=(e,t)=>O` ${ql(e,t)} :host{background-color: var(--fui-card-fill-color);color: var(--fui-card-foreground-color)}`;var vw=class extends Jl{};let yw={};vw.compose(Object.assign({baseName:`card`,template:gw,styles:_w,shadowOptions:void 0},yw));var bw;(function(e){e.BELOW=`below`,e.ABOVE=`above`})(bw||(bw={}));var xw=/* @__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 Sw=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 Cw;let ww=Cw=class extends Tb{constructor(){super(...arguments),this.emptyDataLabel=`No matching records`,this.allowCustomOptions=!1,this.infiniteScroll=!1,this.pageSize=Cw.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 $l?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??`${Ob(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:Cw.defaultPageSize,this.select.addEventListener(`open-change`,this.selectOpenChangeHandler),yield this.applyInfiniteScrollFetchMode(),!this.isConnected)return;x.queueUpdate(()=>this.attachListboxScrollListener())}this.fetchData(),this.valueField||wb.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!==sg.DATASERVER}catch(e){wb.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){wb.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-Cw.scrollLoadThresholdPx}loadNextPage(){return J(this,void 0,void 0,function*(){if(this.loadingMoreRows||!this.canRequestMoreRows())return;this.loadingMoreRows=!0;let e=this.datasource.resourceType===sg.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 $l&&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}Jb(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 Cw||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 $l&&!this.select.async&&e){this.resetCombobox();let e=this.getInitialLabel();x.queueUpdate(()=>{this.select.value=String(e),e&&this.select instanceof $l&&this.select.async&&this.selectChangeHandler({target:{value:e}})}),this.initalSelectedValueInitialized=!0}}else if(this.allowCustomOptions&&this.initialSelectedValue&&(!this.initalSelectedValueInitialized||this.select instanceof $l&&!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 $l?String(t?t.label:e):t?String(t.label):``}resetCombobox(){this.select&&this.select instanceof $l&&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){wb.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){wb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){wb.debug(`handleStreamUpdates - Method not implemented.`)}};ww.defaultPageSize=20,ww.scrollLoadThresholdPx=32,q([$y],ww.prototype,`resources`,void 0),q([D({attribute:`label-field`})],ww.prototype,`labelField`,void 0),q([D({attribute:`option-element`})],ww.prototype,`optionElement`,void 0),q([D({attribute:`value-field`})],ww.prototype,`valueField`,void 0),q([D({attribute:`empty-data-label`})],ww.prototype,`emptyDataLabel`,void 0),q([D({mode:`boolean`,attribute:`allow-custom-options`})],ww.prototype,`allowCustomOptions`,void 0),q([D({mode:`boolean`,attribute:`infinite-scroll`})],ww.prototype,`infiniteScroll`,void 0),q([D({attribute:`page-size`,converter:E})],ww.prototype,`pageSize`,void 0),q([C],ww.prototype,`labelFormatter`,void 0),q([C],ww.prototype,`labelRowFormatter`,void 0),q([C],ww.prototype,`initialSelectedValue`,void 0),ww=Cw=q([$e({name:`options-datasource`})],ww);let Tw=class extends Tb{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||wb.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){wb.debug(`handleStreamInserts - Method not implemented.`)}handleStreamDeletes(e){wb.debug(`handleStreamDeletes - Method not implemented.`)}handleStreamUpdates(e){wb.debug(`handleStreamUpdates - Method not implemented.`)}};q([D({attribute:`value-field`})],Tw.prototype,`valueField`,void 0),q([D({attribute:`label-field`})],Tw.prototype,`labelField`,void 0),Tw=q([$e({name:`multiselect-datasource`})],Tw);let Ew=(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=${mf(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 "${e=>e.filterSearchValue}"</${e}-button>`)}</section></div><slot ${bt({property:`slottedDatasource`,filter:e=>e instanceof Tw})}></slot>`,wse=T` ${Ew()} `,Dw={};var Ow=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=bw.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,xw.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===bw.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?bw.ABOVE:bw.BELOW}this.multiselectDropdown.classList.toggle(`position-above`,e===bw.ABOVE),this.multiselectDropdown.classList.toggle(`position-below`,e===bw.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?qb(this.slottedDatasource[0],this.filterSearchValue):(this.loading=!1,wb.warn(`Multiselect-datasource is not connected. Please add a datasource to use this functionality.`))}changeHandler(e){e.preventDefault(),e.stopImmediatePropagation()}handleClickOutside(e){Eb(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],Ow.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],Ow.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],Ow.prototype,`all`,void 0),q([D({mode:`boolean`})],Ow.prototype,`allSelected`,void 0),q([D({mode:`boolean`})],Ow.prototype,`search`,void 0),q([D({mode:`boolean`})],Ow.prototype,`disabled`,void 0),q([D({mode:`boolean`})],Ow.prototype,`creatable`,void 0),q([D({mode:`boolean`})],Ow.prototype,`async`,void 0),q([D],Ow.prototype,`debounce`,void 0),q([D({mode:`boolean`})],Ow.prototype,`resizable`,void 0),q([D],Ow.prototype,`tabindex`,void 0),q([D({mode:`boolean`,attribute:`filter-by-contains`})],Ow.prototype,`filterByContains`,void 0),q([C],Ow.prototype,`defaultSlottedNodes`,void 0),q([C],Ow.prototype,`slottedDatasource`,void 0),q([C],Ow.prototype,`valueFormatter`,void 0),q([C],Ow.prototype,`loading`,void 0),q([C],Ow.prototype,`filterSearchValue`,void 0),q([C],Ow.prototype,`open`,void 0),q([C],Ow.prototype,`options`,void 0),q([C],Ow.prototype,`selectedOptions`,void 0),q([C],Ow.prototype,`filteredAvailableOptions`,void 0),q([C],Ow.prototype,`scrollContainer`,void 0),q([D],Ow.prototype,`position`,void 0),q([C],Ow.prototype,`onAllSelectedCallback`,void 0),q([C],Ow.prototype,`itemRenderer`,void 0),q([w],Ow.prototype,`getDisplayValue`,null),q([w],Ow.prototype,`getPlaceholder`,null),q([w],Ow.prototype,`isAllOptionsDisabled`,null),q([w],Ow.prototype,`areAllOptionsSelected`,null),q([w],Ow.prototype,`showCreatable`,null),q([C],Ow.prototype,`optionsHeaderSlottedNodes`,void 0),Ow.compose(Object.assign({baseName:`multiselect`,template:wse,styles:Sw,shadowOptions:void 0},Dw));let kw=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}`,Aw=(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=${mf(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>`,Tse=T` ${Aw()} `,jw={};var Mw=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=bw.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===bw.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?bw.BELOW:bw.ABOVE}else{let t=this.getBoundingClientRect(),n=window.innerHeight,r=t.top,i=n-t.bottom;e=i<t.height&&r>i?bw.ABOVE:bw.BELOW}}e===bw.ABOVE?(this.optionsElement.classList.add(`position-above`),this.optionsElement.classList.remove(`position-below`)):e===bw.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){Eb(e,this)&&(this.open=!1)}};q([D],Mw.prototype,`name`,void 0),q([D({mode:`boolean`,attribute:`auto-position`})],Mw.prototype,`autoPosition`,void 0),q([D({mode:`boolean`})],Mw.prototype,`search`,void 0),q([D({mode:`boolean`})],Mw.prototype,`disabled`,void 0),q([C],Mw.prototype,`defaultSlottedNodes`,void 0),q([C],Mw.prototype,`valueFormatter`,void 0),q([C],Mw.prototype,`filterSearchValue`,void 0),q([C],Mw.prototype,`open`,void 0),q([C],Mw.prototype,`options`,void 0),q([C],Mw.prototype,`selectedOptions`,void 0),q([C],Mw.prototype,`filteredAvailableOptions`,void 0),q([C],Mw.prototype,`position`,void 0),q([w],Mw.prototype,`getPlaceholder`,null),Mw.compose(Object.assign({baseName:`categorized-multiselect`,template:Tse,styles:kw,shadowOptions:void 0},jw));let Nw=(e,t)=>Pr(e,t),Pw=(e,t)=>O` ${Yl(e,t)}`;var Fw=class extends Fr{};let Iw={checkedIndicator:`
|
|
258
258
|
<svg
|
|
259
259
|
aria-hidden="true"
|
|
260
260
|
part="checked-indicator"
|