@genesislcap/foundation-rapid-cdn 15.105.0 → 15.107.0

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 ty(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 ny={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 ry(e,t){function n(n,r,i){if(typeof document<`u`){i=ty({},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,``,ty({},t,{expires:-1}))},withAttributes:function(e){return ry(this.converter,ty({},this.attributes,e))},withConverter:function(e){return ry(ty({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var iy=ry(ny,{path:`/`});let ay=N.createInterface();function oy(){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 sy(e=``,t=`:`,n){return e.split(t,n).map(e=>e.trim()).filter(e=>e!==``)}function cy(e,t=`:`){let n=typeof e==`string`&&e.trim();return n?n.includes(t):!1}function ly(e,t=`:`){return typeof e==`string`&&e.trim()?(e.match(new RegExp(t,`g`))||[]).length:0}function uy(e,t=`:`){for(let n of e)if(cy(n,t))return n;return e.find(e=>typeof e==`string`&&e.trim()!==``)}function dy(e,t,n){let r=typeof e==`string`&&e.trim();return!r||n&&!r.includes(n)||ly(r)>1?n&&t&&n!==t?`${t}:${n}`:t||n:r}function fy(e=`credential`){Y.warn(`Unable to migrate legacy ${e} to latest format. Please remove from your browser.`)}let py={password:!0,mediation:`optional`},my={cookie:{path:`/`,name:`credentials`,expires:7300,storePasswords:!1}},hy=class{constructor(e,t=my){this.session=e,this.config=t}createBasicCredentials(e){return{type:Og.BASIC,username:e.username,password:e.password,mfaToken:this.getMFAToken()}}createRefreshCredentials(e){return{type:Og.REFRESH,username:e?.username??this.getUsername(),refreshToken:e?.refreshToken??this.getRefreshToken(),mfaToken:e?.mfaToken??this.getMFAToken()}}createSSOCredentials(e){return{type:Og.SSO,ssoToken:e?.ssoToken??this.getSSOToken()}}validateBasicCredentials(e){return e&&!!e.username&&!!e.password}validateRefreshCredentials(e){return e&&!!e.refreshToken&&!!e.username}validateSSOCredentials(e){return e&&!!e.ssoToken}validateUserCredentialData(e,t){let n=e&&!!e.id&&!!e.name&&!e.name.includes(`:`)&&ly(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]=sy(t.name||t.id),[r,i]=sy(uy([t.id,t.name]));return[{id:dy(t.id||t.name,n,i),name:n,password:t.password||``},!0]}catch{fy(`PasswordCredential`)}if(t)try{let e=t,[n]=sy(e.name||e.username||e.organisation),[r,i]=sy(uy([e.organisation||e.username||e.name]));return[{id:dy(e.id||e.username||e.name,n,i),name:n,password:e.password||``},!1]}catch{fy(`cookie`)}return[void 0,!1]}storeCredentialsInContainer(e){return J(this,void 0,void 0,function*(){if(!oy())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=py){if(oy())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`),!!iy.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=iy.get(this.config.cookie.name);return e?JSON.parse(e):void 0}storeCredentials(e){return J(this,void 0,void 0,function*(){if(oy()){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 oy()?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(){iy.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 oy()&&navigator.credentials.preventSilentAccess()}};hy=q([id(0,Cg),id(1,Lt(ay))],hy);let gy=N.createInterface(e=>e.singleton(hy)),_y=e=>e?{date:e.DATE}:null,vy=e=>e?e.map(e=>({name:e.NAME,version:e.VERSION})):[],yy=e=>Array.isArray(e)?e.map(e=>e??``):[],by=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:_y(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:vy(t.PRODUCT),clientConfig:t.CLIENT_CONFIG??void 0}:null,permission:yy(e.PERMISSION),profile:yy(e.PROFILE)}}throw Error(`No Entity mapping implementation for provided DTO`)}catch(e){throw Y.error(e),e}},xy=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 Am(this.isLoggedIn),this.currentUser.addAuthenticationChangeListener(e=>{var t;(t=this.isLoggedInSubject)==null||t.next(e.detail)})}login(e){return J(this,void 0,void 0,function*(){this.isWorking=!0;try{let t=this.messageBuilder.createLoginMessage(e),n=yield this.connect.send(t);if(!n||n.ERROR||n.DETAILS?.ERROR)throw new kg(t,n);this.applyAuthResults({authToken:n.SESSION_AUTH_TOKEN,refreshToken:n.REFRESH_AUTH_TOKEN,profiles:n.PROFILE,username:n.USER_NAME,permissions:n.PERMISSION,sessionId:n.SESSION_ID}),this.currentUser.set(by(n)),this.session.setAuthResult(n),Y.debug(`Login Authentication Result:`,mg(n))}catch(e){if(Y.error(sg(`Login Authentication Error:`,e?.received),hg(e)),e instanceof kg&&e.hasMfaExpired()&&this.credentialManager.removeMFAToken(),e instanceof kg&&e.isIgnorableError())Y.warn(`Ignoring authentication error as it is a known edge case.`);else throw this.removeAuthResults(),this.currentUser.unset(),e}finally{this.isWorking=!1}return this.loggedUserResult})}logout(){return J(this,void 0,void 0,function*(){this.isWorking=!0;let e={success:!1};try{let t=this.messageBuilder.createLogoutMessage(this.loggedUserResult);this.session.deleteUserFromSessionStorage();let{CODE:n,DETAILS:r,ERROR:i,MESSAGE_TYPE:a,OIDC_LOGOUT_URL:o}=yield this.connect.send(t),s=r?.ERROR??i,c=a===Ag.LOGOUT_NACK;c&&Y.warn(`Unexpected Logout NACK received during logout.`,s),e={success:a===Ag.LOGOUT_ACK||n===Mg.SESSION_NOT_FOUND||!c,error:s},o&&window.open(o,`_self`)}catch(t){let n=new kg(t.sentMessage,t.receivedMessage);if(Y.error(sg(`Logout Authentication Error:`,n.received),hg(n)),n.isIgnorableError())Y.warn(`Ignoring authentication error as it is a known edge case.`),e.success=!0;else throw t}finally{this.removeAuthResults(),this.currentUser.unset(),this.isWorking=!1}return e})}reAuthFromSession(){return J(this,void 0,void 0,function*(){let e=yield this.ensureConnection(),t=this.credentialManager.createRefreshCredentials();if(e&&this.credentialManager.validateRefreshCredentials(t)){let e=this.messageBuilder.createRefreshTokenMessage(),t=yield this.connect.send(e);if(t?.MESSAGE_TYPE===jg.EVENT_LOGIN_AUTH_ACK)return this.session.setAuthResult(t),this.currentUser.set(by(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],xy.prototype,`isWorking`,void 0),q([C],xy.prototype,`loggedUserResult`,void 0),xy=q([id(0,Cg),id(1,Qv),id(2,Lg),id(3,gy),id(4,eg)],xy);let Sy=N.createInterface(e=>e.singleton(xy));function Cy(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 wy={n:`
246
246
  `,r:`\r`,t:` `,b:`\b`,f:`\f`};function Ty(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2].replace(/\\([\s\S])/g,(e,t)=>wy[t]??t):t}function Ey(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`]=Ty(r)}break}case`dateTimeIsLessEqual`:{let n=e.match(/Expr\.dateTimeIsLessEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=Ty(r)}break}case`dateIsGreaterEqual`:{let n=e.match(/Expr\.dateIsGreaterEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_FROM`]=Ty(r)}break}case`dateIsLessEqual`:{let n=e.match(/Expr\.dateIsLessEqual\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[`${e}_TO`]=Ty(r)}break}case`containsIgnoreCase`:{let n=e.match(/Expr\.containsIgnoreCase\((\w+), ?(['"].+['"])\)/);if(n){let[,e,r]=n;t[e]=`*${Ty(r)}*`}break}}}function Dy(e,t){let n=e.indexOf(`=`),r=e.substr(0,n).trim().replace(/["']/g,``);t[r]=Ty(e.slice(n).replace(/^==?/,``))}function Oy(e){if(!e)return{};let t=e.split(`&&`).map(e=>e.trim()),n={};return t.forEach(e=>{if(e){if(e.startsWith(`Expr`))Ey(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`]=Cy(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`]=Cy(i,o)}}else Dy(e,n)}}),n}function ky(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 Ay=class{};Ay.MAX_ROWS_250=250,Ay.MAX_VIEW_1000=1e3,Ay.REQ_REP_POLLING_INTERVAL_MS=1e4,Ay.DATASERVER_ROW_ID=`ROW_REF`,Ay.REQUEST_SERVER_ROW_ID=`RECORD_ID`,Ay.DEFAULT_PAGINATION_PAGE_SIZE=25,Ay.DEFAULT_REQ_REP_OFFSET=0;let jy={options:{criteria:``,isSnapshot:!1,maxRows:Ay.MAX_ROWS_250,maxView:Ay.MAX_VIEW_1000,pollingInterval:Ay.REQ_REP_POLLING_INTERVAL_MS,movingView:!1,orderBy:``,resourceName:``,reverse:!1,pollTriggerEvents:[]},criteriaToFields:Oy,dataServerResultFilter:ky},My=N.createInterface(e=>e.instance(jy));function Ny(e){let t=e==null?NaN:Number(e);return Number.isFinite(t)?t===0?1/0:t:Ay.MAX_VIEW_1000}function Py(e){return e.moreRows===!1?`end`:e.rowsHeld>=Ny(e.maxView)?e.movingView?`more`:`view-full`:e.emptyReply?`stalled`:`more`}function Fy(e){let t=Ny(e.maxView),n=Iy(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 Iy(e){return e==null||!Number.isFinite(Number(e))}let Ly=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(ig,this.onDatasourceStatusChanged,{passive:!0,capture:!0})}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(ig,this.onDatasourceStatusChanged,{capture:!0})}}return q([C],t.prototype,`datasourceStatus`,void 0),t},Ry={throwWhenUnavailable:!0,throwWhenUnknown:!1},zy=N.createInterface(e=>e.instance(Ry)),By=Md(`genesis-resources`);function Vy(){return N.getOrCreateDOMContainer().get(By)}let Hy=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=Vy();e.postMessage(`resources-loaded`,this.resources),e.close()}};Hy=q([id(0,Qv),id(1,zy)],Hy);let Uy=N.createInterface(e=>e.singleton(Hy)),Wy=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 Om}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 Om,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 rg.DATASERVER:return this.connect.snapshot(this.options.resourceName,Object.assign(Object.assign({},this.dataserverOnlyParams),e));case rg.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(![rg.DATASERVER,rg.REQUEST_SERVER].includes(this.resourceType))throw Error(`Streaming not supported for selected resource type: ${this.resourceType}`);return this.resourceType===rg.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(sg(`${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===rg.REQUEST_SERVER&&this.loadMoreCount>0){let t=(this.options.maxRows||25)*(this.loadMoreCount+1);e.DETAILS.MAX_ROWS=t}return Die([this.connect.isConnected$,this.auth.isLoggedIn$]).pipe(Ch(()=>this.connect.isConnected&&this.auth.isLoggedIn),Sh(()=>ch(this.snapshot(e))))};return e?this.pollTrigger$.pipe(xh(0),Sh(()=>gh(0,e).pipe(Sh(t)))):this.pollTrigger$.pipe(xh(0),Sh(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=og(n),this.fieldMetadata=ag(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(sg(`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 '${ig}'`,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],Wy.prototype,`status`,void 0),q([C],Wy.prototype,`fetchMetadataRequired`,void 0),q([C],Wy.prototype,`startStreamRequired`,void 0),q([C],Wy.prototype,`originalFieldDef`,void 0),q([C],Wy.prototype,`fieldMetadata`,void 0),q([C],Wy.prototype,`requestFields`,void 0),q([C],Wy.prototype,`customRequestFields`,void 0),q([C],Wy.prototype,`availableIndexes`,void 0),q([C],Wy.prototype,`availableSortableFields`,void 0),q([C],Wy.prototype,`availableCriteriaFields`,void 0),q([C],Wy.prototype,`criteriaOnlyRequest`,void 0),q([C],Wy.prototype,`loadMoreCount`,void 0),q([C],Wy.prototype,`readOnly`,void 0),q([C],Wy.prototype,`stream`,void 0),Wy=q([id(0,Qv),id(1,Sy),id(2,Uy),id(3,My),id(4,xg)],Wy);let Gy=N.createInterface(e=>e.transient(Wy));var Ky=class extends Wy{constructor(){super(...arguments),this.entityCache=[],this.entityMap=/* @__PURE__ */ new Map,this.rowId=`ROW_REF`,this.initialize=e=>J(this,void 0,void 0,function*(){return this.disconnect(),this.options=Object.assign({},e.options),this.mapper=e.mapper,this.initialized=yield this.init(this.options,e.fetchMeta),this.initialized?(this.subscription=this.stream.subscribe(e=>{this.sourceRef=e.SOURCE_REF,this.subscriptionLoggedOff=e.MESSAGE_TYPE===Ag.LOGOFF_ACK;let t=e.ROW;!this.subscriptionLoggedOff&&t&&this.updateCache(this.config.dataServerResultFilter(e,this.rowId))}),!0):(Y.debug(`EntityDatasource init failed for ${this.options.resourceName}`),!1)}),this.disconnect=()=>{var e;(e=this.subscription)==null||e.unsubscribe(),this.entityCache=[]}}get initialized(){return this._initialized}set initialized(e){this._initialized=e}get cache(){if(!this.initialized)throw Error(`Please initialize EntityDatasource before querying.`);return this.entityCache}get isEmpty(){return this.entityCache.length===0}updateCache(e){var t;this.isEmpty,(t=e.deletes)==null||t.forEach(e=>{let t=e[this.rowId];this.entityMap.delete(t)}),this.processRowDataUpdate(e.inserts,!0),this.processRowDataUpdate(e.updates);let n=[{}];this.entityCache=n.map(e=>this.mapper.fromDTO(e))}processRowDataUpdate(e,t=!1){e.forEach(e=>{let n=e[this.rowId],r=this.entityMap.get(n);if(r&&t)throw Error(`Existing entity found in map while inserting.`);let i=this.mapper.fromDTO(e),a=r?Object.assign(Object.assign({},r),i):i;this.entityMap.set(n,a)})}};N.createInterface(e=>e.transient(Ky));function qy(e,t=`;`){return e&&e.split(t).map(e=>e.trim()).sort((e,t)=>e.localeCompare(t)).join(t)}let Jy=`system-health-changed`,Yy={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 $v().getMoreColumns(e),n=Date.now(),r=t;return{isConnected:t.MESSAGE_TYPE===Ag.MORE_COLUMNS_ACK,lastUpdated:n,lastMessage:r}}),resourceDataLogon:({message:e,functions:t})=>{let{onMessage:n,onError:r}=t;Kv().sendForStream(e,n,r)}},Xy=N.createInterface(e=>e.instance(Yy));var Zy=/* @__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}})}))})),Qy=/* @__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)}}})),$y=/* @__PURE__ */ u(Zy()),eb=/* @__PURE__ */ u(Qy());let tb=Ad(`network-monitor`,{level:vd.info}),nb=Date.now(),rb=window.navigator?.userAgent?$y.default.parse(window.navigator.userAgent):void 0,ib=(e,t={depthLimit:10,edgesLimit:10})=>e instanceof Event?`'${e.type}' Event`:typeof e==`string`?e:(0,eb.default)(e,void 0,2,t);var ab=class{constructor(){this.unsubscribableObservers=[],this.runAllChecks=(e,t)=>J(this,void 0,void 0,function*(){if(!this.isReady||this.isRunningChecks&&!t)return;tb.info(`Run health checks, triggered by`,ib(e),`| Active resources`,this.resources.size),this.isRunningChecks=!0,this.synchroniseCheckInterval();let n=this.getFormattedTimestamp(this.getNowTimestamp()),r=yield this.isOnlineCheck();r?tb.debug(`Network connected at ${n}`):tb.warn(`Network disconnected at ${n}`);let i=this.normaliseSerializedSocketStatus(this.socketStatus.serialize(),r),a=this.preFlightSocketChecks(i);if(a||tb.debug(`Socket pre-flight checks failed`),!r||!a){tb.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{tb.debug(`Running health check against ${r}`);let e=yield Promise.race([c(u,t),zf(this.config.checkTimeout,()=>({isConnected:!1,lastUpdated:this.getNowTimestamp(),timeout:!0}))]);d=e.isConnected,f=e.lastUpdated,p=e.lastMessage,h=e.timeout}catch(e){d=!1,f=this.getNowTimestamp(),m=e,p=e?.receivedMessage??e}return g=p?.MESSAGE_TYPE===Ag.MSG_NACK||Fg(p,cg.NOT_FOUND),n=this.getFormattedTimestamp(f??this.getNowTimestamp()),d?tb.debug(`${r} is healthy at ${n}`):tb.warn(`${r} is not healthy at ${n}`),p&&tb.debug(`${r} messaged at ${n}`,ib(p)),m&&tb.error(`${r} errored at ${n}`,ib(m)),h&&tb.warn(`${r} timed out at ${n}`),g&&(tb.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 tb.warn(`Unexpected promise rejection occurred. Please check any custom resourceChecks return MonitoredResourceChecksResult.`),e},{});tb.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&&(tb.level=this.config.logLevel)}create(){if(this.resources){tb.warn(`NetworkMonitor already created. If this is intentional, please call NetworkMonitor.destroy first.`);return}this.addListeners(),this.resources=/* @__PURE__ */ new Map,setTimeout(()=>{this.isReady=!0,this.synchroniseCheckInterval(),this.runAllChecks(`NetworkMonitor.create()`)},this.config.startDelay)}destroy(){this.removeListeners(),clearInterval(this.internalId),this.resources.clear(),this.resources=void 0,this.status=void 0,this.isReady=void 0}isOnlineCheck(){return Promise.resolve(navigator.onLine)}addResource(e,t){this.resources||this.create(),this.resources.set(e,t)}removeResource(e){this.resources.delete(e)}addListeners(){var e,t;(e=this.config.windowEvents)==null||e.forEach(e=>window.addEventListener(e,this.runAllChecks)),(t=this.config.documentEvents)==null||t.forEach(e=>document.addEventListener(e,this.runAllChecks)),this.config.genesisConnectEvents.includes(`stream`)&&this.unsubscribableObservers.push(this.connectEvents.addStreamListener(({detail:e})=>{let{functions:t,message:n,resourceName:r,stream:i}=e;this.config.ignoredGenesisResources.includes(r)||this.addResource(i,{functions:t,message:n,resourceName:r})},({detail:e})=>{let{resourceName:t,stream:n}=e;this.config.ignoredGenesisResources.includes(t)||this.removeResource(n)},({detail:e})=>{let{resourceName:t,stream:n,error:r}=e,i=r.receivedMessage??r,a=``;Fg(i,cg.NOT_FOUND)?a=`Please check the resource is running.`:Fg(i,cg.FORBIDDEN)&&(a=`You are not authorised to access this resource, removing it from monitoring.`,this.removeResource(n)),tb.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){tb.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?tb.debug:tb.warn)(`Emitting 'system-health-changed' event`,ib(this.status)),t?.dispatchEvent(new CustomEvent(`system-health-changed`,{detail:this.status,bubbles:t!==document,composed:!0})),this.status.socket.reconnectionLimitReached&&(tb.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 tb.debug(`User requested report stability to Genesis.`),tb.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:rb,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:nb,runAllChecks:()=>{tb.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return tb.debug(`Socket not configured`),!1;if(e.isReconnecting)return tb.debug(`Socket reconnecting`),!1;if(e.isConnecting)return tb.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return tb.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&tb.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return tb.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return kf(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([Xy],ab.prototype,`config`,void 0),q([zv],ab.prototype,`socketStatus`,void 0),q([xg],ab.prototype,`connectEvents`,void 0),q([eg],ab.prototype,`user`,void 0),q([C],ab.prototype,`status`,void 0);let ob=N.createInterface(e=>e.singleton(ab)),sb={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},cb=N.createInterface();var lb;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(lb||(lb={}));var ub;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(ub||(ub={}));let db=class{constructor(e,t,n=sb){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(ub.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(lb.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=pf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=pf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=pf(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(lb.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?hf(e.value):e.value}))}},n=yield this.connect.commitEvent(ub.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};db=q([id(0,Qv),id(1,eg),id(2,Lt(cb))],db),N.createInterface(e=>e.singleton(db));var fb=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Am(!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 $h,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],fb.prototype,`isWorking`,void 0),q([C],fb.prototype,`loggedUserResult`,void 0),q([C],fb.prototype,`currentUser`,void 0),q([C],fb.prototype,`isLoggedIn`,void 0);var pb=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=og(e),this.fieldMetadata=ag(this.originalFieldDef),this.requestFields=e.REQUEST_FIELD||[],this.customRequestFields=e.FIELD||[],this.fetchMetadataRequired=!1}unsetMedata(){this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.fetchMetadataRequired=!0}setStream(e){this.stream=ch(Promise.resolve(e))}unsetStream(){this.stream=void 0}deinit(){}destroy(){}validResourceName(e){return!(!e||!e.trim().length)}getMetadata(e){return Promise.resolve(this.fieldMetadata)}snapshot(e){return Promise.resolve(null)}snapshotFiltered(e){return Promise.resolve(null)}updateData(e){return Promise.resolve()}dataHandler(e){return[]}addView(e){}dropView(e){}setFilter(e,t,n){return Promise.resolve()}clearFilter(e){return Promise.resolve()}createItem(e){return Promise.resolve(``)}deleteItem(e){return Promise.resolve()}updateItem(e,t){return Promise.resolve()}get dataserverOnlyParams(){return{}}get requestOnlyParams(){return{}}updateLoadMoreCount(e){}};q([C],pb.prototype,`status`,void 0),q([C],pb.prototype,`fetchMetadataRequired`,void 0),q([C],pb.prototype,`originalFieldDef`,void 0),q([C],pb.prototype,`fieldMetadata`,void 0),q([C],pb.prototype,`requestFields`,void 0),q([C],pb.prototype,`customRequestFields`,void 0),q([C],pb.prototype,`availableIndexes`,void 0),q([C],pb.prototype,`availableSortableFields`,void 0),q([C],pb.prototype,`availableCriteriaFields`,void 0),q([C],pb.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(eg));let mb=Ad(`foundation-ui`);var hb=class extends Ly(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Ay.MAX_ROWS_250,this.maxView=Ay.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 Am(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==qy(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===rg.REQUEST_SERVER?Ay.REQUEST_SERVER_ROW_ID:Ay.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}mb.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?ky(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Ag.LOGOFF_ACK){this.dataSubWasLoggedOff=!0;return}this.dataSubWasLoggedOff=!1,t?this.handleStreamUpdate(t):this.handleStreamUpdate(e)})}})}initDatasource(){return J(this,void 0,void 0,function*(){yield this.datasource.init(this.datasourceOptions(),!0)})}canRequestMoreRows(){if(!this.isConnected||!this.datasource||!this.moreRowsAvailable)return!1;switch(this.datasource.resourceType){case rg.REQUEST_SERVER:return!0;case rg.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===rg.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 ky(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==rg.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=Py({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=Fy({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&mb.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 qy((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&&mb[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===ng.DATE||t===ng.DATETIME?Af(e,t===ng.DATETIME):e}};q([Qv],hb.prototype,`connect`,void 0),q([Gy],hb.prototype,`datasource`,void 0),q([D({mode:`boolean`})],hb.prototype,`withGridInit`,void 0),q([D],hb.prototype,`criteria`,void 0),q([C],hb.prototype,`data`,void 0),q([D],hb.prototype,`fields`,void 0),q([D({mode:`boolean`})],hb.prototype,`isSnapshot`,void 0),q([D],hb.prototype,`maxRows`,void 0),q([D],hb.prototype,`maxView`,void 0),q([D],hb.prototype,`orderBy`,void 0),q([D],hb.prototype,`request`,void 0),q([D],hb.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],hb.prototype,`reverse`,void 0),q([D],hb.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],hb.prototype,`withTimestampFormatting`,void 0);let gb=(e,t)=>!e.composedPath().includes(t),_b=(e,t)=>e.composedPath().includes(t),vb=e=>e.tagName.toLowerCase().split(`-`)[0];function yb(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let bb=Ad(`foundation-criteria`);var xb;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(xb||(xb={}));var Sb=class e{constructor(e){this.$$operator=e}static And(){return new e(xb.AND)}static Or(){return new e(xb.OR)}static Not(){return new e(xb.NOT)}static GreaterThan(){return new e(xb.GT)}static GreaterThanOrEqual(){return new e(xb.GE)}static LessThan(){return new e(xb.LT)}static LessThanOrEqual(){return new e(xb.LE)}static NotEqual(){return new e(xb.NE)}static Equal(){return new e(xb.EQ)}get operator(){return this.$$operator}};let Cb=e=>e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`),wb=e=>`'${Cb(e)}'`,Tb=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?wb(t):t},Eb=e=>t=>`${t.field} ${e} ${Tb(t)}`,Db=e=>Eb(xb.NE)(e),Ob=e=>`${e.field}.contains(${Tb(e)})`,kb={AND:e=>Eb(xb.AND)(e),OR:e=>Eb(xb.OR)(e),NOT:Db,GT:e=>Eb(xb.GT)(e),GE:e=>Eb(xb.GE)(e),LT:e=>Eb(xb.LT)(e),LE:e=>Eb(xb.LE)(e),NE:Db,EQ:e=>Eb(xb.EQ)(e),equals:e=>`${e.field}.equals(${Tb(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Tb(e)})`,contains:Ob,fieldContains:Ob,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Tb(e)})`,startsWith:e=>`${e.field}.startsWith(${Tb(e)})`,endsWith:e=>`${e.field}.endsWith(${Tb(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Tb(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Tb(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Tb(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Tb(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Tb(e)})`},Ab=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),jb=e=>Array.isArray(e)?e:[e],Mb=`default`;var Nb=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,Sb.And()),this.Or=(e,t={})=>this.withExpression(e,t,Sb.Or()),this.Not=(e,t={})=>this.withExpression(e,t,Sb.Not())}withExpression(e,t={},n=Sb.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=Mb)=>{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 Sb;return t&&bb.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Ab(t,i),Mb)}else o(e,Mb)}else typeof e==`string`?o(e,Mb):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 Sb&&n[t-1]instanceof Sb)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof Sb?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Pb=class{constructor(e){this.serialiser=kb.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 Fb=(e=`rapid`)=>T`<${e}-segmented-control :value="${lf(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>`,Ib=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Nb,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(jb(i).map(e=>jb(n).map(t=>new Pb().withField(t).withValue(e).withSerialiser(r).build())),{join:Sb.Or()}):t.And(new Pb().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],Ib.prototype,`criteriaOptions`,void 0),q([C],Ib.prototype,`prefix`,void 0),q([C],Ib.prototype,`value`,void 0),q([C],Ib.prototype,`selectedLabel`,void 0),Ib=q([$e({name:`criteria-segmented-control`,template:Fb(),styles:O``})],Ib);function Lb(e,t){let n=new Nb;n.withExpression(new Pb().withField(e.labelField??e.valueField).withValue(t).withSerialiser(kb.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Rb(e,t){let n=new Nb;n.withExpression(new Pb().withField(e.valueField).withValue(t).withSerialiser(kb.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let zb=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,Bb=e=>{let t=/* @__PURE__ */ new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))},Vb=Bb(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>`),Hb=Bb(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>`),Ub=Bb(e=>T` ${t=>t.iconName?Vb(e):Hb(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>`),Wb=Bb(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>`),Gb=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(vb(e))}</div>`;var Kb=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}},qb=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=`${In(0,Math.max(n-a,0),c)}px`,t.style.right=`${In(0,Math.max(r-i,0),r-e.right)}px`}startTrackingPosition(){this.positionTracker=new Kb(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=pn([`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 Ub(e);if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],Wb(e)):Ub(e)}};q([C],qb.prototype,`actions`,void 0),q([C],qb.prototype,`actionsResolver`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],qb.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],qb.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],qb.prototype,`autoCloseOnAction`,void 0),q([C],qb.prototype,`classNames`,void 0),q([C],qb.prototype,`definition`,void 0),q([D],qb.prototype,`name`,void 0),q([D({attribute:`icon-name`})],qb.prototype,`iconName`,void 0),q([D({attribute:`open`,mode:`boolean`})],qb.prototype,`open`,void 0),q([D],qb.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],qb.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],qb.prototype,`hideMenuSingleOption`,void 0),q([C],qb.prototype,`singleOption`,void 0),qb.compose({baseName:`actions-menu`,styles:qne,template:Gb});let Jb=()=>{};function Yb(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:Jb};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 Xb=!1;try{typeof GENX_ENABLE_AI<`u`&&(Xb=GENX_ENABLE_AI===`true`)}catch{}let Zb=()=>Xb||_f(`ai`),Qb=Ad(`foundation-ai`);function $b(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function ex(e,t){if(!$b())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 tx=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 nx=[`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`],rx=[`claude-fable-5`,`claude-opus-5-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5-5`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-5-5`,`claude-haiku-4-5-20251001`],ix=[`gpt-6-astra`,`gpt-6.1-sol`,`gpt-6.1-terra`,`gpt-6-sol`,`gpt-6-luna`];function ax(e){return e===`image/jpg`?`image/jpeg`:e}function ox(e){return e.replace(/^data:[^,]*;base64,/,``)}let sx=.5;function cx(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=sx?r/sx*t:t+(r-sx)/.5*(n-t)}let lx=1e6,ux={"claude-haiku-4-5-20251001":{kind:`flat`,rate:{promptPerMillion:1,candidatePerMillion:5}},"claude-haiku-5-5":{kind:`tiered`,standard:{promptPerMillion:.1,candidatePerMillion:.5},longContext:{promptPerMillion:.5,candidatePerMillion:2.5}},"claude-fable-5":{kind:`flat`,rate:{promptPerMillion:10,candidatePerMillion:50}},"claude-opus-5-5":{kind:`flat`,rate:{promptPerMillion:4,candidatePerMillion:20},cacheReadMultiplier:.05},"claude-opus-4-8":{kind:`flat`,rate:{promptPerMillion:5,candidatePerMillion:25}},"claude-opus-4-7":{kind:`flat`,rate:{promptPerMillion:5,candidatePerMillion:25}},"claude-sonnet-5-5":{kind:`flat`,rate:{promptPerMillion:2,candidatePerMillion:10},cacheReadMultiplier:.05},"claude-sonnet-5":{kind:`flat`,rate:{promptPerMillion:2,candidatePerMillion:10}},"claude-sonnet-4-6":{kind:`flat`,rate:{promptPerMillion:3,candidatePerMillion:15}}};function dx(e,t=0){let n=ux[e];return n.kind===`flat`?n.rate:t>1e5?n.longContext:n.standard}function fx(e){return ux[e].cacheReadMultiplier??.1}function px(e,t){let{promptPerMillion:n,candidatePerMillion:r}=dx(e,t.uncachedInputTokens+t.cacheReadTokens+t.cacheWriteTokens),i=fx(e),a=lx,o=Math.max(0,t.cacheWriteTokens-t.cacheWrite1hTokens),s=t.uncachedInputTokens/a*n,c=t.cacheReadTokens/a*n*i,l=o/a*n*1.25+t.cacheWrite1hTokens/a*n*2,u=t.outputTokens/a*r,d=t.cacheReadTokens/a*n,f=t.cacheWriteTokens/a*n;return{costUsd:s+c+l+u,savedUsd:d-c+(f-l),breakdown:{promptUsd:s,cacheReadUsd:c,cacheWriteUsd:l,candidateUsd:u}}}let mx={"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 hx(e,t,n=/* @__PURE__ */ new Date){let r=mx[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 gx(e,t,n=/* @__PURE__ */ new Date){let{promptPerMillion:r,candidatePerMillion:i}=hx(e,t.promptTokens,n),a=lx,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 _x={"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 vx(e,t){let n=_x[e];return t<=272e3?n:{promptPerMillion:n.promptPerMillion*2,cachedPerMillion:n.cachedPerMillion*2,candidatePerMillion:n.candidatePerMillion*1.5}}function yx(e,t){let{promptPerMillion:n,cachedPerMillion:r,candidatePerMillion:i}=vx(e,t.inputTokens),a=lx,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 bx=[`properties`,`patternProperties`,`$defs`,`definitions`],xx=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],Sx=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Cx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function wx(e){if(Array.isArray(e))return e.map(wx);if(Cx(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=wx(r);return t}return e}function Tx(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=bx.includes(i)&&Cx(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Cx(r)?t(r,`${e}/${n}`):wx(r)])):xx.includes(i)&&Array.isArray(a)?a.map((n,r)=>Cx(n)?t(n,`${e}/${r}`):wx(n)):Sx.includes(i)?Cx(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Cx(n)?t(n,`${e}/${r}`):wx(n)):wx(a):wx(a)}return r}function Ex(e,t,n=``){return t(Tx(e,(e,n)=>Ex(e,t,n),n),n)}let Dx=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Ox=[`oneOf`,`not`];function kx(e){let t=[],n=[],r=[];return{schema:Ex(e,(e,i)=>{for(let n of Dx)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 Ox)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Cx(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function Ax(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=kx(e);return r.length&&Qb.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&Qb.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&&Qb.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 jx=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Mx(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Cx(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Cx(n)?n:void 0}function Nx(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=Mx(e,o);if(!t)break;let{$ref:n}=i,r=rd(i,[`$ref`]);i=Object.assign(Object.assign({},wx(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),Tx(i,t=>Nx(e,t,a,r),``)}function Px(e){let t=[],n=Nx(e,e,/* @__PURE__ */ new Set,t);return t.length&&Qb.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.`),Ex(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(Cx),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 jx)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}let Fx=[`allOf`,`not`,`if`,`then`,`else`,`oneOf`];function Ix(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=>Cx(e)&&e.type===`null`)?e:Object.assign(Object.assign({},e),{anyOf:[...e.anyOf,{type:`null`}]}):{anyOf:[e,{type:`null`}]}}function Lx(e){let t=[],n=[],r=[];return{schema:Ex(e,(e,i)=>{for(let t of Fx)t in e&&r.push(`${i}/${t}`);if(!(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Cx(e.properties)))return e;if(e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),Cx(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]=Cx(a[e])?Ix(a[e]):{type:`null`},t.push(`${i}/properties/${e}`));e.required=n}return e}),madeNullable:t,overridden:n,undroppable:r}}function Rx(e,t){let{schema:n,madeNullable:r,overridden:i,undroppable:a}=Lx(e);return r.length&&Qb.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&&Qb.warn(`OpenAITransport: tool "${t}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}.`),a.length&&Qb.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 zx=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`});Object.freeze([`anthropic`,`gemini`,`openai`]),new Map(Object.entries(zx).map(([e,t])=>[t.toLowerCase(),e]));var Bx=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 Vx=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,Hx=e=>{try{return JSON.parse(e)}catch{return}},Ux=e=>{let t=e?.code;return typeof t==`string`?t:void 0},Wx=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Gx=e=>typeof e==`boolean`?e:void 0,Kx=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function qx(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 Bx(e,Wx(r.budgetUsd)??Wx(i.budgetUsd),Wx(r.spentUsd)??Wx(i.spentUsd),a,{otherVendorAvailable:Gx(r.otherVendorAvailable)??Gx(i.otherVendorAvailable),serverVendor:Kx(r.vendor)??Kx(i.vendor)})}function Jx(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 Yx(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 Xx=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`}),Zx=new Set(Object.values(Xx));function Qx(e){return typeof e==`string`&&Zx.has(e)?e:void 0}let $x=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),eS=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},tS=e=>e?.code!==void 0;function nS(e,t,n){if(e!==401&&e!==403||tS(t))return;let r=typeof n==`string`&&n.trim()===``;if(eS(t)||r)return e===401?$x.SIGNED_OUT:$x.ACCESS_DENIED}function rS(e,t){return e===413&&t===void 0}function iS(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let aS=`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:aS,FALLBACKS_NOT_SUPPORTED:aS,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 oS=e=>e!==Xx.VENDOR_UNREACHABLE;var sS=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 oS(this.code)}};function cS(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let lS=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]),uS=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var dS=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 coe(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 fS(e,t,n){if(t===400)for(let e of coe(n)){if(!lS.some(t=>t.test(e)))continue;let t=uS.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function loe(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:rb,username:i,isHealthy:t,lastUpdated:n,nextUpdate:r,firstUpdated:nb,runAllChecks:()=>{tb.debug(`User activated run checks command starting.`),this.runAllChecks(`user requested`)},reportStabilityToGenesis:()=>this.reportStabilityToGenesis(a)});return a}preFlightSocketChecks(e){if(!e.isConfigured)return tb.debug(`Socket not configured`),!1;if(e.isReconnecting)return tb.debug(`Socket reconnecting`),!1;if(e.isConnecting)return tb.debug(`Socket connecting`),!1;if(e.isDisconnected){let t=e.isDisconnectedByServer?`by the server, code: ${e.closedCode}, reason: ${e.closedReason}`:``;return tb.debug(`Socket disconnected ${t}`),e.reconnectionLimitReached&&tb.debug(`Socket reconnection limit reached`),!1}let t=this.user.isAuthenticated?`with`:`without`;return tb.debug(`Socket connected ${t} valid session`),!0}getFormattedTimestamp(e){return kf(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([Xy],ab.prototype,`config`,void 0),q([zv],ab.prototype,`socketStatus`,void 0),q([xg],ab.prototype,`connectEvents`,void 0),q([eg],ab.prototype,`user`,void 0),q([C],ab.prototype,`status`,void 0);let ob=N.createInterface(e=>e.singleton(ab)),sb={account:`genesis`,namespace:`default`,authKey:`kv-default`,authEmail:void 0},cb=N.createInterface();var lb;(function(e){e.REQ_KEY_VALUE_LIST=`REQ_KEY_VALUE_LIST`,e.REQ_KEY_VALUE_READ=`REQ_KEY_VALUE_READ`})(lb||(lb={}));var ub;(function(e){e.EVENT_KEY_VALUE_PUT=`EVENT_KEY_VALUE_PUT`,e.EVENT_KEY_VALUE_DELETE=`EVENT_KEY_VALUE_DELETE`})(ub||(ub={}));let db=class{constructor(e,t,n=sb){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(ub.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(lb.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=pf(e);return typeof t==`string`&&t.startsWith(`str:`)&&(t=pf(t)),typeof t==`string`&&t.startsWith(`bin:`)&&(t=pf(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(lb.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?hf(e.value):e.value}))}},n=yield this.connect.commitEvent(ub.EVENT_KEY_VALUE_PUT,t);return n&&n.MESSAGE_TYPE===`EVENT_ACK`?!0:{ERROR:n.ERROR,WARNING:n.WARNING}})}};db=q([id(0,Qv),id(1,eg),id(2,Lt(cb))],db),N.createInterface(e=>e.singleton(db));var fb=class{constructor(){this.isWorking=!1,this.loggedUserResult=null,this.currentUser=null,this.isLoggedIn=!1,this.isLoggedInSubject=new Am(!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 $h,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],fb.prototype,`isWorking`,void 0),q([C],fb.prototype,`loggedUserResult`,void 0),q([C],fb.prototype,`currentUser`,void 0),q([C],fb.prototype,`isLoggedIn`,void 0);var pb=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=og(e),this.fieldMetadata=ag(this.originalFieldDef),this.requestFields=e.REQUEST_FIELD||[],this.customRequestFields=e.FIELD||[],this.fetchMetadataRequired=!1}unsetMedata(){this.availableIndexes=[],this.availableSortableFields=[],this.availableCriteriaFields=[],this.originalFieldDef=[],this.fieldMetadata=[],this.requestFields=[],this.fetchMetadataRequired=!0}setStream(e){this.stream=ch(Promise.resolve(e))}unsetStream(){this.stream=void 0}deinit(){}destroy(){}validResourceName(e){return!(!e||!e.trim().length)}getMetadata(e){return Promise.resolve(this.fieldMetadata)}snapshot(e){return Promise.resolve(null)}snapshotFiltered(e){return Promise.resolve(null)}updateData(e){return Promise.resolve()}dataHandler(e){return[]}addView(e){}dropView(e){}setFilter(e,t,n){return Promise.resolve()}clearFilter(e){return Promise.resolve()}createItem(e){return Promise.resolve(``)}deleteItem(e){return Promise.resolve()}updateItem(e,t){return Promise.resolve()}get dataserverOnlyParams(){return{}}get requestOnlyParams(){return{}}updateLoadMoreCount(e){}};q([C],pb.prototype,`status`,void 0),q([C],pb.prototype,`fetchMetadataRequired`,void 0),q([C],pb.prototype,`originalFieldDef`,void 0),q([C],pb.prototype,`fieldMetadata`,void 0),q([C],pb.prototype,`requestFields`,void 0),q([C],pb.prototype,`customRequestFields`,void 0),q([C],pb.prototype,`availableIndexes`,void 0),q([C],pb.prototype,`availableSortableFields`,void 0),q([C],pb.prototype,`availableCriteriaFields`,void 0),q([C],pb.prototype,`criteriaOnlyRequest`,void 0),N.createInterface(e=>e.aliasTo(eg));let mb=Ad(`foundation-ui`);var hb=class extends Ly(P){constructor(){super(...arguments),this.withGridInit=!0,this.isSnapshot=!1,this.maxRows=Ay.MAX_ROWS_250,this.maxView=Ay.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 Am(/* @__PURE__ */ new Map),this.fetchGeneration=0}criteriaChanged(e,t){let n=e!==qy(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===rg.REQUEST_SERVER?Ay.REQUEST_SERVER_ROW_ID:Ay.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}mb.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?ky(e):void 0;this.updateStreamPagingState(e,t);let n=e.MESSAGE_TYPE;if(n&&n===Ag.LOGOFF_ACK){this.dataSubWasLoggedOff=!0;return}this.dataSubWasLoggedOff=!1,t?this.handleStreamUpdate(t):this.handleStreamUpdate(e)})}})}initDatasource(){return J(this,void 0,void 0,function*(){yield this.datasource.init(this.datasourceOptions(),!0)})}canRequestMoreRows(){if(!this.isConnected||!this.datasource||!this.moreRowsAvailable)return!1;switch(this.datasource.resourceType){case rg.REQUEST_SERVER:return!0;case rg.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===rg.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 ky(e).inserts}}updateStreamPagingState(e,t){let n=typeof e?.MORE_ROWS==`boolean`;if(this.datasource.resourceType!==rg.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=Py({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=Fy({status:a,resourceName:this.resourceName,rowsHeld:this.viewRowCount,maxView:this.maxView,emptyReply:i,attribute:`maxView`});e&&mb.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 qy((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&&mb[n](t,...r)}getFieldMetadata(e){return this.datasource.fieldMetadata?.find(t=>t.name===e)}getDefaultLabelFormat(e,t){return t===ng.DATE||t===ng.DATETIME?Af(e,t===ng.DATETIME):e}};q([Qv],hb.prototype,`connect`,void 0),q([Gy],hb.prototype,`datasource`,void 0),q([D({mode:`boolean`})],hb.prototype,`withGridInit`,void 0),q([D],hb.prototype,`criteria`,void 0),q([C],hb.prototype,`data`,void 0),q([D],hb.prototype,`fields`,void 0),q([D({mode:`boolean`})],hb.prototype,`isSnapshot`,void 0),q([D],hb.prototype,`maxRows`,void 0),q([D],hb.prototype,`maxView`,void 0),q([D],hb.prototype,`orderBy`,void 0),q([D],hb.prototype,`request`,void 0),q([D],hb.prototype,`resourceName`,void 0),q([D({mode:`boolean`})],hb.prototype,`reverse`,void 0),q([D],hb.prototype,`rowId`,void 0),q([D({mode:`boolean`,attribute:`with-timestamp-formatting`})],hb.prototype,`withTimestampFormatting`,void 0);let gb=(e,t)=>!e.composedPath().includes(t),_b=(e,t)=>e.composedPath().includes(t),vb=e=>e.tagName.toLowerCase().split(`-`)[0];function yb(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.activeElement:document.activeElement}let bb=Ad(`foundation-criteria`);var xb;(function(e){e.AND=`&&`,e.OR=`||`,e.NOT=`!`,e.GT=`>`,e.GE=`>=`,e.LT=`<`,e.LE=`<=`,e.NE=`!=`,e.EQ=`==`})(xb||(xb={}));var Sb=class e{constructor(e){this.$$operator=e}static And(){return new e(xb.AND)}static Or(){return new e(xb.OR)}static Not(){return new e(xb.NOT)}static GreaterThan(){return new e(xb.GT)}static GreaterThanOrEqual(){return new e(xb.GE)}static LessThan(){return new e(xb.LT)}static LessThanOrEqual(){return new e(xb.LE)}static NotEqual(){return new e(xb.NE)}static Equal(){return new e(xb.EQ)}get operator(){return this.$$operator}};let Cb=e=>e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`),wb=e=>`'${Cb(e)}'`,Tb=e=>{let{value:t}=e;return e.valueGetter?e.valueGetter(t):typeof t==`function`?t(e):Array.isArray(t)?t.join(`,`):typeof t==`string`?wb(t):t},Eb=e=>t=>`${t.field} ${e} ${Tb(t)}`,Db=e=>Eb(xb.NE)(e),Ob=e=>`${e.field}.contains(${Tb(e)})`,kb={AND:e=>Eb(xb.AND)(e),OR:e=>Eb(xb.OR)(e),NOT:Db,GT:e=>Eb(xb.GT)(e),GE:e=>Eb(xb.GE)(e),LT:e=>Eb(xb.LT)(e),LE:e=>Eb(xb.LE)(e),NE:Db,EQ:e=>Eb(xb.EQ)(e),equals:e=>`${e.field}.equals(${Tb(e)})`,equalsIgnoreCase:e=>`${e.field}.equalsIgnoreCase(${Tb(e)})`,contains:Ob,fieldContains:Ob,containsIgnoreCase:e=>`Expr.containsIgnoreCase(${e.field}, ${Tb(e)})`,startsWith:e=>`${e.field}.startsWith(${Tb(e)})`,endsWith:e=>`${e.field}.endsWith(${Tb(e)})`,dateIsToday:e=>`Expr.dateIsToday(${e.field})`,dateIsEqual:e=>`Expr.dateIsEqual(${e.field}, ${Tb(e)})`,dateIsGreaterEqual:e=>`Expr.dateIsGreaterEqual(${e.field}, ${Tb(e)})`,dateIsLessEqual:e=>`Expr.dateIsLessEqual(${e.field}, ${Tb(e)})`,dateTimeIsGreaterEqual:e=>`Expr.dateTimeIsGreaterEqual(${e.field}, ${Tb(e)})`,dateTimeIsLessEqual:e=>`Expr.dateTimeIsLessEqual(${e.field}, ${Tb(e)})`},Ab=(e,t)=>e.flat().flatMap((e,n,r)=>r.length-1===n?e:[e,t]),jb=e=>Array.isArray(e)?e:[e],Mb=`default`;var Nb=class{constructor(){this.expressions={},this.And=(e,t={})=>this.withExpression(e,t,Sb.And()),this.Or=(e,t={})=>this.withExpression(e,t,Sb.Or()),this.Not=(e,t={})=>this.withExpression(e,t,Sb.Not())}withExpression(e,t={},n=Sb.And()){let{condition:r,join:i,groupName:a}=t,o=(e,t=Mb)=>{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 Sb;return t&&bb.warn(`Inline joins will be discarded when join is defined in ExpressionOptions`),!t});a?t.forEach(e=>{o(e,a)}):o(Ab(t,i),Mb)}else o(e,Mb)}else typeof e==`string`?o(e,Mb):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 Sb&&n[t-1]instanceof Sb)throw Error(`Adjacent Join operations detected`)}),r.push(`(${e.map(e=>this.parseExpression(e,void 0)).join(``)})`)):e instanceof Sb?r.push(` ${e.operator} `):e&&r.push(e.serialiser(e)),r.join(``)}},Pb=class{constructor(e){this.serialiser=kb.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 Fb=(e=`rapid`)=>T`<${e}-segmented-control :value="${lf(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>`,Ib=class extends Qe{constructor(){super(...arguments),this.criteriaOptions=[],this.createCriteria=e=>{let t=new Nb,{field:n,serialiser:r,value:i}=e;return Array.isArray(n)||Array.isArray(i)?t.And(jb(i).map(e=>jb(n).map(t=>new Pb().withField(t).withValue(e).withSerialiser(r).build())),{join:Sb.Or()}):t.And(new Pb().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],Ib.prototype,`criteriaOptions`,void 0),q([C],Ib.prototype,`prefix`,void 0),q([C],Ib.prototype,`value`,void 0),q([C],Ib.prototype,`selectedLabel`,void 0),Ib=q([$e({name:`criteria-segmented-control`,template:Fb(),styles:O``})],Ib);function Lb(e,t){let n=new Nb;n.withExpression(new Pb().withField(e.labelField??e.valueField).withValue(t).withSerialiser(kb.containsIgnoreCase).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}function Rb(e,t){let n=new Nb;n.withExpression(new Pb().withField(e.valueField).withValue(t).withSerialiser(kb.equals).build()),e.criteria=e.baseCriteria?`${e.baseCriteria} && ${n.build()}`:n.build()}let zb=(e,t,n)=>T`<${t}-icon tooltip="${()=>e}" name="${()=>n}"></${t}-icon>`,Bb=e=>{let t=/* @__PURE__ */ new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))},Vb=Bb(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>`),Hb=Bb(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>`),Ub=Bb(e=>T` ${t=>t.iconName?Vb(e):Hb(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>`),Wb=Bb(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>`),Gb=T`<div class="actions-container${e=>e.isVertical?` actions-vertical`:``}" part="actions-container">${e=>e.getTemplate(vb(e))}</div>`;var Kb=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}},qb=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=`${In(0,Math.max(n-a,0),c)}px`,t.style.right=`${In(0,Math.max(r-i,0),r-e.right)}px`}startTrackingPosition(){this.positionTracker=new Kb(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=pn([`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 Ub(e);if(this.singleOption=null,t.length!==0)return t.length===1?(this.singleOption=t[0],Wb(e)):Ub(e)}};q([C],qb.prototype,`actions`,void 0),q([C],qb.prototype,`actionsResolver`,void 0),q([D({attribute:`is-vertical`,mode:`boolean`})],qb.prototype,`isVertical`,void 0),q([D({attribute:`add-default-actions`,mode:`boolean`})],qb.prototype,`addDefaultActions`,void 0),q([D({attribute:`auto-close-on-action`,mode:`boolean`})],qb.prototype,`autoCloseOnAction`,void 0),q([C],qb.prototype,`classNames`,void 0),q([C],qb.prototype,`definition`,void 0),q([D],qb.prototype,`name`,void 0),q([D({attribute:`icon-name`})],qb.prototype,`iconName`,void 0),q([D({attribute:`open`,mode:`boolean`})],qb.prototype,`open`,void 0),q([D],qb.prototype,`buttonAppearance`,void 0),q([D({attribute:`hide-disabled`,mode:`boolean`})],qb.prototype,`hideDisabled`,void 0),q([D({attribute:`hide-menu-single-option`,mode:`boolean`})],qb.prototype,`hideMenuSingleOption`,void 0),q([C],qb.prototype,`singleOption`,void 0),qb.compose({baseName:`actions-menu`,styles:qne,template:Gb});let Jb=()=>{};function Yb(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:Jb};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 Xb=!1;try{typeof GENX_ENABLE_AI<`u`&&(Xb=GENX_ENABLE_AI===`true`)}catch{}let Zb=()=>Xb||_f(`ai`),Qb=Ad(`foundation-ai`);function $b(){return typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)}function ex(e,t){if(!$b())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 tx=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 nx=[`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`],rx=[`claude-fable-5`,`claude-opus-5-5`,`claude-opus-4-8`,`claude-opus-4-7`,`claude-sonnet-5-5`,`claude-sonnet-5`,`claude-sonnet-4-6`,`claude-haiku-5-5`,`claude-haiku-4-5-20251001`],ix=[`gpt-6-astra`,`gpt-6.1-sol`,`gpt-6.1-terra`,`gpt-6-sol`,`gpt-6-luna`];function ax(e){return e===`image/jpg`?`image/jpeg`:e}function ox(e){return e.replace(/^data:[^,]*;base64,/,``)}let sx=.5;function cx(e,{defaultTemp:t,maxTemp:n}){let r=Math.min(Math.max(e,0),1);return r<=sx?r/sx*t:t+(r-sx)/.5*(n-t)}let lx=1e6,ux={"claude-haiku-4-5-20251001":{kind:`flat`,rate:{promptPerMillion:1,candidatePerMillion:5}},"claude-haiku-5-5":{kind:`tiered`,standard:{promptPerMillion:.1,candidatePerMillion:.5},longContext:{promptPerMillion:.5,candidatePerMillion:2.5}},"claude-fable-5":{kind:`flat`,rate:{promptPerMillion:10,candidatePerMillion:50}},"claude-opus-5-5":{kind:`flat`,rate:{promptPerMillion:4,candidatePerMillion:20},cacheReadMultiplier:.05},"claude-opus-4-8":{kind:`flat`,rate:{promptPerMillion:5,candidatePerMillion:25}},"claude-opus-4-7":{kind:`flat`,rate:{promptPerMillion:5,candidatePerMillion:25}},"claude-sonnet-5-5":{kind:`flat`,rate:{promptPerMillion:2,candidatePerMillion:10},cacheReadMultiplier:.05},"claude-sonnet-5":{kind:`flat`,rate:{promptPerMillion:2,candidatePerMillion:10}},"claude-sonnet-4-6":{kind:`flat`,rate:{promptPerMillion:3,candidatePerMillion:15}}};function dx(e,t=0){let n=ux[e];return n.kind===`flat`?n.rate:t>1e5?n.longContext:n.standard}function fx(e){return ux[e].cacheReadMultiplier??.1}function px(e,t){let{promptPerMillion:n,candidatePerMillion:r}=dx(e,t.uncachedInputTokens+t.cacheReadTokens+t.cacheWriteTokens),i=fx(e),a=lx,o=Math.max(0,t.cacheWriteTokens-t.cacheWrite1hTokens),s=t.uncachedInputTokens/a*n,c=t.cacheReadTokens/a*n*i,l=o/a*n*1.25+t.cacheWrite1hTokens/a*n*2,u=t.outputTokens/a*r,d=t.cacheReadTokens/a*n,f=t.cacheWriteTokens/a*n;return{costUsd:s+c+l+u,savedUsd:d-c+(f-l),breakdown:{promptUsd:s,cacheReadUsd:c,cacheWriteUsd:l,candidateUsd:u}}}let mx={"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 hx(e,t,n=/* @__PURE__ */ new Date){let r=mx[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 gx(e,t,n=/* @__PURE__ */ new Date){let{promptPerMillion:r,candidatePerMillion:i}=hx(e,t.promptTokens,n),a=lx,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 _x={"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 vx(e,t){let n=_x[e];return t<=272e3?n:{promptPerMillion:n.promptPerMillion*2,cachedPerMillion:n.cachedPerMillion*2,candidatePerMillion:n.candidatePerMillion*1.5}}function yx(e,t){let{promptPerMillion:n,cachedPerMillion:r,candidatePerMillion:i}=vx(e,t.inputTokens),a=lx,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 bx=[`properties`,`patternProperties`,`$defs`,`definitions`],xx=[`anyOf`,`oneOf`,`allOf`,`prefixItems`],Sx=[`items`,`not`,`additionalProperties`,`propertyNames`,`contains`],Cx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function wx(e){if(Array.isArray(e))return e.map(wx);if(Cx(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=wx(r);return t}return e}function Tx(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`${n}/${i}`;r[i]=bx.includes(i)&&Cx(a)?Object.fromEntries(Object.entries(a).map(([n,r])=>[n,Cx(r)?t(r,`${e}/${n}`):wx(r)])):xx.includes(i)&&Array.isArray(a)?a.map((n,r)=>Cx(n)?t(n,`${e}/${r}`):wx(n)):Sx.includes(i)?Cx(a)?t(a,e):Array.isArray(a)?a.map((n,r)=>Cx(n)?t(n,`${e}/${r}`):wx(n)):wx(a):wx(a)}return r}function Ex(e,t,n=``){return t(Tx(e,(e,n)=>Ex(e,t,n),n),n)}let Dx=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`],Ox=[`oneOf`,`not`];function kx(e){let t=[],n=[],r=[];return{schema:Ex(e,(e,i)=>{for(let n of Dx)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 Ox)t in e&&r.push(`${i}/${t}`);return(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Cx(e.properties))&&e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),e}),stripped:t,overridden:n,undroppable:r}}function Ax(e,t){let{schema:n,stripped:r,overridden:i,undroppable:a}=kx(e);return r.length&&Qb.warn(`AnthropicTransport: tool "${t}" requested schema enforcement; these keywords cannot be enforced and were removed — validate them yourself: ${r.join(`, `)}`),i.length&&Qb.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&&Qb.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 jx=[`additionalProperties`,`examples`,`multipleOf`,`patternProperties`,`$defs`,`definitions`];function Mx(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`)){if(!Cx(n))return;n=n[e.replace(/~1/g,`/`).replace(/~0/g,`~`)]}return Cx(n)?n:void 0}function Nx(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=Mx(e,o);if(!t)break;let{$ref:n}=i,r=rd(i,[`$ref`]);i=Object.assign(Object.assign({},wx(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),Tx(i,t=>Nx(e,t,a,r),``)}function Px(e){let t=[],n=Nx(e,e,/* @__PURE__ */ new Set,t);return t.length&&Qb.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.`),Ex(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(Cx),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 jx)delete e[t];for(let t of Object.keys(e))t.startsWith(`$`)&&t!==`$ref`&&delete e[t];return e})}let Fx=[`allOf`,`not`,`if`,`then`,`else`,`oneOf`];function Ix(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=>Cx(e)&&e.type===`null`)?e:Object.assign(Object.assign({},e),{anyOf:[...e.anyOf,{type:`null`}]}):{anyOf:[e,{type:`null`}]}}function Lx(e){let t=[],n=[],r=[];return{schema:Ex(e,(e,i)=>{for(let t of Fx)t in e&&r.push(`${i}/${t}`);if(!(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)||Cx(e.properties)))return e;if(e.additionalProperties!==!1&&(e.additionalProperties!==void 0&&n.push(`${i}/additionalProperties`),e.additionalProperties=!1),Cx(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]=Cx(a[e])?Ix(a[e]):{type:`null`},t.push(`${i}/properties/${e}`));e.required=n}return e}),madeNullable:t,overridden:n,undroppable:r}}function Rx(e,t){let{schema:n,madeNullable:r,overridden:i,undroppable:a}=Lx(e);return r.length&&Qb.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&&Qb.warn(`OpenAITransport: tool "${t}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${i.join(`, `)}.`),a.length&&Qb.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 zx=Object.freeze({anthropic:`Anthropic`,gemini:`Gemini`,openai:`OpenAI`,chrome:`Chrome`,bedrock:`Bedrock`});Object.freeze([`anthropic`,`gemini`,`openai`]),new Map(Object.entries(zx).map(([e,t])=>[t.toLowerCase(),e]));var Bx=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 Vx=(e,t)=>e===402||t===`BUDGET_EXCEEDED`,Hx=e=>{try{return JSON.parse(e)}catch{return}},Ux=e=>{let t=e?.code;return typeof t==`string`?t:void 0},Wx=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Gx=e=>typeof e==`boolean`?e:void 0,Kx=e=>typeof e==`string`&&e.trim()!==``?e:void 0;function qx(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 Bx(e,Wx(r.budgetUsd)??Wx(i.budgetUsd),Wx(r.spentUsd)??Wx(i.spentUsd),a,{otherVendorAvailable:Gx(r.otherVendorAvailable)??Gx(i.otherVendorAvailable),serverVendor:Kx(r.vendor)??Kx(i.vendor)})}function Jx(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 Yx(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 Xx=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`}),Zx=new Set(Object.values(Xx));function Qx(e){return typeof e==`string`&&Zx.has(e)?e:void 0}let $x=Object.freeze({SIGNED_OUT:`SIGNED_OUT`,ACCESS_DENIED:`ACCESS_DENIED`}),eS=e=>{if(!e||typeof e!=`object`)return!1;let{MESSAGE_TYPE:t,ERROR:n}=e;return t===`MSG_NACK`||Array.isArray(n)},tS=e=>e?.code!==void 0;function nS(e,t,n){if(e!==401&&e!==403||tS(t))return;let r=typeof n==`string`&&n.trim()===``;if(eS(t)||r)return e===401?$x.SIGNED_OUT:$x.ACCESS_DENIED}function rS(e,t){return e===413&&t===void 0}function iS(e){let t=e?.ERROR,n=Array.isArray(t)?t[0]?.TEXT:void 0;return typeof n==`string`&&n?n:void 0}let aS=`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:aS,FALLBACKS_NOT_SUPPORTED:aS,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 oS=e=>e!==Xx.VENDOR_UNREACHABLE;var sS=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 oS(this.code)}};function cS(e){let t=e?.error;return typeof t==`string`&&t?t:void 0}let lS=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]),uS=/(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;var dS=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 coe(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 fS(e,t,n){if(t===400)for(let e of coe(n)){if(!lS.some(t=>t.test(e)))continue;let t=uS.exec(e);return{promptTokens:t?Number(t[1].replace(/,/g,``)):void 0,limitTokens:t?Number(t[2].replace(/,/g,``)):void 0,message:e}}}function loe(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 uoe=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 doe=Object.freeze([/credit balance/i,/usage limit/i,/spend limit/i,/insufficient (credit|funds|balance)/i]),foe=Object.freeze([`authentication_error`,`permission_error`]);function pS(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 poe(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 mS(e){let t=pS(e);if(t?.type){if(foe.includes(t.type))return`auth`;if(t.type===`billing_error`)return`spend`}}function hS(e,t,n){if(t===`PROVIDER_REFUSED`)return poe(n)??mS(n)??`spend`;if(e!==`anthropic`)return;let r=mS(n);if(r)return r;let i=pS(n);if(i?.type===`invalid_request_error`&&i.message){let e=i.message;if(doe.some(t=>t.test(e)))return`spend`}}function gS(e,t,n,r,i){let a=pS(r);return new uoe(e,t,n,a?.type,a?.message??i)}function moe(e){return Object.entries(zx).find(([,t])=>t===e)?.[0]}let _S=12e4,vS=1e3;function hoe(e){let t=(e?.get)?.call(e,`x-should-retry`);return typeof t==`string`&&t.trim().toLowerCase()===`false`}function goe(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*vS);let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function yS(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*vS}}}function _oe(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 voe(e,t){return Math.max(0,e-t)}function bS(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=moe(o),p=(e,t,n)=>(Qb.error(`${o}Transport: the AI service refused the request (${t} ${e})${n?`: ${n}`:``}`),new sS(o,e,t,n)),m=0,h=(e,t)=>{let n=u*2**e,r=_S-m,i=_oe(e,u,t,r);return m+=voe(i,n),t!=null&&i>n?Qb.warn(`${o}Transport: honouring the server's requested retry delay (${Math.round(i)}ms, asked ${Math.round(t)}ms)`):t!=null&&t>n&&Qb.warn(`${o}Transport: declining the server's requested retry delay (asked ${Math.round(t)}ms; the ${_S}ms sequence allowance is spent) — using the ladder's ${Math.round(i)}ms`),Yx(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}=Yb([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=Hx(t),r=hS(f,Ux(n),n);if(r)throw gS(o,r,c.status,n,t||void 0);let i=fS(f,c.status,n);if(i)throw new dS(o,i.promptTokens,i.limitTokens,i.message??(t||void 0));if(Vx(c.status,Ux(n)))throw qx(o,n,t||void 0);let a=Qx(Ux(n));if(a&&a!==Xx.VENDOR_UNREACHABLE)throw p(a,c.status,cS(n));let l=nS(c.status,n,t);if(l)throw p(l,c.status,iS(n)??(t||void 0));if(rS(c.status,n))throw p(Xx.REQUEST_TOO_LARGE,c.status,t||void 0);let u=hoe(c.headers);if(s.includes(c.status)&&!u&&e<5){Qb.warn(`${o}Transport: retryable status ${c.status}, retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,goe(c.headers)||yS(n));continue}throw a?p(a,c.status,cS(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 loe(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=hS(f,t.code,t);if(n)throw gS(o,n,t.status,t,t.error);let r=fS(f,t.status,t);if(r)throw new dS(o,r.promptTokens,r.limitTokens,r.message??t.error);if(Vx(t.status,t.code))throw qx(o,t);let i=Qx(t.code);if(i&&i!==Xx.VENDOR_UNREACHABLE)throw p(i,t.status,cS(t));if(s.includes(t.status)&&e<5){Qb.warn(`${o}Transport: retryable status ${t.status} (err frame), retrying (attempt ${e+1}/5)`),clearTimeout(y),yield h(e,yS(t));continue}throw i?p(i,t.status,cS(t)):Error(`${o} request error ${t.status}: ${t.error??JSON.stringify(t.details)}`)}return yield c.json()}catch(e){throw Jx(e,u.signal,d)}finally{clearTimeout(y),x()}}throw Error(`${o} request failed: max retries exceeded`)})}function yoe(e){if(e&&e!==`auto`)return e===`required`?{type:`any`}:e===`none`?{type:`none`}:{type:`tool`,name:e.tool}}let boe={"claude-fable-5":1e6,"claude-opus-5-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-sonnet-5-5":1e6,"claude-sonnet-5":1e6,"claude-sonnet-4-6":1e6,"claude-haiku-5-5":1e6,"claude-haiku-4-5-20251001":2e5},xS=`emit_structured_response`;function xoe(e){if(!rx.includes(e))throw Error(`AnthropicTransport: unsupported model "${e}". Use one of: ${rx.join(`, `)}.`)}function SS(e){return e===`claude-opus-5-5`||e===`claude-sonnet-5-5`||e===`claude-haiku-5-5`}function Soe(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-opus-4-7`||e===`claude-sonnet-5`||SS(e)}function CS(e){return e!==`claude-opus-5-5`&&e!==`claude-sonnet-5-5`}function wS(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`||e===`claude-haiku-4-5-20251001`||SS(e)}function TS(e){return e!==`claude-haiku-4-5-20251001`}function ES(e){return e===`claude-fable-5`||e===`claude-opus-5-5`}function DS(e){return e===`claude-sonnet-5`||e===`claude-sonnet-5-5`||e===`claude-haiku-5-5`||ES(e)}function OS(e){return e===`claude-sonnet-5-5`?{type:`between_tools`}:{type:`disabled`}}let kS={"claude-opus-5-5":`low`};function Coe(e){return e===`claude-fable-5`||e===`claude-opus-5-5`||e===`claude-sonnet-5-5`}function woe(e){return(rx.includes(e)?jS(e,`off`):void 0)??{type:`disabled`}}function AS(e){return SS(e)}function Toe(e,t){return!AS(e)||!t||t.type===`adaptive`}function jS(e,t){let n=DS(e),r={type:`adaptive`,display:`summarized`};return t===`off`?ES(e)?r:n?OS(e):void 0:t===`auto`||t!==void 0?TS(e)?r:void 0:n?r:void 0}function MS(e){return e===`claude-fable-5`||e===`claude-opus-4-8`||e===`claude-sonnet-5`||SS(e)}let Eoe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Doe(e,t){if(t!==void 0&&t!==`auto`){if(t===`off`)return kS[e];if(MS(e)&&TS(e))return Eoe[t]}}let NS=`anthropic`;var PS=class e{constructor(e,t){this.hash=Ooe,this.length=0,this.fold(JSON.stringify([e??``,(t??[]).map(e=>[e.name,e.description,e.parameters,!!e.enforceSchema])]))}static of(t,n,r){let i=new e(t,n);for(let e of r){i.message(e.role);let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t)i.block(e)}return i.key}message(e){this.fold(`\u0000M:${e}`)}block(e){this.fold(`\u0000B:${JSON.stringify(e,(e,t)=>e===`cache_control`?void 0:t)}`)}get key(){return`${(this.hash>>>0).toString(Aoe)}:${this.length}`}fold(e){for(let t=0;t<e.length;t+=1)this.hash^=e.charCodeAt(t),this.hash=Math.imul(this.hash,koe);this.length+=e.length}};let Ooe=2166136261,koe=16777619,Aoe=16;var FS=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`}},IS=class e{warnIfThinkingUnclampable(e){if(this.warnedThinkingClamped)return;let t=this.clampWarning(e);t&&(this.warnedThinkingClamped=!0,Qb.warn(t))}clampWarning(e){switch(e){case void 0:return;case`off`:return ES(this.model)?kS[this.model]?`AnthropicTransport: thinkingPolicy 'off' approximated — ${this.model} always thinks and rejects an explicit disable, so the turn runs at effort '${kS[this.model]}' instead. It may still think a little, billed as output.`:`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 TS(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!TS(this.model)||!MS(this.model)?`AnthropicTransport: thinkingPolicy '${e}' ignored — ${this.model} predates output_config.effort, so this turn runs at its default posture. Use Opus 4.8 or later, Sonnet 5 or later, Haiku 5.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.warnedToolChoiceDowngraded=!1,this.warnedFallbacksUnsupported=!1,this.warnedUnknownServingModels=/* @__PURE__ */ new Set;let t=e.model??`claude-haiku-4-5-20251001`;xoe(t),this.model=t,t===`claude-sonnet-5`?Qb.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`?Qb.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`?Qb.warn(`AnthropicTransport: using ${t} — significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`):t===`claude-opus-5-5`?Qb.warn(`AnthropicTransport: using claude-opus-5-5 — Opus tier ($4 / $20 per MTok) with thinking always on (effort defaults to medium). Reserve for tasks where Sonnet reliability is insufficient.`):t===`claude-sonnet-5-5`?Qb.warn(`AnthropicTransport: using claude-sonnet-5-5 — standard Sonnet tier ($2 / $10 per MTok), 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-fable-5`&&Qb.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??(SS(t)?64e3:4096),this.thinkingBlockBinding=e.thinkingBlockBinding??`drop_block`}getConfig(){return{provider:`anthropic`,model:this.model,contextLimit:boe[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&&wS(this.model),s=r!=null&&!o;if(o)a.output_config=Object.assign(Object.assign({},a.output_config),{format:{type:`json_schema`,schema:r}});else if(s){if(!CS(this.model))throw Error(`AnthropicTransport: ${this.model} rejects forced tool_choice and must be listed in supportsNativeStructuredOutput.`);a.tools=[{name:xS,description:`Emit the structured response that matches the required schema.`,input_schema:r}],a.tool_choice={type:`tool`,name:xS}}DS(this.model)&&!ES(this.model)&&(a.thinking=OS(this.model));let c=yield this.post(a);if(s){let e=(c.content??[]).find(e=>e.type===`tool_use`&&e.name===xS);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=n?.fallbacks;r?.length&&!Coe(this.model)&&(this.warnedFallbacksUnsupported||(this.warnedFallbacksUnsupported=!0,Qb.warn(`AnthropicTransport: ${this.model} does not support server-side fallbacks; sending the request without them.`)),r=void 0);let i=/* @__PURE__ */ new Set([this.model,...(r??[]).map(e=>e.model)]),a=jS(this.model,n?.thinkingPolicy),o=this.toAnthropicMessages(e,t,n?.attachments,i,Toe(this.model,a),this.replayFingerprint(n)),s={model:this.model,max_tokens:n?.maxTokens??this.maxTokens,messages:o};n?.systemPrompt&&(s.system=n.systemPrompt),n?.tools?.length&&(s.tools=n.tools.map(e=>Object.assign({name:e.name,description:e.description,input_schema:e.enforceSchema?Ax(e.parameters,e.name):e.parameters},e.enforceSchema?{strict:!0}:{})));let c=s.tools?.length?this.applyToolChoice(s,n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy),a&&(s.thinking=this.withBlockBinding(a));let l=Doe(this.model,n?.thinkingPolicy);l&&(s.output_config=Object.assign(Object.assign({},s.output_config),{effort:l}));let u=a?.type===`adaptive`;if(n?.temperature!=null&&!Soe(this.model)&&!u&&(s.temperature=cx(n.temperature,{defaultTemp:1,maxTemp:1})),n?.responseSchema&&wS(this.model)&&(s.output_config=Object.assign(Object.assign({},s.output_config),{format:{type:`json_schema`,schema:n.responseSchema}})),r?.length){let e=s.thinking?.type===`between_tools`;s.fallbacks=r.map(t=>Object.assign(Object.assign({model:t.model},t.maxTokens==null?{}:{max_tokens:t.maxTokens}),e?{thinking:woe(t.model)}:{}))}n?.cachePolicy&&this.applyCacheControl(s,n.cachePolicy),c&&this.appendTailContext(s,c),n?.tailContext&&this.appendTailContext(s,n.tailContext);let d=yield this.post(s,n?.signal),f=this.fromAnthropicResponse(d,s.max_tokens,this.sentPrefix(n,s.messages));return c&&f.responseMeta&&(f.responseMeta.toolChoiceDowngraded=!0,f.responseMeta.toolChoiceNote=c),f})}replayFingerprint(e){return AS(this.model)?new PS(e?.systemPrompt,e?.tools):void 0}sentPrefix(e,t){return AS(this.model)?PS.of(e?.systemPrompt,e?.tools,t):void 0}applyToolChoice(e,t){let n=yoe(t);if(n){if((n.type===`any`||n.type===`tool`)&&!CS(this.model))return this.downgradeForcedToolChoice(n);e.tool_choice=n}}withBlockBinding(e){return e.type!==`adaptive`||!AS(this.model)||this.thinkingBlockBinding===`omit`?e:Object.assign(Object.assign({},e),{block_binding:{prefix_mismatch_behavior:this.thinkingBlockBinding}})}downgradeForcedToolChoice(e){return this.warnedToolChoiceDowngraded||(this.warnedToolChoiceDowngraded=!0,Qb.warn(`AnthropicTransport: ${this.model} rejects a forced tool_choice; sending 'auto' with an instruction to call the tool instead. A reply may still come back without a tool call — check responseMeta.toolChoiceDowngraded.`)),e.type===`tool`&&e.name?`<system-reminder>Respond to this turn by calling the \`${e.name}\` tool. Do not reply with text alone.</system-reminder>`:`<system-reminder>Respond to this turn by calling one of your tools. Do not reply with text alone.</system-reminder>`}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}=px(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]),i=!0,a){let o=[],s=(e,t)=>{let n=o[o.length-1];n&&n.role===e&&Array.isArray(n.content)?n.content.push(t):(o.push({role:e,content:[t]}),a?.message(e)),a?.block(t)},c=e=>{let t=[],n=[];for(let r of e)r.kind===`image`?t.push({type:`image`,source:{type:`base64`,media_type:ax(r.mimeType),data:ox(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.role===`assistant`&&t.responseMeta?.toolChoiceNote&&s(`user`,{type:`text`,text:t.responseMeta.toolChoiceNote}),t.toolResult){let e=t.toolResult.attachments??[];s(`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:ax(e.mimeType),data:ox(e.data)}}))]:t.toolResult.content});continue}if(t.toolCalls?.length){for(let e of this.reasoningToReplay(t.toolCalls[0],r,i,a?.key))s(`assistant`,e);t.content&&s(`assistant`,{type:`text`,text:t.content});for(let e of t.toolCalls)s(`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}=c(t.attachments);for(let t of n)s(e,t);t.content&&s(e,{type:`text`,text:t.content});for(let t of r)s(e,t)}else t.content&&s(e,{type:`text`,text:t.content})}if(t||n?.length){let{images:e,texts:r}=c(n??[]);for(let t of e)s(`user`,t);t&&s(`user`,{type:`text`,text:t});for(let e of r)s(`user`,e)}return o}reasoningToReplay(e,t,n=!0,r){let i=e.providerMetadata?.[NS];if(!i)return[];let a=i.fallbacks??[],o=i.requestedModel===this.model&&t.has(i.model),s=i.model===this.model||o,c=r===void 0||i.prefixKey===r;return[...a,...s&&n&&c?i.reasoning??[]:[]]}servingModel(e){let t=e.model;return!t||t===this.model?this.model:rx.includes(t)?t:(this.warnedUnknownServingModels.has(t)||(this.warnedUnknownServingModels.add(t),Qb.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,n){let r,i,a,o,s,c=this.servingModel(e);if(e.usage){let t=e.usage.input_tokens??0,n=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`;s=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 s=this.isUnbilledRefusal({},e.usage,e.stop_reason===`refusal`)?0:this.costAttempt(c,e.usage);r=t+n+d,a=n,o=d,e.usage.output_tokens!=null&&(i=e.usage.output_tokens)}let l=e.content??[],u=[],d=[],f=[],p=[],m=l.map(e=>e.type).lastIndexOf(`fallback`),h=l.filter(e=>e.type===`fallback`);for(let[e,t]of l.entries()){let n=e>m;t.type===`tool_use`?n&&u.push({id:t.id,name:t.name,args:t.input??{}}):t.type===`thinking`?(n&&p.push(t),d.push(t.thinking)):t.type===`redacted_thinking`?n&&p.push(t):t.type===`text`&&f.push(t.text)}if(u.length>0&&(p.length>0||h.length>0)){let e={reasoning:p,model:c,requestedModel:this.model};h.length>0&&(e.fallbacks=h),n!==void 0&&(e.prefixKey=n),u[0].providerMetadata=Object.assign(Object.assign({},u[0].providerMetadata),{[NS]:e})}if(e.stop_reason===`max_tokens`&&u.length>0)throw new FS(this.model,t,i,u.map(e=>e.name));let g=d.join(``)||void 0,_=u.length>0?{role:`assistant`,content:f.join(``),reasoning:g,toolCalls:u}:{role:`assistant`,content:f.join(``),reasoning:g};r!=null&&(_.inputTokens=r),i!=null&&(_.outputTokens=i),a!=null&&(_.cacheReadTokens=a),o!=null&&(_.cacheWriteTokens=o),s!=null&&(_.cost=s),_.model=c;let v={parts:{functionCall:l.filter(e=>e.type===`tool_use`).length,thought:l.filter(e=>e.type===`thinking`||e.type===`redacted_thinking`).length,text:l.filter(e=>e.type===`text`).length}};if(e.stop_reason&&(v.finishReason=e.stop_reason),e.input_transformations?.length){v.inputTransformations=e.input_transformations.map(e=>Object.assign(Object.assign({type:e.type},e.path==null?{}:{path:e.path}),e.reason==null?{}:{reason:e.reason}));let t=e.input_transformations.filter(e=>e.type===`thinking_dropped`);t.length&&Qb.debug(`AnthropicTransport: ${t.length} thinking block(s) dropped by ${e.model??this.model}: ${t.map(e=>`${e.path??`?`} (${e.reason??`unknown`})`).join(`, `)}`)}return _.responseMeta=v,_}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(),o=[t.fallbacks?.length?`server-side-fallback-2026-06-01`:void 0,t.thinking?.type===`adaptive`&&t.thinking.block_binding?`thinking-binding-controls-2026-08-01`:void 0].filter(e=>!!e);return yield bS({url:r,headers:o.length?Object.assign(Object.assign({},i),{"anthropic-beta":[i[`anthropic-beta`],...o].filter(Boolean).join(`,`)}):i,body:t,credentials:a,vendorLabel:zx.anthropic,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};IS.TOKENS_PER_MILLION=1e6,IS.COST_DECIMAL_PLACES=6,IS.RATE_LIMIT_STATUS=429,IS.SERVICE_UNAVAILABLE_STATUS=503,IS.OVERLOADED_STATUS=529,IS.RETRYABLE_STATUSES=[IS.RATE_LIMIT_STATUS,IS.SERVICE_UNAVAILABLE_STATUS,IS.OVERLOADED_STATUS],IS.BACKOFF_BASE_MS=1e3;let LS=`default_api.`,joe=/print\(\s*$/;var Moe=class{constructor(e){this.src=e,this.pos=0}parse(){let e=this.src.indexOf(LS);e===-1&&this.bail();let t=joe.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(LS);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 Noe(e,t){if(!e)return null;let n;try{n=new Moe(e).parse()}catch{return null}return t.has(n.name)?n:null}let Poe=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,Foe={"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 Ioe(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Loe(e){if(!nx.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${nx.join(`, `)}.`)}let Roe={"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.`},RS=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],zoe=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],Boe=[`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],zS=[`minimal`,`low`,`medium`,`high`],BS={"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 VS(e,t){if(!e?.length||e.includes(t))return t;let n=zS.indexOf(t),r=e=>Math.abs(zS.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let HS={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},US=e=>e!==void 0&&e!==`auto`&&e!==`off`;function Voe(e,t){if(US(t)){let n=BS[e];if(n)return{includeThoughts:!0,thinkingLevel:VS(n,HS[t])}}return t===`off`&&RS.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&RS.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let WS=`gemini`;function GS(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:ax(r.mimeType),data:ox(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var Hoe=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},KS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!RS.includes(this.model)){this.warnedThinkingClamped=!0,Qb.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(US(e)){let t=BS[this.model];if(!t){this.warnedThinkingClamped=!0,Qb.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=HS[e],r=VS(t,n);r!==n&&(this.warnedThinkingClamped=!0,Qb.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`;Loe(t),this.model=t;let n=Roe[t];n&&Qb.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:Foe[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:Px(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Ioe(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:Voe(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&&zoe.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=cx(n.temperature,{defaultTemp:1,maxTemp:2}));let l=new Set((n?.tools??[]).map(e=>e.name)),u=Boe.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:Px(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=gx(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:ax(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?.[WS],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}=GS(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}=GS(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:{[WS]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=Noe(c.finishMessage,t);if(!e)throw new Hoe(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 FS(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};Qb.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:`${Poe(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 bS({url:r,headers:a,body:i,credentials:o,vendorLabel:zx.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}};KS.TOKENS_PER_MILLION=1e6,KS.COST_DECIMAL_PLACES=6,KS.RATE_LIMIT_STATUS=429,KS.SERVICE_UNAVAILABLE_STATUS=503,KS.BAD_GATEWAY_STATUS=502,KS.RETRYABLE_STATUSES=[KS.RATE_LIMIT_STATUS,KS.SERVICE_UNAVAILABLE_STATUS,KS.BAD_GATEWAY_STATUS],KS.BACKOFF_BASE_MS=1e3;let Uoe={"gpt-6-astra":922e3,"gpt-6.1-sol":105e4,"gpt-6.1-terra":105e4,"gpt-6-sol":105e4,"gpt-6-luna":105e4},qS=[`gpt-6.1-terra`,`gpt-6-luna`],Woe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Goe(e,t){if(t!==void 0&&t!==`auto`)return t===`off`?qS.includes(e)?`none`:`low`:Woe[t]}function Koe(e){if(e&&e!==`auto`)return e===`required`||e===`none`?e:{type:`function`,name:e.tool}}function qoe(e){let t=e.enforceSchema?Rx(e.parameters,e.name):e.parameters;return{type:`function`,name:e.name,description:e.description,parameters:t,strict:!!e.enforceSchema}}function Joe(e){if(!ix.includes(e))throw Error(`OpenAITransport: unsupported model "${e}". Use one of: ${ix.join(`, `)}.`)}let Yoe={"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.`},JS=`openai`,YS=Object.freeze({mode:`explicit`});function Xoe(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:tse(s.arguments)});return{reasoning:t,summaryParts:n,textParts:r,refusals:i,toolCalls:a,phase:o}}function XS(e){let t={type:`input_image`,image_url:`data:${ax(e.mimeType)};base64,${ox(e.data)}`};return e.detail&&(t.detail=e.detail===`medium`?`auto`:e.detail),t}function ZS(e,t){let n=[];for(let e of t)e.kind===`image`&&n.push(XS(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 Zoe(e){return e.providerMetadata?.[JS]??e.toolCalls?.[0]?.providerMetadata?.[JS]}function Qoe(e){let{status:t}=e;return rd(e,[`status`])}var QS=class e{constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=/* @__PURE__ */ new Set;let t=e.model??`gpt-6-luna`;Joe(t),this.model=t;let n=Yoe[t];n&&Qb.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:Uoe[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=ese(t?.tools);for(let t of e.toolCalls??[]){let e=n.get(t.name);e&&$S(t.args,e)}if(!t?.responseSchema||!e.content)return;let{madeNullable:r}=Lx(t.responseSchema);if(r.length)try{let t=JSON.parse(e.content);$S(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=YS),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(qoe);let e=Koe(n.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingClamped(n?.thinkingPolicy);let o=Goe(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=cx(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:Lx(n.responseSchema).schema,strict:!0}}),a}warnIfThinkingClamped(e){e&&!this.warnedThinkingClamped.has(e)&&(e===`off`&&!qS.includes(this.model)?(this.warnedThinkingClamped.add(e),Qb.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),Qb.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=ZS(t.content,t.attachments??[]);e.length&&r.push({type:`message`,role:`user`,content:e});continue}let e=Zoe(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(Qoe(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=ZS(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(XS)]}}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:YS}),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}=yx(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}=Xoe(r),u={model:this.model};i.length&&(u.reasoning=i),l&&(u.phase=l);let d={[JS]:u};c.length&&(c[0].providerMetadata=d);let f=o.join(``),p=a.join(`