@graphcore/react-kernel 0.2.3 → 0.3.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.
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=s(c,1);c=s(c);let u=require("react/jsx-runtime"),d=require("react-router-dom"),f=require("react-dom");var p=null,m=null,h=null,g=``;function _(e,t,n){p=e,m=t,h=n??null}function v(e){let t=(e??``).trim().replace(/^\/+|\/+$/g,``);return t?`/${t}`:``}function y(e){g=v(e)}function b(){return g}function x(e){return e===`/`?g||`/`:`${g}${e}`}function S(){if(!p)throw Error(`GraphCoreProvider is missing required apiUrl config.`);return p}function C(){if(!m)throw Error(`GraphCoreProvider is missing required wsUrl config.`);return m}function w(){return h!==null}var T=(0,c.createContext)(null),E=T.Provider,D=()=>(0,c.useContext)(T),O=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},k=(e=>e?O(e):O);function A(e,t,n){let r=(0,c.useRef)(void 0);return(0,c.useSyncExternalStore)(e.subscribe,()=>{let i=t(e.getState());return n&&r.current!==void 0&&n(r.current,i)?r.current:(r.current=i,i)},()=>t(e.getInitialState()))}var j=e=>e?Array.isArray(e)?e.reduce((e,t)=>(t?.entity_id&&(e[t.entity_id]=t),e),{}):Object.entries(e).reduce((e,[t,n])=>((n?.entity_id||t)&&(e[n.entity_id||t]=n),e),{}):{},M=(e,t)=>!e?.deleted&&!e?.forbidden&&!t?.forbidden&&typeof e?.version==`number`&&typeof t?.version==`number`&&e.version<t.version,N=(e,t={})=>{let n=e?.entity_type_id,r=Array.isArray(t.types)?t.types.filter(Boolean):[],i=Array.isArray(t.excludeTypes)?t.excludeTypes.filter(Boolean):[];return!(r.length>0&&!r.includes(n)||i.length>0&&i.includes(n))},ee=(e,t)=>{if(!t)return[];let n=e.entitiesById[t];return Array.isArray(n?.children_ids)?n.children_ids.filter(Boolean):[]},te=(e,t,n={})=>{if(!t||n.enabled===!1)return null;let r=(i,a=new Set)=>{if(a.has(i))return null;a.add(i);let o=e.entitiesById[i];if(!o)return null;let s=ee(e,i).reduce((e,t)=>{let n=r(t,new Set(a));return n&&(e[t]=n),e},{});return N(o,n)||Object.keys(s).length>0||n.includeRoot&&i===t?{entity:o,children:s}:null};return r(t)},P=k(()=>({entitiesById:{},entityIds:[],requestedEntityIds:new Set,notFoundEntityIds:new Set})),F=(e,t)=>A(P,e,t),I={getEntityIds(){return P.getState().entityIds},readEntity(e){return e?P.getState().entitiesById[e]??null:null},readEntities(e){let t=P.getState().entitiesById;return(e||[]).map(e=>e?t[e]??null:null)},readChildren(e,t={}){if(!e||t.enabled===!1)return[];let n=P.getState();return ee(n,e).map(e=>n.entitiesById[e]??null).filter(e=>!!e&&!e.forbidden).filter(e=>N(e,t))},readRecursiveChildren(e,t={}){return te(P.getState(),e,t)},mergeEntities(e){let t=j(e),n=new Set(P.getState().entityIds);return P.setState(e=>{let r={...e.entitiesById},i=new Set(e.requestedEntityIds),a=new Set(e.notFoundEntityIds);return Object.entries(t).forEach(([e,t])=>{i.delete(e),a.delete(e),!M(t,r[e])&&(t?.deleted===!0?(delete r[e],n.delete(e)):(r[e]=t,n.add(e)))}),{entitiesById:r,entityIds:[...n],requestedEntityIds:i,notFoundEntityIds:a}}),P.getState().entityIds},removeEntity(e){e&&P.setState(t=>{if(!t.entitiesById[e])return t;let n={...t.entitiesById};delete n[e];let r=new Set(t.requestedEntityIds),i=new Set(t.notFoundEntityIds);return r.delete(e),i.delete(e),{entitiesById:n,entityIds:t.entityIds.filter(t=>t!==e),requestedEntityIds:r,notFoundEntityIds:i}})},clearEntities(){P.setState({entitiesById:{},entityIds:[],requestedEntityIds:new Set,notFoundEntityIds:new Set})},markRequested(e){e&&P.setState(t=>{let n=new Set(t.requestedEntityIds),r=new Set(t.notFoundEntityIds);return n.add(e),r.delete(e),{requestedEntityIds:n,notFoundEntityIds:r}})},clearRequestedEntity(e){e&&P.setState(t=>{if(!t.requestedEntityIds.has(e))return t;let n=new Set(t.requestedEntityIds);return n.delete(e),{requestedEntityIds:n}})},clearRequestedEntities(){P.setState({requestedEntityIds:new Set})},isRequested(e){return P.getState().requestedEntityIds.has(e)},markNotFound(e){e&&P.setState(t=>{let n=new Set(t.requestedEntityIds),r=new Set(t.notFoundEntityIds);return n.delete(e),r.add(e),{requestedEntityIds:n,notFoundEntityIds:r}})},isNotFound(e){return P.getState().notFoundEntityIds.has(e)},clearEntityFlags(e){e?P.setState(t=>{let n=new Set(t.requestedEntityIds),r=new Set(t.notFoundEntityIds);return n.delete(e),r.delete(e),{requestedEntityIds:n,notFoundEntityIds:r}}):P.setState({requestedEntityIds:new Set,notFoundEntityIds:new Set})}},ne=e=>e;function L(e,t=ne){let n=l.default.useSyncExternalStore(e.subscribe,l.default.useCallback(()=>t(e.getState()),[e,t]),l.default.useCallback(()=>t(e.getInitialState()),[e,t]));return l.default.useDebugValue(n),n}var re=k(()=>`idle`),ie=e=>{re.setState(e)},R=()=>L(re,e=>e),ae=class extends Error{constructor(e,t={}){super(e),this.name=`StrategyError`,this.code=t.code??void 0,this.details=t.details??{},this.strategyRequestId=t.strategyRequestId??void 0}},z=new Set;function oe(e){return z.add(e),()=>{z.delete(e)}}function se(e){z.forEach(t=>t(e))}var ce=new Set;function le(e){return ce.add(e),()=>{ce.delete(e)}}function ue(e){ce.forEach(t=>t(e))}var de=()=>({isAuthenticated:!1,token:null,principalEntityId:null,username:null,isLoading:!1,error:null}),B=k(()=>({...de(),isLoading:!0})),V=e=>{B.setState(e)},fe=()=>L(B),pe=class extends Error{};pe.prototype.name=`InvalidTokenError`;function me(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function he(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return me(t)}catch{return atob(t)}}function ge(e,t){if(typeof e!=`string`)throw new pe(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new pe(`Invalid token specified: missing part #${n+1}`);let i;try{i=he(r)}catch(e){throw new pe(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new pe(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var _e={debug:()=>void 0,info:()=>void 0,warn:()=>void 0,error:()=>void 0},H,U,ve=(e=>(e[e.NONE=0]=`NONE`,e[e.ERROR=1]=`ERROR`,e[e.WARN=2]=`WARN`,e[e.INFO=3]=`INFO`,e[e.DEBUG=4]=`DEBUG`,e))(ve||{});(e=>{function t(){H=3,U=_e}e.reset=t;function n(e){if(!(0<=e&&e<=4))throw Error(`Invalid log level`);H=e}e.setLevel=n;function r(e){U=e}e.setLogger=r})(ve||={});var W=class e{constructor(e){this._name=e}debug(...t){H>=4&&U.debug(e._format(this._name,this._method),...t)}info(...t){H>=3&&U.info(e._format(this._name,this._method),...t)}warn(...t){H>=2&&U.warn(e._format(this._name,this._method),...t)}error(...t){H>=1&&U.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){let t=Object.create(this);return t._method=e,t.debug(`begin`),t}static createStatic(t,n){let r=new e(`${t}.${n}`);return r.debug(`begin`),r}static _format(e,t){let n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){H>=4&&U.debug(e._format(t),...n)}static info(t,...n){H>=3&&U.info(e._format(t),...n)}static warn(t,...n){H>=2&&U.warn(e._format(t),...n)}static error(t,...n){H>=1&&U.error(e._format(t),...n)}};ve.reset();var G=class{static decode(e){try{return ge(e)}catch(e){throw W.error(`JwtUtils.decode`,e),e}}static async generateSignedJwt(e,t,n){let r=`${K.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e)))}.${K.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:`ECDSA`,hash:{name:`SHA-256`}},n,new TextEncoder().encode(r));return`${r}.${K.encodeBase64Url(new Uint8Array(i))}`}static async generateSignedJwtWithHmac(e,t,n){let r=`${K.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e)))}.${K.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign(`HMAC`,n,new TextEncoder().encode(r));return`${r}.${K.encodeBase64Url(new Uint8Array(i))}`}},ye=`10000000-1000-4000-8000-100000000000`,be=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join(``)),xe=class e{static _randomWord(){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return ye.replace(/[018]/g,t=>(+t^e._randomWord()&15>>t/4).toString(16)).replace(/-/g,``)}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw Error(`Crypto.subtle is available only in secure contexts (HTTPS).`);try{let t=new TextEncoder().encode(e);return be(await crypto.subtle.digest(`SHA-256`,t)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}catch(e){throw W.error(`CryptoUtils.generateCodeChallenge`,e),e}}static generateBasicAuth(e,t){return be(new TextEncoder().encode([e,t].join(`:`)))}static async hash(e,t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case`RSA`:n={e:t.e,kty:t.kty,n:t.n};break;case`EC`:n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case`OKP`:n={crv:t.crv,kty:t.kty,x:t.x};break;case`oct`:n={crv:t.k,kty:t.kty};break;default:throw Error(`Unknown jwk type`)}let r=await e.hash(`SHA-256`,JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:i,nonce:a}){let o,s,c={jti:window.crypto.randomUUID(),htm:r??`GET`,htu:t,iat:Math.floor(Date.now()/1e3)};n&&(o=await e.hash(`SHA-256`,n),s=e.encodeBase64Url(o),c.ath=s),a&&(c.nonce=a);try{let e=await crypto.subtle.exportKey(`jwk`,i.publicKey),t={alg:`ES256`,typ:`dpop+jwt`,jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await G.generateSignedJwt(t,c,i.privateKey)}catch(e){throw e instanceof TypeError?Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{let n=await crypto.subtle.exportKey(`jwk`,t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(e){throw e instanceof TypeError?Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!1,[`sign`,`verify`])}static async generateClientAssertionJwt(t,n,r,i=`HS256`){let a=Math.floor(Date.now()/1e3),o={alg:i,typ:`JWT`},s={iss:t,sub:t,aud:r,jti:e.generateUUIDv4(),exp:a+300,iat:a},c={HS256:`SHA-256`,HS384:`SHA-384`,HS512:`SHA-512`}[i];if(!c)throw Error(`Unsupported algorithm: ${i}. Supported algorithms are: HS256, HS384, HS512`);let l=new TextEncoder,u=await crypto.subtle.importKey(`raw`,l.encode(n),{name:`HMAC`,hash:c},!1,[`sign`]);return await G.generateSignedJwtWithHmac(o,s,u)}};xe.encodeBase64Url=e=>be(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`);var K=xe,Se=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new W(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){let t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug(`raise:`,...e);for(let t of this._callbacks)await t(...e)}},Ce=class{static center({...e}){return e.width??=[800,720,600,480].find(e=>e<=window.outerWidth/1.618)??360,e.left??=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2)),e.height!=null&&(e.top??=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2))),e}static serialize(e){return Object.entries(e).filter(([,e])=>e!=null).map(([e,t])=>`${e}=${typeof t==`boolean`?t?`yes`:`no`:t}`).join(`,`)}},we=class e extends Se{constructor(){super(...arguments),this._logger=new W(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{let t=this._expiration-e.getEpochTime();this._logger.debug(`timer completes in`,t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){let n=this._logger.create(`init`);t=Math.max(Math.floor(t),1);let r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle){n.debug(`skipping since already initialized for expiration at`,this.expiration);return}this.cancel(),n.debug(`using duration`,t),this._expiration=r;let i=Math.min(t,5);this._timerHandle=setInterval(this._callback,i*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create(`cancel`),this._timerHandle&&=(clearInterval(this._timerHandle),null)}},Te=class{static readParams(e,t=`query`){if(!e)throw TypeError(`Invalid URL`);let n=new URL(e,`http://127.0.0.1`)[t===`fragment`?`hash`:`search`];return new URLSearchParams(n.slice(1))}},Ee=`;`,De=class extends Error{constructor(e,t){if(super(e.error_description||e.error||``),this.form=t,this.name=`ErrorResponse`,!e.error)throw W.error(`ErrorResponse`,`No error passed`),Error(`No error passed`);this.error=e.error,this.error_description=e.error_description??null,this.error_uri=e.error_uri??null,this.state=e.userState,this.session_state=e.session_state??null,this.url_state=e.url_state}},Oe=class extends Error{constructor(e){super(e),this.name=`ErrorTimeout`}},ke=class{constructor(e){this._logger=new W(`AccessTokenEvents`),this._expiringTimer=new we(`Access token expiring`),this._expiredTimer=new we(`Access token expired`),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){let t=this._logger.create(`load`);if(e.access_token&&e.expires_in!==void 0){let n=e.expires_in;if(t.debug(`access token present, remaining duration:`,n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug(`registering expiring timer, raising in`,e,`seconds`),this._expiringTimer.init(e)}else t.debug(`canceling existing expiring timer because we're past expiration.`),this._expiringTimer.cancel();let r=n+1;t.debug(`registering expired timer, raising in`,r,`seconds`),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug(`unload: canceling existing access token timers`),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},Ae=class{constructor(e,t,n,r,i){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=i,this._logger=new W(`CheckSessionIFrame`),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data===`error`?(this._logger.error(`error message from check session op iframe`),this._stopOnError&&this.stop()):e.data===`changed`?(this._logger.debug(`changed message from check session op iframe`),this.stop(),this._callback()):this._logger.debug(e.data+` message from check session op iframe`))};let a=new URL(n);this._frame_origin=a.origin,this._frame=window.document.createElement(`iframe`),this._frame.style.visibility=`hidden`,this._frame.style.position=`fixed`,this._frame.style.left=`-1000px`,this._frame.style.top=`0`,this._frame.width=`0`,this._frame.height=`0`,this._frame.src=a.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener(`message`,this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create(`start`),this.stop(),this._session_state=e;let t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+` `+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._logger.create(`stop`),this._session_state=null,this._timer&&=(clearInterval(this._timer),null)}},je=class{constructor(){this._logger=new W(`InMemoryWebStorage`),this._data={}}clear(){this._logger.create(`clear`),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},Me=class extends Error{constructor(e,t){super(t),this.name=`ErrorDPoPNonce`,this.nonce=e}},Ne=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new W(`JsonService`),this._contentTypes=[],this._contentTypes.push(...e,`application/json`),t&&this._contentTypes.push(`application/jwt`)}async fetchWithTimeout(e,t={}){let{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);let i=new AbortController,a=setTimeout(()=>i.abort(),n*1e3);try{return await fetch(e,{...t,signal:i.signal})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?new Oe(`Network timed out`):e}finally{clearTimeout(a)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){let i=this._logger.create(`getJson`),a={Accept:this._contentTypes.join(`, `)};t&&(i.debug(`token passed, setting Authorization header`),a.Authorization=`Bearer `+t),this._appendExtraHeaders(a);let o;try{i.debug(`url:`,e),o=await this.fetchWithTimeout(e,{method:`GET`,headers:a,timeoutInSeconds:r,credentials:n})}catch(e){throw i.error(`Network Error`),e}i.debug(`HTTP response received, status`,o.status);let s=o.headers.get(`Content-Type`);if(s&&!this._contentTypes.find(e=>s.startsWith(e))&&i.throw(Error(`Invalid response Content-Type: ${s??`undefined`}, from URL: ${e}`)),o.ok&&this._jwtHandler&&s?.startsWith(`application/jwt`))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){throw i.error(`Error parsing JSON response`,e),o.ok?e:Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw i.error(`Error from server:`,c),c.error?new De(c):Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`);return c}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:i,extraHeaders:a}){let o=this._logger.create(`postForm`),s={Accept:this._contentTypes.join(`, `),"Content-Type":`application/x-www-form-urlencoded`,...a};n!==void 0&&(s.Authorization=`Basic `+n),this._appendExtraHeaders(s);let c;try{o.debug(`url:`,e),c=await this.fetchWithTimeout(e,{method:`POST`,headers:s,body:t,timeoutInSeconds:r,credentials:i})}catch(e){throw o.error(`Network error`),e}o.debug(`HTTP response received, status`,c.status);let l=c.headers.get(`Content-Type`);if(l&&!this._contentTypes.find(e=>l.startsWith(e)))throw Error(`Invalid response Content-Type: ${l??`undefined`}, from URL: ${e}`);let u=await c.text(),d={};if(u)try{d=JSON.parse(u)}catch(e){throw o.error(`Error parsing JSON response`,e),c.ok?e:Error(`${c.statusText} (${c.status})`)}if(!c.ok)throw o.error(`Error from server:`,d),c.headers.has(`dpop-nonce`)?new Me(c.headers.get(`dpop-nonce`),`${JSON.stringify(d)}`):d.error?new De(d,t):Error(`${c.statusText} (${c.status}): ${JSON.stringify(d)}`);return d}_appendExtraHeaders(e){let t=this._logger.create(`appendExtraHeaders`),n=Object.keys(this._extraHeaders),r=[`accept`,`content-type`],i=[`authorization`];n.length!==0&&n.forEach(n=>{if(r.includes(n.toLocaleLowerCase())){t.warn(`Protected header could not be set`,n,r);return}if(i.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n)){t.warn(`Header could not be overridden`,n,i);return}let a=typeof this._extraHeaders[n]==`function`?this._extraHeaders[n]():this._extraHeaders[n];a&&a!==``&&(e[n]=a)})}},Pe=class{constructor(e){this._settings=e,this._logger=new W(`MetadataService`),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Ne([`application/jwk-set+json`],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug(`using signingKeys from settings`),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug(`using metadata from settings`),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug(`using fetchRequestCredentials from settings`),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){let e=this._logger.create(`getMetadata`);if(this._metadata)return e.debug(`using cached values`),this._metadata;if(!this._metadataUrl)throw e.throw(Error(`No authority or metadataUrl configured on settings`)),null;e.debug(`getting metadata from`,this._metadataUrl);let t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug(`merging remote JSON with seed metadata`),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty(`issuer`)}getAuthorizationEndpoint(){return this._getMetadataProperty(`authorization_endpoint`)}getUserInfoEndpoint(){return this._getMetadataProperty(`userinfo_endpoint`)}getTokenEndpoint(e=!0){return this._getMetadataProperty(`token_endpoint`,e)}getCheckSessionIframe(){return this._getMetadataProperty(`check_session_iframe`,!0)}getEndSessionEndpoint(){return this._getMetadataProperty(`end_session_endpoint`,!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty(`revocation_endpoint`,e)}getKeysEndpoint(e=!0){return this._getMetadataProperty(`jwks_uri`,e)}async _getMetadataProperty(e,t=!1){let n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug(`resolved`),r[e]===void 0){if(t===!0){n.warn(`Metadata does not contain optional property`);return}n.throw(Error(`Metadata does not contain property `+e))}return r[e]}async getSigningKeys(){let e=this._logger.create(`getSigningKeys`);if(this._signingKeys)return e.debug(`returning signingKeys from cache`),this._signingKeys;let t=await this.getKeysEndpoint(!1);e.debug(`got jwks_uri`,t);let n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug(`got key set`,n),!Array.isArray(n.keys))throw e.throw(Error(`Missing keys on keyset`)),null;return this._signingKeys=n.keys,this._signingKeys}},Fe=class{constructor({prefix:e=`oidc.`,store:t=localStorage}={}){this._logger=new W(`WebStorageStateStore`),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create(`getAllKeys`);let e=await this._store.length,t=[];for(let n=0;n<e;n++){let e=await this._store.key(n);e&&e.indexOf(this._prefix)===0&&t.push(e.substr(this._prefix.length))}return t}},Ie=`code`,Le=`openid`,Re=`client_secret_post`,ze=900,Be=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:i,client_id:a,client_secret:o,response_type:s=Ie,scope:c=Le,redirect_uri:l,post_logout_redirect_uri:u,client_authentication:d=Re,token_endpoint_auth_signing_alg:f=`HS256`,prompt:p,display:m,max_age:h,ui_locales:g,acr_values:_,resource:v,response_mode:y,filterProtocolClaims:b=!0,loadUserInfo:x=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:C=ze,mergeClaimsStrategy:w={array:`replace`},disablePKCE:T=!1,stateStore:E,revokeTokenAdditionalContentTypes:D,fetchRequestCredentials:O,refreshTokenAllowedScope:k,extraQueryParams:A={},extraTokenParams:j={},extraHeaders:M={},dpop:N,omitScopeWhenRequesting:ee=!1}){if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith(`/`)||(this.metadataUrl+=`/`),this.metadataUrl+=`.well-known/openid-configuration`)),this.metadata=n,this.metadataSeed=i,this.signingKeys=r,this.client_id=a,this.client_secret=o,this.response_type=s,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=u,this.client_authentication=d,this.token_endpoint_auth_signing_alg=f,this.prompt=p,this.display=m,this.max_age=h,this.ui_locales=g,this.acr_values=_,this.resource=v,this.response_mode=y,this.filterProtocolClaims=b??!0,this.loadUserInfo=!!x,this.staleStateAgeInSeconds=C,this.mergeClaimsStrategy=w,this.omitScopeWhenRequesting=ee,this.disablePKCE=!!T,this.revokeTokenAdditionalContentTypes=D,this.fetchRequestCredentials=O||`same-origin`,this.requestTimeoutInSeconds=S,E)this.stateStore=E;else{let e=typeof window<`u`?window.localStorage:new je;this.stateStore=new Fe({store:e})}if(this.refreshTokenAllowedScope=k,this.extraQueryParams=A,this.extraTokenParams=j,this.extraHeaders=M,this.dpop=N,this.dpop&&!this.dpop?.store)throw Error(`A DPoPStore is required when dpop is enabled`)}},Ve=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new W(`UserInfoService`),this._getClaimsFromJwt=async e=>{let t=this._logger.create(`_getClaimsFromJwt`);try{let n=G.decode(e);return t.debug(`JWT decoding successful`),n}catch(e){throw t.error(`Error parsing JWT response`),e}},this._jsonService=new Ne(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){let t=this._logger.create(`getClaims`);e||this._logger.throw(Error(`No token passed`));let n=await this._metadataService.getUserInfoEndpoint();t.debug(`got userinfo url`,n);let r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug(`got claims`,r),r}},He=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new W(`TokenClient`),this._jsonService=new Ne(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e=`authorization_code`,redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...a}){let o=this._logger.create(`exchangeCode`);n||o.throw(Error(`A client_id is required`)),t||o.throw(Error(`A redirect_uri is required`)),a.code||o.throw(Error(`A code is required`));let s=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[e,t]of Object.entries(a))t!=null&&s.set(e,t);if((this._settings.client_authentication===`client_secret_basic`||this._settings.client_authentication===`client_secret_jwt`)&&r==null)throw o.throw(Error(`A client_secret is required`)),null;let c,l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case`client_secret_basic`:c=K.generateBasicAuth(n,r);break;case`client_secret_post`:s.append(`client_id`,n),r&&s.append(`client_secret`,r);break;case`client_secret_jwt`:{let e=await K.generateClientAssertionJwt(n,r,l,this._settings.token_endpoint_auth_signing_alg);s.append(`client_id`,n),s.append(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),s.append(`client_assertion`,e);break}}o.debug(`got token endpoint`);let u=await this._jsonService.postForm(l,{body:s,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug(`got response`),u}async exchangeCredentials({grant_type:e=`password`,client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...i}){let a=this._logger.create(`exchangeCredentials`);t||a.throw(Error(`A client_id is required`));let o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set(`scope`,r);for(let[e,t]of Object.entries(i))t!=null&&o.set(e,t);if((this._settings.client_authentication===`client_secret_basic`||this._settings.client_authentication===`client_secret_jwt`)&&n==null)throw a.throw(Error(`A client_secret is required`)),null;let s,c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case`client_secret_basic`:s=K.generateBasicAuth(t,n);break;case`client_secret_post`:o.append(`client_id`,t),n&&o.append(`client_secret`,n);break;case`client_secret_jwt`:{let e=await K.generateClientAssertionJwt(t,n,c,this._settings.token_endpoint_auth_signing_alg);o.append(`client_id`,t),o.append(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),o.append(`client_assertion`,e);break}}a.debug(`got token endpoint`);let l=await this._jsonService.postForm(c,{body:o,basicAuth:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return a.debug(`got response`),l}async exchangeRefreshToken({grant_type:e=`refresh_token`,client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:i,...a}){let o=this._logger.create(`exchangeRefreshToken`);t||o.throw(Error(`A client_id is required`)),a.refresh_token||o.throw(Error(`A refresh_token is required`));let s=new URLSearchParams({grant_type:e});for(let[e,t]of Object.entries(a))Array.isArray(t)?t.forEach(t=>s.append(e,t)):t!=null&&s.set(e,t);if((this._settings.client_authentication===`client_secret_basic`||this._settings.client_authentication===`client_secret_jwt`)&&n==null)throw o.throw(Error(`A client_secret is required`)),null;let c,l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case`client_secret_basic`:c=K.generateBasicAuth(t,n);break;case`client_secret_post`:s.append(`client_id`,t),n&&s.append(`client_secret`,n);break;case`client_secret_jwt`:{let e=await K.generateClientAssertionJwt(t,n,l,this._settings.token_endpoint_auth_signing_alg);s.append(`client_id`,t),s.append(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),s.append(`client_assertion`,e);break}}o.debug(`got token endpoint`);let u=await this._jsonService.postForm(l,{body:s,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug(`got response`),u}async revoke(e){let t=this._logger.create(`revoke`);e.token||t.throw(Error(`A token is required`));let n=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${e.token_type_hint??`default token type`}`);let r=new URLSearchParams;for(let[t,n]of Object.entries(e))n!=null&&r.set(t,n);r.set(`client_id`,this._settings.client_id),this._settings.client_secret&&r.set(`client_secret`,this._settings.client_secret),await this._jsonService.postForm(n,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),t.debug(`got response`)}},Ue=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new W(`ResponseValidator`),this._userInfoService=new Ve(this._settings,this._metadataService),this._tokenClient=new He(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){let r=this._logger.create(`validateSigninResponse`);this._processSigninState(e,t),r.debug(`state processed`),await this._processCode(e,t,n),r.debug(`code processed`),e.isOpenId&&this._validateIdTokenAttributes(e,``,t.nonce),r.debug(`tokens validated`),await this._processClaims(e,t?.skipUserInfo,e.isOpenId),r.debug(`claims processed`)}async validateCredentialsResponse(e,t){let n=this._logger.create(`validateCredentialsResponse`),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),n.debug(`tokens validated`),await this._processClaims(e,t,r),n.debug(`claims processed`)}async validateRefreshResponse(e,t){let n=this._logger.create(`validateRefreshResponse`);e.userState=t.data,e.session_state??=t.session_state,e.scope??=t.scope,e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug(`ID Token validated`)),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);let r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug(`claims processed`)}validateSignoutResponse(e,t){let n=this._logger.create(`validateSignoutResponse`);if(t.id!==e.state&&n.throw(Error(`State does not match`)),n.debug(`state validated`),e.userState=t.data,e.error)throw n.warn(`Response was error`,e.error),new De(e)}_processSigninState(e,t){let n=this._logger.create(`_processSigninState`);if(t.id!==e.state&&n.throw(Error(`State does not match`)),t.client_id||n.throw(Error(`No client_id on state`)),t.authority||n.throw(Error(`No authority on state`)),this._settings.authority!==t.authority&&n.throw(Error(`authority mismatch on settings vs. signin state`)),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(Error(`client_id mismatch on settings vs. signin state`)),n.debug(`state validated`),e.userState=t.data,e.url_state=t.url_state,e.scope??=t.scope,e.error)throw n.warn(`Response was error`,e.error),new De(e);t.code_verifier&&!e.code&&n.throw(Error(`Expected code in response`))}async _processClaims(e,t=!1,n=!0){let r=this._logger.create(`_processClaims`);if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){r.debug(`not loading user info`);return}r.debug(`loading user info`);let i=await this._userInfoService.getClaims(e.access_token);r.debug(`user info claims received from user info endpoint`),n&&i.sub!==e.profile.sub&&r.throw(Error(`subject from UserInfo response does not match subject in ID Token`)),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),r.debug(`user info claims received, updated profile:`,e.profile)}async _processCode(e,t,n){let r=this._logger.create(`_processCode`);if(e.code){r.debug(`Validating code`);let i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,i)}else r.debug(`No code to process`)}_validateIdTokenAttributes(e,t,n){let r=this._logger.create(`_validateIdTokenAttributes`);r.debug(`decoding ID Token JWT`);let i=G.decode(e.id_token??``);if(i.sub||r.throw(Error(`ID Token is missing a subject claim`)),n&&i.nonce!==n&&r.throw(Error(`nonce in id_token does not match nonce in client storage`)),t){let e=G.decode(t);i.sub!==e.sub&&r.throw(Error(`sub in id_token does not match current sub`)),i.auth_time&&i.auth_time!==e.auth_time&&r.throw(Error(`auth_time in id_token does not match original auth_time`)),i.azp&&i.azp!==e.azp&&r.throw(Error(`azp in id_token does not match original azp`)),!i.azp&&e.azp&&r.throw(Error(`azp not in id_token, but present in original id_token`))}e.profile=i}},We=class e{constructor(e){this.id=e.id||K.generateUUIDv4(),this.data=e.data,this.created=e.created&&e.created>0?e.created:we.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new W(`State`).create(`toStorageString`),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return W.createStatic(`State`,`fromStorageString`),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){let r=W.createStatic(`State`,`clearStaleState`),i=we.getEpochTime()-n,a=await t.getAllKeys();r.debug(`got keys`,a);for(let n=0;n<a.length;n++){let o=a[n],s=await t.get(o),c=!1;if(s)try{let t=await e.fromStorageString(s);r.debug(`got item from key:`,o,t.created),t.created<=i&&(c=!0)}catch(e){r.error(`Error parsing state for key:`,o,e),c=!0}else r.debug(`no item in storage for key:`,o),c=!0;c&&(r.debug(`removed item for key:`,o),t.remove(o))}}},Ge=class e extends We{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo,this.nonce=e.nonce}static async create(t){let n=t.code_verifier===!0?K.generateCodeVerifier():t.code_verifier||void 0,r=n?await K.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new W(`SigninState`).create(`toStorageString`),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(t){W.createStatic(`SigninState`,`fromStorageString`);let n=JSON.parse(t);return e.create(n)}},Ke=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:i,response_type:a,scope:o,state_data:s,response_mode:c,request_type:l,client_secret:u,nonce:d,url_state:f,resource:p,skipUserInfo:m,extraQueryParams:h,extraTokenParams:g,disablePKCE:_,dpopJkt:v,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error(`create: No url passed`),Error(`url`);if(!r)throw this._logger.error(`create: No client_id passed`),Error(`client_id`);if(!i)throw this._logger.error(`create: No redirect_uri passed`),Error(`redirect_uri`);if(!a)throw this._logger.error(`create: No response_type passed`),Error(`response_type`);if(!o)throw this._logger.error(`create: No scope passed`),Error(`scope`);if(!n)throw this._logger.error(`create: No authority passed`),Error(`authority`);let x=await Ge.create({data:s,request_type:l,url_state:f,code_verifier:!_,client_id:r,authority:n,redirect_uri:i,response_mode:c,client_secret:u,scope:o,extraTokenParams:g,skipUserInfo:m,nonce:d}),S=new URL(t);S.searchParams.append(`client_id`,r),S.searchParams.append(`redirect_uri`,i),S.searchParams.append(`response_type`,a),y||S.searchParams.append(`scope`,o),d&&S.searchParams.append(`nonce`,d),v&&S.searchParams.append(`dpop_jkt`,v);let C=x.id;f&&(C=`${C}${Ee}${f}`),S.searchParams.append(`state`,C),x.code_challenge&&(S.searchParams.append(`code_challenge`,x.code_challenge),S.searchParams.append(`code_challenge_method`,`S256`)),p&&(Array.isArray(p)?p:[p]).forEach(e=>S.searchParams.append(`resource`,e));for(let[e,t]of Object.entries({response_mode:c,...b,...h}))t!=null&&S.searchParams.append(e,t.toString());return new e({url:S.href,state:x})}};Ke._logger=new W(`SigninRequest`);var qe=Ke,Je=`openid`,Ye=class{constructor(e){if(this.access_token=``,this.token_type=``,this.profile={},this.state=e.get(`state`),this.session_state=e.get(`session_state`),this.state){let e=decodeURIComponent(this.state).split(Ee);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Ee))}this.error=e.get(`error`),this.error_description=e.get(`error_description`),this.error_uri=e.get(`error_uri`),this.code=e.get(`code`)}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-we.getEpochTime()}set expires_in(e){typeof e==`string`&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+we.getEpochTime())}get isOpenId(){return this.scope?.split(` `).includes(Je)||!!this.id_token}},Xe=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:i,request_type:a,client_id:o,url_state:s}){if(this._logger=new W(`SignoutRequest`),!e)throw this._logger.error(`ctor: No url passed`),Error(`url`);let c=new URL(e);if(n&&c.searchParams.append(`id_token_hint`,n),o&&c.searchParams.append(`client_id`,o),r&&(c.searchParams.append(`post_logout_redirect_uri`,r),t||s)){this.state=new We({data:t,request_type:a,url_state:s});let e=this.state.id;s&&(e=`${e}${Ee}${s}`),c.searchParams.append(`state`,e)}for(let[e,t]of Object.entries({...i}))t!=null&&c.searchParams.append(e,t.toString());this.url=c.href}},Ze=class{constructor(e){if(this.state=e.get(`state`),this.state){let e=decodeURIComponent(this.state).split(Ee);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Ee))}this.error=e.get(`error`),this.error_description=e.get(`error_description`),this.error_uri=e.get(`error_uri`)}},Qe=[`nbf`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`at_hash`],$e=[`sub`,`iss`,`aud`,`exp`,`iat`],et=class{constructor(e){this._settings=e,this._logger=new W(`ClaimsService`)}filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:Qe;for(let n of e)$e.includes(n)||delete t[n]}return t}mergeClaims(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(n[e]!==r){if(Array.isArray(n[e])||Array.isArray(r)){if(this._settings.mergeClaimsStrategy.array==`replace`)n[e]=r;else{let t=Array.isArray(n[e])?n[e]:[n[e]];for(let e of Array.isArray(r)?r:[r])t.includes(e)||t.push(e);n[e]=t}}else n[e]=typeof n[e]==`object`&&typeof r==`object`?this.mergeClaims(n[e],r):r}return n}},tt=class{constructor(e,t){this.keys=e,this.nonce=t}},nt=class{constructor(e,t){this._logger=new W(`OidcClient`),this.settings=e instanceof Be?e:new Be(e),this.metadataService=t??new Pe(this.settings),this._claimsService=new et(this.settings),this._validator=new Ue(this.settings,this.metadataService,this._claimsService),this._tokenClient=new He(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:i,login_hint:a,skipUserInfo:o,nonce:s,url_state:c,response_type:l=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:f=this.settings.prompt,display:p=this.settings.display,max_age:m=this.settings.max_age,ui_locales:h=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:x,omitScopeWhenRequesting:S=this.settings.omitScopeWhenRequesting}){let C=this._logger.create(`createSigninRequest`);if(l!==`code`)throw Error(`Only the Authorization Code flow (with PKCE) is supported`);let w=await this.metadataService.getAuthorizationEndpoint();C.debug(`Received authorization endpoint`,w);let T=await qe.create({url:w,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:u,state_data:e,url_state:c,prompt:f,display:p,max_age:m,ui_locales:h,id_token_hint:i,login_hint:a,acr_values:g,dpopJkt:x,resource:_,request:t,request_uri:n,extraQueryParams:y,extraTokenParams:b,request_type:r,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:s,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:S});await this.clearStaleState();let E=T.state;return await this.settings.stateStore.set(E.id,E.toStorageString()),T}async readSigninResponseState(e,t=!1){let n=this._logger.create(`readSigninResponseState`),r=new Ye(Te.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(Error(`No state in response`)),null;let i=await this.settings.stateStore[t?`remove`:`get`](r.state);if(!i)throw n.throw(Error(`No matching state found in storage`)),null;return{state:await Ge.fromStorageString(i),response:r}}async processSigninResponse(e,t,n=!0){let r=this._logger.create(`processSigninResponse`),{state:i,response:a}=await this.readSigninResponseState(e,n);if(r.debug(`received state from storage; validating response`),this.settings.dpop&&this.settings.dpop.store){let e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(a,i,t)}catch(e){if(e instanceof Me&&this.settings.dpop){let n=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=n,await this._validator.validateSigninResponse(a,i,t)}else throw e}return a}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await K.generateDPoPKeys(),r=new tt(n,t),await e.set(this.settings.client_id,r)),await K.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:`POST`,keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){let i=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),a=new Ye(new URLSearchParams);return Object.assign(a,i),await this._validator.validateCredentialsResponse(a,n),a}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:a}){let o=this._logger.create(`useRefreshToken`),s;if(this.settings.refreshTokenAllowedScope===void 0)s=e.scope;else{let t=this.settings.refreshTokenAllowedScope.split(` `);s=(e.scope?.split(` `)||[]).filter(e=>t.includes(e)).join(` `)}if(this.settings.dpop&&this.settings.dpop.store){let e=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:e}}let c;try{c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:s,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...a})}catch(o){if(o instanceof Me&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:s,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...a});else throw o}let l=new Ye(new URLSearchParams);return Object.assign(l,c),o.debug(`validating response`,l),await this._validator.validateRefreshResponse(l,{...e,scope:s}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:i,post_logout_redirect_uri:a=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){let s=this._logger.create(`createSignoutRequest`),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw s.throw(Error(`No end session endpoint`)),null;s.debug(`Received end session endpoint`,c),!n&&a&&!t&&(n=this.settings.client_id);let l=new Xe({url:c,id_token_hint:t,client_id:n,post_logout_redirect_uri:a,state_data:e,extraQueryParams:o,request_type:r,url_state:i});await this.clearStaleState();let u=l.state;return u&&(s.debug(`Signout request has state to persist`),await this.settings.stateStore.set(u.id,u.toStorageString())),l}async readSignoutResponseState(e,t=!1){let n=this._logger.create(`readSignoutResponseState`),r=new Ze(Te.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug(`No state in response`),r.error)throw n.warn(`Response was error:`,r.error),new De(r);return{state:void 0,response:r}}let i=await this.settings.stateStore[t?`remove`:`get`](r.state);if(!i)throw n.throw(Error(`No matching state found in storage`)),null;return{state:await We.fromStorageString(i),response:r}}async processSignoutResponse(e){let t=this._logger.create(`processSignoutResponse`),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug(`Received state from storage; validating response`),this._validator.validateSignoutResponse(r,n)):t.debug(`No state from storage; skipping response validation`),r}clearStaleState(){return this._logger.create(`clearStaleState`),We.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create(`revokeToken`),await this._tokenClient.revoke({token:e,token_type_hint:t})}},rt=class{constructor(e){this._userManager=e,this._logger=new W(`SessionMonitor`),this._start=async e=>{let t=e.session_state;if(!t)return;let n=this._logger.create(`_start`);if(e.profile?(this._sub=e.profile.sub,n.debug(`session_state`,t,`, sub`,this._sub)):(this._sub=void 0,n.debug(`session_state`,t,`, anonymous user`)),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{let e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug(`initializing check session iframe`);let r=this._userManager.settings.client_id,i=this._userManager.settings.checkSessionIntervalInSeconds,a=this._userManager.settings.stopCheckSessionOnError,o=new Ae(this._callback,r,e,i,a);await o.load(),this._checkSessionIFrame=o,o.start(t)}else n.warn(`no check session iframe found in the metadata`)}catch(e){n.error(`Error from getCheckSessionIframe:`,e instanceof Error?e.message:e)}},this._stop=()=>{let e=this._logger.create(`_stop`);if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){let t=setInterval(async()=>{clearInterval(t);try{let e=await this._userManager.querySessionStatus();if(e){let t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error(`error from querySessionStatus`,t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{let e=this._logger.create(`_callback`);try{let t=await this._userManager.querySessionStatus(),n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug(`same sub still logged in at OP, session state has changed, restarting check session iframe; session_state`,t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug(`different subject signed into OP`,t.sub):e.debug(`subject no longer signed into OP`),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug(`no change in session detected, no event to raise`)}catch(t){this._sub&&(e.debug(`Error calling queryCurrentSigninSession; raising signed out event`,t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(Error(`No user manager passed`)),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create(`_init`);let e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){let e=await this._userManager.querySessionStatus();if(e){let t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},it=class e{constructor(e){this.id_token=e.id_token,this.session_state=e.session_state??null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-we.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+we.getEpochTime())}get expired(){let e=this.expires_in;if(e!==void 0)return e<=0}get scopes(){return this.scope?.split(` `)??[]}toStorageString(){return new W(`User`).create(`toStorageString`),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return W.createStatic(`User`,`fromStorageString`),new e(JSON.parse(t))}},at=`oidc-client`,ot=class{constructor(){this._abort=new Se(`Window navigation aborted`),this._disposeHandlers=new Set,this._window=null}async navigate(e){let t=this._logger.create(`navigate`);if(!this._window)throw Error(`Attempted to navigate on a disposed window`);t.debug(`setting URL in window`),this._window.location.replace(e.url);let{url:n,keepOpen:r}=await new Promise((n,r)=>{let i=i=>{let a=i.data,o=e.scriptOrigin??window.location.origin;if(i.origin===o&&a?.source===at){try{let n=Te.readParams(a.url,e.response_mode).get(`state`);if(n||t.warn(`no state found in response url`),i.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(Error(`Invalid response from window`))}n(a)}};window.addEventListener(`message`,i,!1),this._disposeHandlers.add(()=>window.removeEventListener(`message`,i,!1));let a=new BroadcastChannel(`oidc-client-popup-${e.state}`);a.addEventListener(`message`,i,!1),this._disposeHandlers.add(()=>a.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),r(e)}))});return t.debug(`got response from window`),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create(`_dispose`);for(let e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){let i={source:at,url:t,keepOpen:n},a=new W(`_notifyParent`);if(e)a.debug(`With parent. Using parent.postMessage.`),e.postMessage(i,r);else{a.debug(`No parent. Using BroadcastChannel.`);let e=new URL(t).searchParams.get(`state`);if(!e)throw Error(`No parent and no state in URL. Can't complete notification.`);let n=new BroadcastChannel(`oidc-client-popup-${e}`);n.postMessage(i),n.close()}}},st={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},ct=`_blank`,lt=60,ut=2,dt=10,ft=class extends Be{constructor(e){let{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=st,popupWindowTarget:i=ct,redirectMethod:a=`assign`,redirectTarget:o=`self`,iframeNotifyParentOrigin:s=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:u=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:f=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:m=!1,monitorSession:h=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:_=ut,query_status_response_type:v=`code`,stopCheckSessionOnError:y=!0,revokeTokenTypes:b=[`access_token`,`refresh_token`],revokeTokensOnSignout:x=!1,includeIdTokenInSilentSignout:S=!1,accessTokenExpiringNotificationTimeInSeconds:C=lt,maxSilentRenewTimeoutRetries:w,userStore:T}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=i,this.redirectMethod=a,this.redirectTarget=o,this.iframeNotifyParentOrigin=s,this.iframeScriptOrigin=c,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=d||l||dt,this.automaticSilentRenew=f,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=m,this.monitorSession=h,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=y,this.query_status_response_type=v,this.revokeTokenTypes=b,this.revokeTokensOnSignout=x,this.includeIdTokenInSilentSignout=S,this.accessTokenExpiringNotificationTimeInSeconds=C,this.maxSilentRenewTimeoutRetries=w,T)this.userStore=T;else{let e=typeof window<`u`?window.sessionStorage:new je;this.userStore=new Fe({store:e})}}},pt=class e extends ot{constructor({silentRequestTimeoutInSeconds:t=dt}){super(),this._logger=new W(`IFrameWindow`),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){let e=window.document.createElement(`iframe`);return e.style.visibility=`hidden`,e.style.position=`fixed`,e.style.left=`-1000px`,e.style.top=`0`,e.width=`0`,e.height=`0`,window.document.body.appendChild(e),e}async navigate(e){this._logger.debug(`navigate: Using timeout of:`,this._timeoutInSeconds);let t=setTimeout(()=>void this._abort.raise(new Oe(`IFrame timed out without a response`)),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&=(this._frame.parentNode&&(this._frame.addEventListener(`load`,e=>{var t;let n=e.target;(t=n.parentNode)==null||t.removeChild(n),this._abort.raise(Error(`IFrame removed from DOM`))},!0),(e=this._frame.contentWindow)==null||e.location.replace(`about:blank`)),null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},mt=class{constructor(e){this._settings=e,this._logger=new W(`IFrameNavigator`)}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new pt({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create(`callback`),pt.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ht=500,gt=1e3,_t=class extends ot{constructor({popupWindowTarget:e=ct,popupWindowFeatures:t={},popupSignal:n,popupAbortOnClose:r}){super(),this._logger=new W(`PopupWindow`);let i=Ce.center({...st,...t});this._window=window.open(void 0,e,Ce.serialize(i)),this.abortOnClose=!!r,n&&n.addEventListener(`abort`,()=>{this._abort.raise(Error(n.reason??`Popup aborted`))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{!this._window||typeof this._window.closed!=`boolean`||this._window.closed?this._abort.raise(Error(`Popup blocked by user`)):this.close()},t.closePopupWindowAfterInSeconds*gt)}async navigate(e){var t;(t=this._window)==null||t.focus();let n=setInterval(()=>{(!this._window||this._window.closed)&&(this._logger.debug(`Popup closed by user or isolated by redirect`),r(),this._disposeHandlers.delete(r),this.abortOnClose&&this._abort.raise(Error(`Popup closed by user`)))},ht),r=()=>clearInterval(n);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(Error(`Popup closed`)))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),!t&&!window.opener&&window.close()}},vt=class{constructor(e){this._settings=e,this._logger=new W(`PopupNavigator`)}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n,popupAbortOnClose:r}){return new _t({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n,popupAbortOnClose:r})}async callback(e,{keepOpen:t=!1}){this._logger.create(`callback`),_t.notifyOpener(e,t)}},yt=class{constructor(e){this._settings=e,this._logger=new W(`RedirectNavigator`)}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){this._logger.create(`prepare`);let n=window.self;t===`top`&&(n=window.top??window.self);let r=n.location[e].bind(n.location),i;return{navigate:async e=>(this._logger.create(`navigate`),await new Promise((t,n)=>{i=n,window.addEventListener(`pageshow`,()=>t(window.location.href)),r(e.url)})),close:()=>{this._logger.create(`close`),i?.(Error(`Redirect aborted`)),n.stop()}}}async callback(){}},bt=class extends ke{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new W(`UserManagerEvents`),this._userLoaded=new Se(`User loaded`),this._userUnloaded=new Se(`User unloaded`),this._silentRenewError=new Se(`Silent renew error`),this._userSignedIn=new Se(`User signed in`),this._userSignedOut=new Se(`User signed out`),this._userSessionChanged=new Se(`User session changed`)}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},xt=class{constructor(e){this._userManager=e,this._logger=new W(`SilentRenewService`),this._isStarted=!1,this._retryTimer=new we(`Retry Silent Renew`),this._timeoutRetryCount=0,this._tokenExpiring=async()=>{let e=this._logger.create(`_tokenExpiring`);try{await this._userManager.signinSilent(),this._timeoutRetryCount=0,e.debug(`silent token renewal successful`)}catch(t){if(t instanceof Oe){this._timeoutRetryCount++;let n=this._userManager.settings.maxSilentRenewTimeoutRetries;if(n!==void 0&&this._timeoutRetryCount>n){e.error(`Timeout retry limit reached (${this._timeoutRetryCount} > ${n}), raising silentRenewError:`,t),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(t);return}e.warn(`ErrorTimeout from signinSilent (attempt ${this._timeoutRetryCount}), retry in 5s:`,t),this._retryTimer.init(5);return}e.error(`Error from signinSilent:`,t),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(t)}}}async start(){let e=this._logger.create(`start`);if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error(`getUser error`,t)}}}stop(){this._isStarted&&=(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),!1)}},St=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Ct=class{constructor(e,t,n,r){this._logger=new W(`UserManager`),this.settings=new ft(e),this._client=new nt(e),this._redirectNavigator=t??new yt(this.settings),this._popupNavigator=n??new vt(this.settings),this._iframeNavigator=r??new mt(this.settings),this._events=new bt(this.settings),this._silentRenewService=new xt(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new rt(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){let t=this._logger.create(`getUser`),n=await this._loadUser();return n?(t.info(`user loaded`),await this._events.load(n,e),n):(t.info(`user not found in storage`),null)}async removeUser(){let e=this._logger.create(`removeUser`);await this.storeUser(null),e.info(`user removed from storage`),await this._events.unload()}async signinRedirect(e={}){this._logger.create(`signinRedirect`);let{redirectMethod:t,...n}=e,r;this.settings.dpop?.bind_authorization_code&&(r=await this.generateDPoPJkt(this.settings.dpop));let i=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:`si:r`,dpopJkt:r,...n},i)}async signinRedirectCallback(e=window.location.href){let t=this._logger.create(`signinRedirectCallback`),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info(`success, signed in subject`,n.profile.sub):t.info(`no subject`),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){let r=this._logger.create(`signinResourceOwnerCredential`),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug(`got signin response`);let a=await this._buildUser(i);return a.profile&&a.profile.sub?r.info(`success, signed in subject`,a.profile.sub):r.info(`no subject`),a}async signinPopup(e={}){let t=this._logger.create(`signinPopup`),n;this.settings.dpop?.bind_authorization_code&&(n=await this.generateDPoPJkt(this.settings.dpop));let{popupWindowFeatures:r,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o,...s}=e,c=this.settings.popup_redirect_uri;c||t.throw(Error(`No popup_redirect_uri configured`));let l=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o}),u=await this._signin({request_type:`si:p`,redirect_uri:c,display:`popup`,dpopJkt:n,...s},l);return u&&(u.profile&&u.profile.sub?t.info(`success, signed in subject`,u.profile.sub):t.info(`no subject`)),u}async signinPopupCallback(e=window.location.href,t=!1){let n=this._logger.create(`signinPopupCallback`);await this._popupNavigator.callback(e,{keepOpen:t}),n.info(`success`)}async signinSilent(e={}){let t=this._logger.create(`signinSilent`),{silentRequestTimeoutInSeconds:n,...r}=e,i=await this._loadUser();if(!e.forceIframeAuth&&i?.refresh_token){t.debug(`using refresh token`);let e=new St(i);return await this._useRefreshToken({state:e,redirect_uri:r.redirect_uri,resource:r.resource,extraTokenParams:r.extraTokenParams,timeoutInSeconds:n})}let a;this.settings.dpop?.bind_authorization_code&&(a=await this.generateDPoPJkt(this.settings.dpop));let o=this.settings.silent_redirect_uri;o||t.throw(Error(`No silent_redirect_uri configured`));let s;i&&this.settings.validateSubOnSilentRenew&&(t.debug(`subject prior to silent renew:`,i.profile.sub),s=i.profile.sub);let c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});return i=await this._signin({request_type:`si:s`,redirect_uri:o,prompt:`none`,id_token_hint:this.settings.includeIdTokenInSilentRenew?i?.id_token:void 0,dpopJkt:a,...r},c,s),i&&(i.profile?.sub?t.info(`success, signed in subject`,i.profile.sub):t.info(`no subject`)),i}async _useRefreshToken(e){let t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new it({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){let t=this._logger.create(`signinSilentCallback`);await this._iframeNavigator.callback(e),t.info(`success`)}async signinCallback(e=window.location.href){let{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case`si:r`:return await this.signinRedirectCallback(e);case`si:p`:await this.signinPopupCallback(e);break;case`si:s`:await this.signinSilentCallback(e);break;default:throw Error(`invalid request_type in state`)}}async signoutCallback(e=window.location.href,t=!1){let{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case`so:r`:return await this.signoutRedirectCallback(e);case`so:p`:await this.signoutPopupCallback(e,t);break;case`so:s`:await this.signoutSilentCallback(e);break;default:throw Error(`invalid request_type in state`)}}async querySessionStatus(e={}){let t=this._logger.create(`querySessionStatus`),{silentRequestTimeoutInSeconds:n,...r}=e,i=this.settings.silent_redirect_uri;i||t.throw(Error(`No silent_redirect_uri configured`));let a=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),s=await this._signinStart({request_type:`si:s`,redirect_uri:i,prompt:`none`,id_token_hint:this.settings.includeIdTokenInSilentRenew?a?.id_token:void 0,response_type:this.settings.query_status_response_type,scope:`openid`,skipUserInfo:!0,...r},o);try{let e=await this._client.processSigninResponse(s.url,{});return t.debug(`got signin response`),e.session_state&&e.profile.sub?(t.info(`success for subject`,e.profile.sub),{session_state:e.session_state,sub:e.profile.sub}):(t.info(`success, user not authenticated`),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof De)switch(e.error){case`login_required`:case`consent_required`:case`interaction_required`:case`account_selection_required`:return t.info(`success for anonymous user`),{session_state:e.session_state}}throw e}}async _signin(e,t,n){let r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){let n=this._logger.create(`_signinStart`);try{let r=await this._client.createSigninRequest(e);return n.debug(`got signin request`),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug(`error after preparing navigator, closing navigator window`),t.close(),e}}async _signinEnd(e,t){let n=this._logger.create(`_signinEnd`),r=await this._client.processSigninResponse(e,{});return n.debug(`got signin response`),await this._buildUser(r,t)}async _buildUser(e,t){let n=this._logger.create(`_buildUser`),r=new it(e);if(t){if(t!==r.profile.sub)throw n.debug(`current user does not match user returned from signin. sub from signin:`,r.profile.sub),new De({...e,error:`login_required`});n.debug(`current user matches user returned from signin`)}return await this.storeUser(r),n.debug(`user stored`),await this._events.load(r),r}async signoutRedirect(e={}){let t=this._logger.create(`signoutRedirect`),{redirectMethod:n,...r}=e,i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:`so:r`,post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},i),t.info(`success`)}async signoutRedirectCallback(e=window.location.href){let t=this._logger.create(`signoutRedirectCallback`),n=await this._signoutEnd(e);return t.info(`success`),n}async signoutPopup(e={}){let t=this._logger.create(`signoutPopup`),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i,...a}=e,o=this.settings.popup_post_logout_redirect_uri,s=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i});await this._signout({request_type:`so:p`,post_logout_redirect_uri:o,state:o==null?void 0:{},...a},s),t.info(`success`)}async signoutPopupCallback(e=window.location.href,t=!1){let n=this._logger.create(`signoutPopupCallback`);await this._popupNavigator.callback(e,{keepOpen:t}),n.info(`success`)}async _signout(e,t){let n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){let n=this._logger.create(`_signoutStart`);try{let r=await this._loadUser();n.debug(`loaded current user from storage`),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);let i=e.id_token_hint||r&&r.id_token;i&&(n.debug(`setting id_token_hint in signout request`),e.id_token_hint=i),await this.removeUser(),n.debug(`user removed, creating signout request`);let a=await this._client.createSignoutRequest(e);return n.debug(`got signout request`),await t.navigate({url:a.url,state:a.state?.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug(`error after preparing navigator, closing navigator window`),t.close(),e}}async _signoutEnd(e){let t=this._logger.create(`_signoutEnd`),n=await this._client.processSignoutResponse(e);return t.debug(`got signout response`),n}async signoutSilent(e={}){let t=this._logger.create(`signoutSilent`),{silentRequestTimeoutInSeconds:n,...r}=e,i=this.settings.includeIdTokenInSilentSignout?(await this._loadUser())?.id_token:void 0,a=this.settings.popup_post_logout_redirect_uri,o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:`so:s`,post_logout_redirect_uri:a,id_token_hint:i,...r},o),t.info(`success`)}async signoutSilentCallback(e=window.location.href){let t=this._logger.create(`signoutSilentCallback`);await this._iframeNavigator.callback(e),t.info(`success`)}async revokeTokens(e){let t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){let n=this._logger.create(`_revokeInternal`);if(!e)return;let r=t.filter(t=>typeof e[t]==`string`);if(!r.length)n.debug(`no need to revoke due to no token(s)`);else{for(let t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),t!==`access_token`&&(e[t]=null);await this.storeUser(e),n.debug(`user stored`),await this._events.load(e)}}startSilentRenew(){this._logger.create(`startSilentRenew`),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){let e=this._logger.create(`_loadUser`),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug(`user storageString loaded`),it.fromStorageString(t)):(e.debug(`no user storageString`),null)}async storeUser(e){let t=this._logger.create(`storeUser`);if(e){t.debug(`storing user`);let n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug(`removing user`),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,r){let i=await(this.settings.dpop?.store)?.get(this.settings.client_id);if(i)return await K.generateDPoPProof({url:e,accessToken:t?.access_token,httpMethod:n,keyPair:i.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);return t||(t=new tt(await K.generateDPoPKeys()),await e.store.set(this.settings.client_id,t)),await K.generateDPoPJkt(t.keys)}},wt=`/auth/callback`,Tt=`Your session ended. Sign in again.`,Et=class extends Error{constructor(){super(Tt),this.name=`SessionEndedError`}},Dt=null,Ot=null,kt=null,At=new Set;async function jt(){let e=await fetch(`${S()}/graphcore/api/auth/client/`);if(!e.ok)throw Error(`The backend did not say where to sign in`);let{issuer:t,client_id:n}=await e.json();if(!t||!n)throw Error(`The backend named no issuer or client to sign in with`);return{authority:t,clientId:n}}function Mt(){return Dt||(Dt=jt().then(({authority:e,clientId:t})=>new Ct({authority:e,client_id:t,redirect_uri:`${window.location.origin}${x(wt)}`,post_logout_redirect_uri:`${window.location.origin}${x(`/`)}`,response_type:`code`,scope:`openid`,automaticSilentRenew:!0})),Dt.catch(()=>{Dt=null})),Dt}function Nt(){let{pathname:e,search:t}=window.location;return e===x(`/auth/callback`)&&new URLSearchParams(t).has(`state`)}async function Pt(){try{return!!(await(await Mt()).metadataService.getMetadata()).prompt_values_supported?.includes(`create`)}catch{return!1}}async function Ft(){let e=await(await Mt()).signinRedirectCallback(),t=e.state?.returnTo??`/`;return window.history.replaceState(null,``,t),window.dispatchEvent(new PopStateEvent(`popstate`)),e}async function It(e={}){let{pathname:t,search:n,hash:r}=window.location;await(await Mt()).signinRedirect({state:{returnTo:`${t}${n}${r}`},...e.createAccount?{prompt:`create`}:{}})}async function Lt(){let e=await Mt(),t=await e.getUser();if(!t)return null;if(!t.expired)return t;try{return await e.signinSilent()}catch{return await e.removeUser(),null}}function Rt(){return kt||=(async()=>{let e=await Mt();try{let t=await e.signinSilent();if(t)return t.access_token}catch(e){console.warn(`Session renewal failed:`,e)}return await e.removeUser(),At.forEach(e=>e()),null})().finally(()=>{kt=null}),kt}async function zt(){return(await(await Mt()).getUser())?.expired?(await Rt(),!0):!1}function Bt(e){return At.add(e),()=>At.delete(e)}async function Vt(){try{return await Ft()}catch(e){return console.warn(`Ignoring a sign-in callback that cannot be completed:`,e),window.history.replaceState(null,``,x(`/`)),Lt()}}function Ht(){return Ot||=Nt()?Vt():Lt(),Ot}function Ut(e){let t=t=>{t.persisted&&e()};return window.addEventListener(`pageshow`,t),()=>window.removeEventListener(`pageshow`,t)}async function Wt(){let e=await Mt(),t=await e.getUser();await e.removeUser(),t&&await e.signoutRedirect({id_token_hint:t.id_token})}async function Gt(e,t){if(e.status===401)return new Et;let n=await e.json().catch(()=>null);return Error(n?.error||`${t} (HTTP ${e.status})`)}var q=new class{async me(e){let t=await fetch(`${S()}/graphcore/api/auth/me/`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`This deployment did not accept the sign-in`);return t.json()}async getIdentity(){let e=await fetch(`${S()}/graphcore/.well-known/graphcore/`);if(!e.ok)throw Error(`Failed to fetch identity document`);return e.json()}_authHeaders(){let{token:e}=B.getState();return e?{Authorization:`Bearer ${e}`}:{}}async _authorizedFetch(e,t={}){let n=n=>fetch(e,{...t,headers:{...t.headers,...n}}),r=await n(this._authHeaders());if(r.status!==401||w())return r;let i=await Rt();if(!i)throw new Et;return n({Authorization:`Bearer ${i}`})}async getStrategyDirectory(){let e=await this._authorizedFetch(`${S()}/graphcore/api/get_strategy_directory/`);if(!e.ok)throw await Gt(e,`Failed to fetch strategy directory`);return e.json()}async getRoutes(){let e=await fetch(`${S()}/graphcore/api/routes/`);if(!e.ok)throw Error(`Failed to fetch routes`);return e.json()}async getEntityDirectory(){let e=await this._authorizedFetch(`${S()}/graphcore/api/get_entity_directory/`);if(!e.ok)throw await Gt(e,`Failed to fetch entity directory`);return e.json()}async createInvite(e,t,n={}){let r=await this._authorizedFetch(`${S()}/graphcore/api/invites/`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({resource_id:e,role_name:t,...n})});if(!r.ok)throw await Gt(r,`Failed to create invite`);return r.json()}async redeemInvite(e){let t=await this._authorizedFetch(`${S()}/graphcore/api/invites/redeem/`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:e})});if(!t.ok)throw await Gt(t,`Failed to redeem invite`);return t.json()}async getAccess(e){let t=await this._authorizedFetch(`${S()}/graphcore/api/access/${encodeURIComponent(e)}/`);if(!t.ok)throw await Gt(t,`Failed to fetch access`);return t.json()}async listEntities({type_ids:e,parent_id:t,where:n,granted_to_me:r,cursor:i,limit:a=25}){let o={type_ids:e,limit:a};t&&(o.parent_id=t),n&&(o.where=n),r&&(o.granted_to_me=!0),i&&(o.cursor=i);let s=await this._authorizedFetch(`${S()}/graphcore/api/list_entities/`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw await Gt(s,`Failed to list entities`);return s.json()}async getEntity(e,t){let n={"Content-Type":`application/json`};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${S()}/graphcore/api/get_entity/${encodeURIComponent(e)}/`,{method:`GET`,headers:n});if(!r.ok)throw await Gt(r,`Failed to fetch entity`);return r.json()}},Kt=(e,t)=>({equal:{field:e,value:t}}),qt=(e,t)=>({in_values:{field:e,values:t}}),Jt=(e,t)=>({contains_value:{field:e,value:t}}),Yt=(e,t)=>({contains_any:{field:e,values:t}}),Xt=(...e)=>({all_of:e}),Zt=(...e)=>({any_of:e}),Qt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},$t=l.default.createContext&&l.default.createContext(Qt),en=[`attr`,`size`,`title`];function tn(e,t){if(e==null)return{};var n,r,i=nn(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function nn(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function rn(){return rn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},rn.apply(null,arguments)}function an(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function on(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?an(Object(n),!0).forEach(function(t){sn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):an(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function sn(e,t,n){return(t=cn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cn(e){var t=ln(e,`string`);return typeof t==`symbol`?t:t+``}function ln(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function un(e){return e&&e.map((e,t)=>l.default.createElement(e.tag,on({key:t},e.attr),un(e.child)))}function J(e){return t=>l.default.createElement(dn,rn({attr:on({},e.attr)},t),un(e.child))}function dn(e){var t=t=>{var n=e.attr,r=e.size,i=e.title,a=tn(e,en),o=r||t.size||`1em`,s;return t.className&&(s=t.className),e.className&&(s=(s?s+` `:``)+e.className),l.default.createElement(`svg`,rn({stroke:`currentColor`,fill:`currentColor`,strokeWidth:`0`},t.attr,n,a,{className:s,style:on(on({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:`http://www.w3.org/2000/svg`}),i&&l.default.createElement(`title`,null,i),e.children)};return $t===void 0?t(Qt):l.default.createElement($t.Consumer,null,e=>t(e))}function fn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M85.57 446.25h340.86a32 32 0 0 0 28.17-47.17L284.18 82.58c-12.09-22.44-44.27-22.44-56.36 0L57.4 399.08a32 32 0 0 0 28.17 47.17`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m250.26 195.39 5.74 122 5.73-121.95a5.74 5.74 0 0 0-5.79-6h0a5.74 5.74 0 0 0-5.68 5.95`},child:[]},{tag:`path`,attr:{d:`M256 397.25a20 20 0 1 1 20-20 20 20 0 0 1-20 20`},child:[]}]})(e)}function pn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m112 112 20 320c.95 18.49 14.4 32 32 32h184c17.67 0 30.87-13.51 32-32l20-320`},child:[]},{tag:`path`,attr:{strokeLinecap:`round`,strokeMiterlimit:`10`,strokeWidth:`32`,d:`M80 112h352`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M192 112V72h0a23.93 23.93 0 0 1 24-24h80a23.93 23.93 0 0 1 24 24h0v40m-64 64v224m-72-224 8 224m136-224-8 224`},child:[]}]})(e)}function mn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M434.67 285.59v-29.8c0-98.73-80.24-178.79-179.2-178.79a179 179 0 0 0-140.14 67.36m-38.53 82v29.8C76.8 355 157 435 256 435a180.45 180.45 0 0 0 140-66.92`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m32 256 44-44 46 44m358 0-44 44-46-44`},child:[]}]})(e)}function hn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M262.29 192.31a64 64 0 1 0 57.4 57.4 64.13 64.13 0 0 0-57.4-57.4M416.39 256a154 154 0 0 1-1.53 20.79l45.21 35.46a10.81 10.81 0 0 1 2.45 13.75l-42.77 74a10.81 10.81 0 0 1-13.14 4.59l-44.9-18.08a16.11 16.11 0 0 0-15.17 1.75A164.5 164.5 0 0 1 325 400.8a15.94 15.94 0 0 0-8.82 12.14l-6.73 47.89a11.08 11.08 0 0 1-10.68 9.17h-85.54a11.11 11.11 0 0 1-10.69-8.87l-6.72-47.82a16.07 16.07 0 0 0-9-12.22 155 155 0 0 1-21.46-12.57 16 16 0 0 0-15.11-1.71l-44.89 18.07a10.81 10.81 0 0 1-13.14-4.58l-42.77-74a10.8 10.8 0 0 1 2.45-13.75l38.21-30a16.05 16.05 0 0 0 6-14.08c-.36-4.17-.58-8.33-.58-12.5s.21-8.27.58-12.35a16 16 0 0 0-6.07-13.94l-38.19-30A10.81 10.81 0 0 1 49.48 186l42.77-74a10.81 10.81 0 0 1 13.14-4.59l44.9 18.08a16.11 16.11 0 0 0 15.17-1.75A164.5 164.5 0 0 1 187 111.2a15.94 15.94 0 0 0 8.82-12.14l6.73-47.89A11.08 11.08 0 0 1 213.23 42h85.54a11.11 11.11 0 0 1 10.69 8.87l6.72 47.82a16.07 16.07 0 0 0 9 12.22 155 155 0 0 1 21.46 12.57 16 16 0 0 0 15.11 1.71l44.89-18.07a10.81 10.81 0 0 1 13.14 4.58l42.77 74a10.8 10.8 0 0 1-2.45 13.75l-38.21 30a16.05 16.05 0 0 0-6.05 14.08c.33 4.14.55 8.3.55 12.47`},child:[]}]})(e)}function gn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M96 256h320M96 176h320M96 336h320`},child:[]}]})(e)}function _n(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M332.64 64.58C313.18 43.57 286 32 256 32c-30.16 0-57.43 11.5-76.8 32.38-19.58 21.11-29.12 49.8-26.88 80.78C156.76 206.28 203.27 256 256 256s99.16-49.71 103.67-110.82c2.27-30.7-7.33-59.33-27.03-80.6M432 480H80a31 31 0 0 1-24.2-11.13c-6.5-7.77-9.12-18.38-7.18-29.11C57.06 392.94 83.4 353.61 124.8 326c36.78-24.51 83.37-38 131.2-38s94.42 13.5 131.2 38c41.4 27.6 67.74 66.93 76.18 113.75 1.94 10.73-.68 21.34-7.18 29.11A31 31 0 0 1 432 480`},child:[]}]})(e)}function vn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M336 256c-20.56 0-40.44-9.18-56-25.84-15.13-16.25-24.37-37.92-26-61-1.74-24.62 5.77-47.26 21.14-63.76S312 80 336 80c23.83 0 45.38 9.06 60.7 25.52 15.47 16.62 23 39.22 21.26 63.63-1.67 23.11-10.9 44.77-26 61C376.44 246.82 356.57 256 336 256m131.83 176H204.18a27.71 27.71 0 0 1-22-10.67 30.22 30.22 0 0 1-5.26-25.79c8.42-33.81 29.28-61.85 60.32-81.08C264.79 297.4 299.86 288 336 288c36.85 0 71 9 98.71 26.05 31.11 19.13 52 47.33 60.38 81.55a30.27 30.27 0 0 1-5.32 25.78A27.68 27.68 0 0 1 467.83 432M147 260c-35.19 0-66.13-32.72-69-72.93-1.42-20.6 5-39.65 18-53.62 12.86-13.83 31-21.45 51-21.45s38 7.66 50.93 21.57c13.1 14.08 19.5 33.09 18 53.52-2.87 40.2-33.8 72.91-68.93 72.91m65.66 31.45c-17.59-8.6-40.42-12.9-65.65-12.9-29.46 0-58.07 7.68-80.57 21.62-25.51 15.83-42.67 38.88-49.6 66.71a27.39 27.39 0 0 0 4.79 23.36A25.32 25.32 0 0 0 41.72 400h111a8 8 0 0 0 7.87-6.57c.11-.63.25-1.26.41-1.88 8.48-34.06 28.35-62.84 57.71-83.82a8 8 0 0 0-.63-13.39c-1.57-.92-3.37-1.89-5.42-2.89`},child:[]}]})(e)}function yn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M384 224v184a40 40 0 0 1-40 40H104a40 40 0 0 1-40-40V168a40 40 0 0 1 40-40h167.48M336 64h112v112M224 288 440 72`},child:[]}]})(e)}function bn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M448 96a64 64 0 1 0-96.31 55.21c-1.79 20.87-11.47 38.1-28.87 51.29C305.07 216 280.09 224 256 224s-49.07-8-66.82-21.5c-17.4-13.19-27.08-30.42-28.87-51.29a64 64 0 1 0-64.11.29c2.08 40.87 21.17 76.87 54.31 102C171.3 269.26 197 280.19 224 285.09v75.52a64 64 0 1 0 64 0v-75.52c27-4.9 52.7-15.83 73.49-31.59 33.14-25.13 52.23-61.13 54.31-102A64 64 0 0 0 448 96M128 64a32 32 0 1 1-32 32 32 32 0 0 1 32-32m128 384a32 32 0 1 1 32-32 32 32 0 0 1-32 32m128-320a32 32 0 1 1 32-32 32 32 0 0 1-32 32`},child:[]}]})(e)}function xn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M64 192v-72a40 40 0 0 1 40-40h75.89a40 40 0 0 1 22.19 6.72l27.84 18.56a40 40 0 0 0 22.19 6.72H408a40 40 0 0 1 40 40v40`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M479.9 226.55 463.68 392a40 40 0 0 1-39.93 40H88.25a40 40 0 0 1-39.93-40L32.1 226.55A32 32 0 0 1 64 192h384.1a32 32 0 0 1 31.8 34.55`},child:[]}]})(e)}function Sn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`circle`,attr:{cx:`256`,cy:`256`,r:`64`},child:[]},{tag:`path`,attr:{d:`M490.84 238.6c-26.46-40.92-60.79-75.68-99.27-100.53C349 110.55 302 96 255.66 96c-42.52 0-84.33 12.15-124.27 36.11-40.73 24.43-77.63 60.12-109.68 106.07a31.92 31.92 0 0 0-.64 35.54c26.41 41.33 60.4 76.14 98.28 100.65C162 402 207.9 416 255.66 416c46.71 0 93.81-14.43 136.2-41.72 38.46-24.77 72.72-59.66 99.08-100.92a32.2 32.2 0 0 0-.1-34.76M256 352a96 96 0 1 1 96-96 96.11 96.11 0 0 1-96 96`},child:[]}]})(e)}function Cn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`circle`,attr:{cx:`256`,cy:`256`,r:`48`},child:[]},{tag:`circle`,attr:{cx:`416`,cy:`256`,r:`48`},child:[]},{tag:`circle`,attr:{cx:`96`,cy:`256`,r:`48`},child:[]}]})(e)}function wn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M416 221.25V416a48 48 0 0 1-48 48H144a48 48 0 0 1-48-48V96a48 48 0 0 1 48-48h98.75a32 32 0 0 1 22.62 9.37l141.26 141.26a32 32 0 0 1 9.37 22.62z`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M256 56v120a32 32 0 0 0 32 32h120m-232 80h160m-160 80h160`},child:[]}]})(e)}function Tn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M440.9 136.3a4 4 0 0 0 0-6.91L288.16 40.65a64.14 64.14 0 0 0-64.33 0L71.12 129.39a4 4 0 0 0 0 6.91L254 243.88a4 4 0 0 0 4.06 0zM54 163.51a4 4 0 0 0-6 3.49v173.89a48 48 0 0 0 23.84 41.39L234 479.51a4 4 0 0 0 6-3.46V274.3a4 4 0 0 0-2-3.46zM272 275v201a4 4 0 0 0 6 3.46l162.15-97.23A48 48 0 0 0 464 340.89V167a4 4 0 0 0-6-3.45l-184 108a4 4 0 0 0-2 3.45`},child:[]}]})(e)}function En(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`rect`,attr:{width:`336`,height:`336`,x:`128`,y:`128`,fill:`none`,strokeLinejoin:`round`,strokeWidth:`32`,rx:`57`,ry:`57`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m383.5 128 .5-24a56.16 56.16 0 0 0-56-56H112a64.19 64.19 0 0 0-64 64v216a56.16 56.16 0 0 0 56 56h24`},child:[]}]})(e)}function Dn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M160 368 32 256l128-112m192 224 128-112-128-112m-48-48-96 320`},child:[]}]})(e)}function On(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M368 368 144 144m224 0L144 368`},child:[]}]})(e)}function kn(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeMiterlimit:`10`,strokeWidth:`32`,d:`M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M250.26 166.05 256 288l5.73-121.95a5.74 5.74 0 0 0-5.79-6h0a5.74 5.74 0 0 0-5.68 6`},child:[]},{tag:`path`,attr:{d:`M256 367.91a20 20 0 1 1 20-20 20 20 0 0 1-20 20`},child:[]}]})(e)}function An(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M256 112v288m144-144H112`},child:[]}]})(e)}var Y=Object.freeze({ENTITY:`graphcore.Entity`,VIEW:`graphcore.View`,USER:`graphcore.User`,GROUP:`graphcore.Group`,GRANT:`graphcore.Grant`,DEPLOYMENT:`graphcore.Deployment`,STRATEGY_REQUEST:`graphcore.StrategyRequest`}),jn={[Y.ENTITY]:Tn,[Y.VIEW]:Sn,[Y.USER]:_n,[Y.GROUP]:vn,[Y.STRATEGY_REQUEST]:bn},Mn=Tn;function Nn(e){return jn[e]||Mn}var Pn=k(()=>null),Fn=e=>{Pn.setState(e)},In=(e,t)=>{t instanceof Et||Fn({message:`${e}: ${t instanceof Error?t.message:String(t)}`,type:`error`})},Ln=()=>L(Pn,e=>e),Rn=100,zn=100,Bn=k(()=>({loaded:{},views:{}})),Vn=new Map,Hn=new Set,Un=!1,Wn=(e,t,n)=>JSON.stringify([`top`,e,t,n]),Gn=(e,t,n,r)=>JSON.stringify([e,t,n,r]);function Kn(e){if(typeof e.slot!=`string`||typeof e.client!=`string`)return null;let t=typeof e.renders==`string`?e.renders:null;return typeof e.parent_id==`string`&&e.parent_id?Gn(e.parent_id,e.client,e.slot,t):typeof e.owner==`string`?Wn(e.owner,e.client,e.slot):null}function qn(e,t){let{client:n,address:r,view:i}=e;return r===void 0?{key:JSON.stringify([`view`,n,i]),predicate:Xt(Jt(`ancestor_ids`,i),Kt(`client`,n))}:{key:JSON.stringify([`page`,t,n,r]),predicate:Xt(Kt(`owner`,t),Kt(`client`,n),Kt(`address`,r))}}function Jn(e){let t={},n=new Set;e.forEach(e=>{if(e?.entity_type_id!==Y.VIEW)return;let r=Kn(e);r&&(e.deleted?n.add(e.entity_id):t[r]=e.entity_id)}),(Object.keys(t).length!==0||n.size!==0)&&Bn.setState(e=>{let r={...e.views,...t};return n.size&&Object.keys(r).forEach(e=>n.has(r[e])&&delete r[e]),{views:r}})}async function Yn(e){try{let t=[],n;do{let r=await q.listEntities({type_ids:[Y.VIEW],where:e.length===1?e[0].predicate:Zt(...e.map(e=>e.predicate)),cursor:n,limit:Rn});t.push(...r?.entities??[]),n=r?.next_cursor??void 0}while(n);I.mergeEntities(t),Jn(t),Bn.setState(t=>({loaded:{...t.loaded,...Object.fromEntries(e.map(e=>[e.key,!0]))}}))}catch(e){console.error(`View lookup failed:`,e),In(`Could not load views`,e)}finally{e.forEach(e=>Hn.delete(e.key))}}function Xn(){Un=!1;let e=[...Vn.values()];Vn=new Map,e.forEach(e=>Hn.add(e.key));for(let t=0;t<e.length;t+=zn)Yn(e.slice(t,t+zn))}var Zn=e=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,16)};function Qn(e,t,n){let{client:r,address:i,view:a,placement:o}=t,s;if(i!==void 0){if(!e.loaded[qn(t,n).key])return;s=e.views[Wn(n,r,i)]??null}else{if(o.length&&!e.loaded[qn(t,n).key])return;s=a}for(let t of o){if(!s)return null;s=e.views[Gn(s,r,t.slot,t.renders)]??null}return s}var $n={request(e,t){let n=qn(e,t);Bn.getState().loaded[n.key]||Hn.has(n.key)||(Vn.set(n.key,n),!Un&&(Un=!0,Zn(Xn)))},noteEntities(e){Jn(e)},find(e,t){return Qn(Bn.getState(),e,t)},clear(){Vn=new Map,Hn.clear(),Un=!1,Bn.setState({loaded:{},views:{}})}};function er(e){let{principalEntityId:t}=fe(),n=e&&t?qn(e,t).key:null;(0,c.useEffect)(()=>{e&&t&&$n.request(e,t)},[n]);let r=L(Bn,n=>e&&t?Qn(n,e,t):null),i=F(e=>r?e.entitiesById[r]??null:null);if(r!==void 0)return r?i:null}var tr=3e4,nr=1e4,rr=3e3,ir=100,ar=new Set([`succeeded`,`failed`]),or=null,sr=e=>e?Array.isArray(e)?e.reduce((e,t)=>(t?.entity_id&&(e[t.entity_id]=t),e),{}):Object.entries(e).reduce((e,[t,n])=>((n?.entity_id||t)&&(e[n.entity_id||t]=n),e),{}):{},cr=()=>{let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();if(typeof e?.getRandomValues==`function`){let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join(`-`)}return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return(e===`x`?t:t&3|8).toString(16)})},lr=()=>{let e=C();if(/^wss?:\/\//.test(e)){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/,``)}/ws/entities/`,t.toString()}return`${window.location.protocol===`https:`?`wss:`:`ws:`}//${e}/ws/entities/`},ur=`graphcore.bearer`,dr=()=>{let e={current:null},t={current:{token:null,principalEntityId:null}},n={current:0},r={current:null},i={current:null},a={current:null},o={current:ir},s={current:{outstanding:new Set,since:0,nextId:0}},c={current:null},l={current:null},u=new Map,d={current:{}},f={current:0},p={current:null},m=`idle`,h=e=>{m=e,ie(e)},g=()=>{r.current&&=(clearTimeout(r.current),null)},_=()=>{i.current&&=(clearInterval(i.current),null)},v=()=>{a.current&&=(clearTimeout(a.current),null)},y=()=>{d.current={},f.current=0,p.current!==null&&(window.cancelAnimationFrame(p.current),p.current=null)},b=()=>{p.current=null;let e=d.current;Object.keys(e).length!==0&&(d.current={},f.current=0,I.mergeEntities(e),$n.noteEntities(Object.values(e)))},x=e=>{let t=d.current;Object.entries(sr(e)).forEach(([e,n])=>{M(n,t[e])||(t[e]=n)}),f.current+=1,p.current===null&&(p.current=window.requestAnimationFrame(b))},S=(e,t,n,r={})=>{let i=u.get(e);i&&(clearTimeout(i.timeout),u.delete(e),t?i.resolve(n):i.reject(new ae(r.error||`Strategy execution failed`,{code:r.error_code,details:r.error_details,strategyRequestId:r.requestId??i.requestId})))},C=e=>{u.forEach((t,n)=>{let r=t.requestId?e[t.requestId]:void 0;r&&ar.has(r.status)&&S(n,r.status===`succeeded`,r.ret_val,{...r,requestId:r.entity_id})})},w=(e,t=!1)=>{u.forEach((n,r)=>{t&&n.requestId||(clearTimeout(n.timeout),n.reject(e),u.delete(r))})},T=e=>{b();let t={};I.getEntityIds().forEach(e=>{t[e]=I.readEntity(e)?.etag??``}),u.forEach(e=>{e.requestId&&(t[e.requestId]=``)});let n=s.current;n.outstanding=new Set,n.since=Date.now();let r=Object.keys(t);for(let i=0;i<r.length;i+=o.current){let a=r.slice(i,i+o.current);n.nextId+=1,n.outstanding.add(n.nextId),e.send(JSON.stringify({command:`resync`,resync_id:n.nextId,entities:Object.fromEntries(a.map(e=>[e,t[e]]))}))}n.outstanding.size===0&&ue(n.since)},E=e=>{let t=s.current;!t.outstanding.delete(e)||t.outstanding.size>0||(b(),ue(t.since))},D=(t=`Cleaning up connection`)=>{_(),v(),y();let n=e.current;if(n){if(n.readyState===WebSocket.CONNECTING)n.onopen=()=>n.close(1e3,t);else try{n.close(1e3,t)}catch(e){console.error(`Error closing GraphCore WebSocket:`,e)}}e.current=null},O=t=>{let n=e.current;t&&n&&n.readyState===WebSocket.OPEN&&(I.isRequested(t)||I.isNotFound(t)||(I.markRequested(t),n.send(JSON.stringify({command:`get_entity`,entity_id:t}))))},k=()=>{let r=t.current.token,a=t.current.principalEntityId;if(!r){h(`idle`);return}g(),D(`Reconnecting`),h(`connecting`);let s=new WebSocket(lr(),[ur,r]);e.current=s,s.onopen=()=>{n.current=0,h(`connected`),t.current.token&&t.current.token!==r&&s.send(JSON.stringify({command:`reauth`,token:t.current.token})),a&&s.send(JSON.stringify({command:`subscribe_entities`,entity_ids:[a]})),_(),i.current=setInterval(()=>j(s,nr),tr)},s.onmessage=e=>{try{let t=JSON.parse(e.data);if(t.type===`auth_error`){l.current?.(t.message||`Session expired. Please log in again.`);return}if(t.type===`connected`){typeof t.max_batch_size==`number`&&t.max_batch_size>0&&(o.current=t.max_batch_size),T(s);return}if(t.type===`resync`){T(s);return}if(t.type===`resync_done`){t.error&&console.error(`GraphCore resync failed:`,t.error),E(t.resync_id);return}if(t.type===`pong`){v();return}if(t.type===`entity_update`){let e=sr(t.entities);C(e),x(e);return}if(t.type===`strategy_queued`){let e=u.get(t.client_request_id);e&&(e.requestId=t.request_id);return}if(t.type===`entity_not_found`){I.markNotFound(t.entity_id);return}if(t.type===`access_revoked`){x({[t.resource_id]:{entity_id:t.resource_id,forbidden:!0}}),se(t.resource_id);return}if(t.type===`access_granted`||t.type===`access_changed`){I.clearEntityFlags(t.resource_id),O(t.resource_id),se(t.resource_id);return}if(t.type===`strategy_result`){S(t.client_request_id,t.success,t.ret_val,{...t,requestId:t.request_id});return}if(t.type===`error`){let e=typeof t.error==`object`?t.error.message||JSON.stringify(t.error):t.error||t.message||`Unknown server error`;console.error(`GraphCore server error:`,e)}}catch(e){console.error(`Error parsing GraphCore WebSocket message:`,e)}},s.onerror=e=>{console.error(`GraphCore WebSocket error:`,e)},s.onclose=e=>A(s,e.code)},A=(i,a,o=!1)=>{if(e.current===i){if(_(),v(),e.current=null,I.clearRequestedEntities(),b(),w(Error(`Connection lost before the request was queued`),!0),h(t.current.token?`disconnected`:`idle`),o&&t.current.token)k();else if(a!==1e3&&t.current.token){let e=Math.min(3e4,2**n.current*500);r.current=setTimeout(()=>{n.current+=1,k()},e)}else n.current=0}},j=(e,t)=>{e.readyState===WebSocket.OPEN&&(e.send(JSON.stringify({command:`ping`})),v(),a.current=setTimeout(()=>{a.current=null,e.onopen=null,e.onmessage=null,e.onclose=null;try{e.close()}catch{}A(e,4e3,!0)},t))},N=()=>{if(!t.current.token)return;let r=e.current;!r||r.readyState===WebSocket.CLOSING||r.readyState===WebSocket.CLOSED?(n.current=0,k()):r.readyState===WebSocket.OPEN&&j(r,rr)},ee=()=>{if(c.current||typeof window>`u`)return;let e=()=>{document.visibilityState===`visible`&&N()},t=e=>{e.persisted&&N()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`online`,N),window.addEventListener(`pageshow`,t),c.current=()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`online`,N),window.removeEventListener(`pageshow`,t)}};return or=u,{pendingRequests:u,wsRef:e,connect(n){let r=n.token??null,i=n.principalEntityId??null,a=t.current.principalEntityId!==i,o=t.current.token;t.current={token:r,principalEntityId:i},r?(ee(),a||!e.current||e.current.readyState===WebSocket.CLOSED||e.current.readyState===WebSocket.CLOSING?k():e.current.readyState===WebSocket.OPEN&&r!==o&&e.current.send(JSON.stringify({command:`reauth`,token:r}))):this.disconnect(`Authentication ended`)},disconnect(e=`Cleaning up connection`){t.current={token:null,principalEntityId:null},g(),I.clearRequestedEntities(),y(),D(e),h(`idle`),w(Error(`Connection closed`))},dispose(){this.disconnect(`Disposing bridge`),g(),_(),c.current?.(),c.current=null,or===u&&(or=null)},fetchEntity:O,subscribe(t){let n=e.current;n&&n.readyState===WebSocket.OPEN&&t.length!==0&&n.send(JSON.stringify({command:`subscribe_entities`,entity_ids:t}))},executeStrategy(t,n={}){let r=e.current;if(!r||r.readyState!==WebSocket.OPEN){let e=Error(`No active WebSocket connection`);if(n.awaitResponse)return Promise.reject(e);throw e}let i=!!n.awaitResponse,a=n.timeout??6e4;if(i){let e=cr(),n={...t,client_request_id:e};return new Promise((t,i)=>{let o=setTimeout(()=>{u.delete(e),i(Error(`Request timeout after ${a}ms`))},a);u.set(e,{resolve:e=>{t(e)},reject:e=>{i(e)},timeout:o}),r.send(JSON.stringify({command:`execute_strategy`,strategy:[n],await_response:!0}))})}let o=Array.isArray(t)?t:t==null?[]:[t];r.send(JSON.stringify({command:`execute_strategy`,strategy:o}))},getStatus(){return m},setOnAuthError(e){l.current=e},ping(){e.current&&j(e.current,nr)}}},fr=e=>Symbol.iterator in e,pr=e=>`entries`in e,mr=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},hr=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function gr(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:fr(e)&&fr(t)?pr(e)&&pr(t)?mr(e,t):hr(e,t):mr({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}var _r=(e,t={})=>{let n=e?.entity_type_id,r=Array.isArray(t.types)?t.types.filter(Boolean):[],i=Array.isArray(t.excludeTypes)?t.excludeTypes.filter(Boolean):[];return!(r.length>0&&!r.includes(n)||i.length>0&&i.includes(n))},vr=e=>I.readEntity(e),yr=e=>{let t=vr(e);return Array.isArray(t?.children_ids)?t.children_ids.filter(Boolean):[]},br=(e,t={})=>!e||t.enabled===!1?[]:yr(e).map(e=>vr(e)).filter(e=>!!e).filter(e=>_r(e,t)),xr=(e,t={})=>{if(!e||t.enabled===!1)return null;let n=(r,i=new Set)=>{if(i.has(r))return null;i.add(r);let a=vr(r);if(!a)return null;let o=yr(r).reduce((e,t)=>{let r=n(t,new Set(i));return r&&(e[t]=r),e},{});return _r(a,t)||Object.keys(o).length>0||t.includeRoot&&r===e?{entity:a,children:o}:null};return n(e)},Sr={readEntity(e){return vr(e)},readEntities(e){return I.readEntities(e)},readChildren(e,t={}){return br(e,t)},readRecursiveChildren(e,t={}){return xr(e,t)}},Cr=()=>{let e=D();if(!e)throw Error(`useGraphCoreBridge must be used within GraphCoreProvider.`);return e},wr=()=>{let e=Cr();return(0,c.useMemo)(()=>e.executeStrategy.bind(e),[e])},Tr=(e,t)=>{t&&e.forEach(e=>{!e||I.readEntity(e)||I.isNotFound(e)||t(e)})},X=e=>{let t=Cr(),n=R(),r=F((0,c.useMemo)(()=>t=>e?t.entitiesById[e]??null:null,[e]));return(0,c.useEffect)(()=>{Tr([e],t.fetchEntity)},[t,n,e,r]),r},Er=e=>{let t=Cr(),n=(0,c.useMemo)(()=>e.filter(Boolean),[e]),r=R(),i=F(e=>n.map(t=>e.entitiesById[t]??null).filter(e=>!!e),gr);return(0,c.useEffect)(()=>{Tr(n,t.fetchEntity)},[t,r,i,n]),i},Dr=(e,t={})=>{let n=Cr(),r=X(e),i=(0,c.useMemo)(()=>Array.isArray(r?.children_ids)?r.children_ids.filter(Boolean):[],[r?.children_ids]),a=R(),o=F(()=>Sr.readChildren(e,t),gr);return(0,c.useEffect)(()=>{Tr(i,n.fetchEntity)},[n,a,i]),o},Or=(e,t={})=>{let n=Cr(),r=R(),i=F(e=>e.entityIds),a=(0,c.useMemo)(()=>Sr.readRecursiveChildren(e,t),[i,t,e]);return(0,c.useEffect)(()=>{Tr([e],n.fetchEntity)},[n,r,e]),a},kr=e=>e?.attributes??{},Ar=(e,t)=>kr(e)[t],jr=e=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==`attributes`));function Mr(e){return(typeof e==`string`?e:e?.entity_type_id)?.split(`.`).pop()??``}function Z(e){return[e?.username,e?.name,Ar(e,`name`),Mr(e),e?.entity_id].find(e=>typeof e==`string`&&e.trim().length>0)??`Entity`}var Nr=()=>{let e=F(e=>e.entityIds,gr),t=(0,c.useCallback)(e=>{I.mergeEntities(e)},[]);async function n(){try{let e=await q.getEntityDirectory();t(e.entities||e)}catch(e){console.error(`Failed to fetch entity types:`,e)}}return{entityIds:e,mergeEntities:t,fetchEntityTypes:n,clearEntities:(0,c.useCallback)(()=>{I.clearEntities()},[])}},Pr=()=>{let e=fe(),{mergeEntities:t,clearEntities:n}=Nr(),{isAuthenticated:r,isLoading:i,token:a,principalEntityId:o,username:s,error:c}=e;function l(e){V(t=>({...t,error:e}))}async function u(e){V(e=>({...e,isLoading:!0,error:null}));try{await It(e)}catch(e){console.error(`Sign-in error:`,e),V(t=>({...t,isLoading:!1,error:e.message||`Sign-in failed`}))}}let d=()=>u(),f=()=>u({createAccount:!0});async function p(){n(),$n.clear(),V(de());try{await Wt()}catch(e){console.error(`Sign-out error:`,e)}}async function m(e,n){let r=e||o,i=n||a;if(!r)console.warn(`Cannot load user entities: no principalEntityId provided`);else try{let e=await q.getEntity(r,i);e&&t([e])}catch(e){console.error(`Error loading user entities:`,e),l(`Failed to load user entities: ${e.message}`)}}async function h(){if(!a||!o)return!1;try{return await m(o),!0}catch(e){return console.error(`Token validation failed:`,e),p(),!1}}return{isAuthenticated:r,isLoading:i,token:a,principalEntityId:o,username:s,error:c,login:d,register:f,logout:p,loadUserEntities:m,validateToken:h,setAuthError:l}},Fr=k(()=>null),Ir=e=>{Fr.setState(e,!0)},Lr=()=>L(Fr,e=>e),Rr={error:`bg-red-50 border-red-200 text-red-700`,success:`bg-green-50 border-green-200 text-green-700`,info:`bg-blue-50 border-blue-200 text-blue-700`},zr=()=>{let e=Ln();if((0,c.useEffect)(()=>{if(!e)return;let t=setTimeout(()=>Fn(null),5e3);return()=>clearTimeout(t)},[e]),!e)return null;let t=typeof e.message==`string`?e.message:JSON.stringify(e.message);return(0,u.jsx)(`div`,{className:`pointer-events-none fixed inset-x-0 top-4 z-10000 flex justify-center px-4`,children:(0,u.jsxs)(`div`,{className:`pointer-events-auto flex max-w-md items-center gap-3 rounded-lg border px-4 py-3 text-sm shadow-lg ${Rr[e.type]||Rr.info}`,children:[(0,u.jsx)(`span`,{className:`flex-1`,children:t}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>Fn(null),className:`text-lg leading-none opacity-60 hover:opacity-100`,"aria-label":`Dismiss notification`,children:`×`})]})})},Br=(0,c.createContext)(null),Vr=Br.Provider;function Hr(){let e=(0,c.useContext)(Br);if(!e)throw Error(`useViewRegistry() must be called within a <GraphCoreProvider registry={...}>.`);return e}function Ur(e){return J({tag:`svg`,attr:{viewBox:`0 0 640 512`},child:[{tag:`path`,attr:{d:`M622.3 271.1l-115.2-45c-4.1-1.6-12.6-3.7-22.2 0l-115.2 45c-10.7 4.2-17.7 14-17.7 24.9 0 111.6 68.7 188.8 132.9 213.9 9.6 3.7 18 1.6 22.2 0C558.4 489.9 640 420.5 640 296c0-10.9-7-20.7-17.7-24.9zM496 462.4V273.3l95.5 37.3c-5.6 87.1-60.9 135.4-95.5 151.8zM224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm96 40c0-2.5.8-4.8 1.1-7.2-2.5-.1-4.9-.8-7.5-.8h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c6.8 0 13.3-1.5 19.2-4-54-42.9-99.2-116.7-99.2-212z`},child:[]}]})(e)}function Wr(e){return J({tag:`svg`,attr:{viewBox:`0 0 352 512`},child:[{tag:`path`,attr:{d:`M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z`},child:[]}]})(e)}function Gr(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M497 273L329 441c-15 15-41 4.5-41-17v-96H152c-13.3 0-24-10.7-24-24v-96c0-13.3 10.7-24 24-24h136V88c0-21.4 25.9-32 41-17l168 168c9.3 9.4 9.3 24.6 0 34zM192 436v-40c0-6.6-5.4-12-12-12H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h84c6.6 0 12-5.4 12-12V76c0-6.6-5.4-12-12-12H96c-53 0-96 43-96 96v192c0 53 43 96 96 96h84c6.6 0 12-5.4 12-12z`},child:[]}]})(e)}function Kr(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z`},child:[]}]})(e)}function qr(e){return J({tag:`svg`,attr:{viewBox:`0 0 640 512`},child:[{tag:`path`,attr:{d:`M32,224H64V416H32A31.96166,31.96166,0,0,1,0,384V256A31.96166,31.96166,0,0,1,32,224Zm512-48V448a64.06328,64.06328,0,0,1-64,64H160a64.06328,64.06328,0,0,1-64-64V176a79.974,79.974,0,0,1,80-80H288V32a32,32,0,0,1,64,0V96H464A79.974,79.974,0,0,1,544,176ZM264,256a40,40,0,1,0-40,40A39.997,39.997,0,0,0,264,256Zm-8,128H192v32h64Zm96,0H288v32h64ZM456,256a40,40,0,1,0-40,40A39.997,39.997,0,0,0,456,256Zm-8,128H384v32h64ZM640,256V384a31.96166,31.96166,0,0,1-32,32H576V224h32A31.96166,31.96166,0,0,1,640,256Z`},child:[]}]})(e)}function Jr(e){return J({tag:`svg`,attr:{viewBox:`0 0 448 512`},child:[{tag:`path`,attr:{d:`M320 448v40c0 13.255-10.745 24-24 24H24c-13.255 0-24-10.745-24-24V120c0-13.255 10.745-24 24-24h72v296c0 30.879 25.121 56 56 56h168zm0-344V0H152c-13.255 0-24 10.745-24 24v368c0 13.255 10.745 24 24 24h272c13.255 0 24-10.745 24-24V128H344c-13.2 0-24-10.8-24-24zm120.971-31.029L375.029 7.029A24 24 0 0 0 358.059 0H352v96h96v-6.059a24 24 0 0 0-7.029-16.97z`},child:[]}]})(e)}function Yr(e){return J({tag:`svg`,attr:{viewBox:`0 0 448 512`},child:[{tag:`path`,attr:{d:`M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z`},child:[]}]})(e)}function Xr(e){return J({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z`},child:[]}]})(e)}var Zr=/version: (\S+)/,Qr=0;async function $r(e){let t=await fetch(`${S()}/mcp`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,Authorization:`Bearer ${B.getState().token??``}`},body:JSON.stringify({jsonrpc:`2.0`,id:++Qr,method:`tools/call`,params:{name:`open`,arguments:{at:e}}})});if(!t.ok)throw Error(`The agent frontend answered ${t.status}`);let n=await t.json();if(n.error)throw Error(n.error.message);let r=(n.result?.content??[]).map(e=>e.text??``).join(`
2
- `);if(n.result?.isError)throw Error(r);return{text:r,version:Zr.exec(r)?.[1]??null}}var ei=`e/:backend_id/:local_id`,ti=`[0-9a-hjkmnp-tv-z]`,ni=RegExp(`gc:/+(${ti}{10})/(${ti}{12})(?![0-9A-Za-z])`);function ri(e){return`/e/${e.replace(/^gc:\/\//,``)}`}function ii(e){let{backend_id:t,local_id:n}=e;return t&&n?`gc://${t}/${n}`:null}function ai(e){let t=e;try{t=decodeURIComponent(e)}catch{}let n=ni.exec(t);return n?`gc://${n[1]}/${n[2]}`:null}var oi=`graphcore.agent_mirror`,si=2e3,ci=(0,c.createContext)(!1),li=()=>{try{return localStorage.getItem(oi)===`1`}catch{return!1}},ui=k(()=>({open:li()}));function di(e){ui.setState({open:e});try{localStorage.setItem(oi,e?`1`:`0`)}catch{}}function fi(e){let[t,n]=(0,c.useState)({place:null,error:null,changed:!1});return(0,c.useEffect)(()=>{let t=!1,r=!1,i=!1,a=null,o,s;n({place:null,error:null,changed:!1});let c=async()=>{if(r)i=!0;else{r=!0;try{let r=await $r(e);if(t)return;let i=a!==null&&r.version!==a;a=r.version,n({place:r,error:null,changed:i}),i&&(clearTimeout(s),s=setTimeout(()=>n(e=>({...e,changed:!1})),si))}catch(e){if(t)return;n(t=>({...t,error:e instanceof Error?e.message:String(e),changed:!1}))}finally{r=!1}i&&!t&&(i=!1,c())}};c();let l=P.subscribe((e,t)=>{e.entitiesById!==t.entitiesById&&(clearTimeout(o),o=setTimeout(c,250))});return()=>{t=!0,clearTimeout(o),clearTimeout(s),l()}},[e]),t}var pi=`[0-9a-hjkmnp-tv-z]`,mi=RegExp(`(gc://${pi}{10}/${pi}{12}|/e/${pi}{10}/${pi}{12})`,`g`);function hi({text:e}){let t=e.split(mi);return(0,u.jsx)(u.Fragment,{children:t.map((e,t)=>t%2?(0,u.jsx)(d.Link,{to:e.startsWith(`gc://`)?ri(e):e,className:`text-blue-700 hover:underline`,children:e},t):e)})}function gi({text:e}){return(0,u.jsx)(`div`,{className:`space-y-0.5 font-mono text-xs text-gray-800`,children:e.split(`
3
- `).map((e,t)=>e.startsWith(`# `)?(0,u.jsx)(`h2`,{className:`font-sans text-base font-semibold text-gray-900`,children:(0,u.jsx)(hi,{text:e.slice(2)})},t):e.startsWith(`## `)?(0,u.jsx)(`h3`,{className:`pt-2 font-sans text-sm font-semibold text-gray-900`,children:(0,u.jsx)(hi,{text:e.slice(3)})},t):e.startsWith(`- `)?(0,u.jsxs)(`div`,{className:`break-all pl-3 -indent-3`,children:[`• `,(0,u.jsx)(hi,{text:e.slice(2)})]},t):e.trim()?(0,u.jsx)(`div`,{className:`break-all text-gray-600`,children:(0,u.jsx)(hi,{text:e})},t):(0,u.jsx)(`div`,{className:`h-2`},t))})}function _i({address:e}){let{place:t,error:n,changed:r}=fi(e),[i,a]=(0,c.useState)(!1);return(0,u.jsxs)(`aside`,{"aria-label":`Agent view`,className:`flex h-full w-2/5 min-w-80 flex-col border-l border-gray-200 bg-white`,children:[(0,u.jsxs)(`header`,{className:`flex items-center gap-2 border-b border-gray-200 px-3 py-2 text-xs text-gray-600 transition-colors ${r?`bg-amber-50`:``}`,children:[(0,u.jsx)(qr,{className:`h-3.5 w-3.5 shrink-0 text-gray-500`}),(0,u.jsx)(`code`,{className:`min-w-0 truncate text-gray-900`,children:e}),t?.version&&(0,u.jsxs)(`span`,{className:`shrink-0 font-mono text-gray-400`,children:[`v`,t.version.slice(0,8)]}),r&&(0,u.jsx)(`span`,{className:`shrink-0 rounded bg-amber-200 px-1.5 text-amber-900`,children:`changed`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>a(!i),className:`ml-auto shrink-0 rounded border border-gray-200 px-2 py-0.5 hover:bg-gray-50`,children:i?`Formatted`:`Raw`}),(0,u.jsx)(`button`,{type:`button`,"aria-label":`Close agent view`,onClick:()=>di(!1),className:`shrink-0 rounded p-1 hover:bg-gray-100`,children:(0,u.jsx)(Wr,{className:`h-3 w-3`})})]}),(0,u.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:[n&&(0,u.jsx)(`div`,{role:`alert`,className:`mb-3 whitespace-pre-wrap rounded border border-red-200 bg-red-50 p-2 font-mono text-xs text-red-700`,children:n}),t?i?(0,u.jsx)(`pre`,{className:`whitespace-pre-wrap break-all font-mono text-xs text-gray-800`,children:t.text}):(0,u.jsx)(gi,{text:t.text}):!n&&(0,u.jsxs)(`div`,{className:`text-xs text-gray-400`,children:[`Opening `,e,`…`]})]})]})}function vi({address:e,children:t}){let n=(0,c.useContext)(ci),r=L(ui,e=>e.open);return n?(0,u.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,u.jsxs)(`div`,{className:`relative h-full min-w-0 flex-1`,children:[t,!r&&(0,u.jsxs)(`button`,{type:`button`,onClick:()=>di(!0),className:`absolute bottom-3 right-3 z-10 flex items-center gap-1.5 rounded-full border border-gray-200 bg-white px-3 py-1.5 text-xs text-gray-700 shadow-sm hover:bg-gray-50`,children:[(0,u.jsx)(qr,{className:`h-3.5 w-3.5`}),`Agent view`]})]}),r&&(0,u.jsx)(_i,{address:e})]}):(0,u.jsx)(u.Fragment,{children:t})}function yi({getToken:e,principalEntityId:t}){return(0,c.useEffect)(()=>{let n=e();n&&V(e=>({...e,isAuthenticated:!0,isLoading:!1,token:n,principalEntityId:t??e.principalEntityId}))},[e,t]),null}function bi(){let{mergeEntities:e,clearEntities:t}=Nr();return(0,c.useEffect)(()=>{let n=!1,r=()=>{},i=Ut(()=>window.location.reload()),a=e=>{V(t=>t.isAuthenticated?{...t,token:e.access_token}:t)},o=()=>{t(),$n.clear(),V({...de(),error:Tt})},s=Bt(o);return(async()=>{try{let t=await Mt();t.events.addUserLoaded(a),t.events.addSilentRenewError(o),r=()=>{t.events.removeUserLoaded(a),t.events.removeSilentRenewError(o)};let i=await Ht();if(n)return;if(!i){V(e=>({...e,isLoading:!1}));return}let s=await q.me(i.access_token);if(n)return;V(e=>({...e,isAuthenticated:!0,isLoading:!1,error:null,token:i.access_token,principalEntityId:s.principal_entity_id,username:s.username}));let c=await q.getEntity(s.principal_entity_id,i.access_token);!n&&c&&e([c])}catch(e){if(n)return;console.error(`Sign-in error:`,e),V(t=>({...t,isLoading:!1,error:e instanceof Error?e.message:`Sign-in failed`}))}})(),()=>{n=!0,r(),i(),s()}},[e,t]),null}function xi({bridge:e}){let{isAuthenticated:t,token:n,principalEntityId:r}=Pr();return(0,c.useEffect)(()=>(e.setOnAuthError(async e=>{(w()||!await zt())&&Fn({message:e,type:`error`})}),()=>e.setOnAuthError(null)),[e]),(0,c.useEffect)(()=>{t&&n?e.connect({token:n,principalEntityId:r}):e.disconnect(`Authentication ended`)},[e,t,n,r]),null}function Si({apiUrl:e}){return(0,c.useEffect)(()=>{let e=!1;return q.getIdentity().then(t=>{e||Ir(t?.deployment_entity_id??null)}).catch(()=>{e||Ir(null)}),()=>{e=!0}},[e]),null}function Ci({apiUrl:e,wsUrl:t,registry:n,getToken:r,principalEntityId:i,agentMirror:a=!1,basePath:o,children:s}){let l=(0,c.useMemo)(()=>dr(),[]);return _(e,t,r),y(o),(0,c.useEffect)(()=>()=>{l.dispose()},[l]),(0,u.jsx)(Vr,{value:n,children:(0,u.jsxs)(E,{value:l,children:[r?(0,u.jsx)(yi,{getToken:r,principalEntityId:i}):(0,u.jsx)(bi,{}),(0,u.jsx)(xi,{bridge:l}),(0,u.jsx)(Si,{apiUrl:e}),(0,u.jsx)(ci.Provider,{value:a,children:s}),(0,u.jsx)(zr,{})]})})}function wi(){let[e,t]=(0,c.useState)(!1);return(0,c.useEffect)(()=>{let e=!0;return Pt().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}var Ti=`/invite`;function Ei(e){return`${window.location.origin}${x(Ti)}#${e}`}var Di=e=>e.startsWith(`#`)?decodeURIComponent(e.slice(1)):``;function Oi(){let{pathname:e,hash:t}=(0,d.useLocation)();return e===`/invite`&&!!Di(t)}function ki({onRedeemed:e}){let{hash:t}=(0,d.useLocation)(),n=(0,d.useNavigate)(),[r,i]=(0,c.useState)(null),a=(0,c.useRef)(null),o=Di(t);(0,c.useEffect)(()=>{o&&a.current!==o&&(a.current=o,q.redeemInvite(o).then(t=>{e?e(t):n(ri(t.resource_id),{replace:!0})}).catch(e=>i(e.message||`This invite is invalid or has expired`)))},[o,e,n]);let s=(0,u.jsx)(`p`,{className:`text-gray-600`,role:`status`,children:`Accepting invite…`});return o?r&&(s=(0,u.jsx)(`p`,{role:`alert`,className:`text-red-600`,children:r})):s=(0,u.jsx)(`p`,{className:`text-gray-600`,children:`This invite link is incomplete.`}),(0,u.jsx)(`div`,{className:`flex h-full items-center justify-center p-8 text-center`,children:s})}var Ai=({className:e,title:t=`graphcore`})=>{let{login:n,register:r,isLoading:i,error:a}=Pr(),o=wi(),s=Oi();return(0,u.jsx)(`div`,{className:e??`min-h-screen flex items-center justify-center bg-linear-to-br from-blue-50 to-indigo-100 px-4`,children:(0,u.jsxs)(`div`,{className:`max-w-md w-full bg-white rounded-lg shadow-xl p-8`,children:[(0,u.jsxs)(`div`,{className:`text-center mb-8`,children:[(0,u.jsx)(`h1`,{className:`text-3xl font-bold text-gray-900 mb-2`,children:t}),(0,u.jsx)(`p`,{className:`text-gray-600`,role:i?`status`:void 0,children:i?`Please wait...`:s?`You've been invited. Sign in to accept.`:`Sign in to continue`})]}),a&&(0,u.jsx)(`div`,{className:`mb-6 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg text-sm`,children:a}),!i&&(0,u.jsxs)(`div`,{className:`space-y-3`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>n(),className:`w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2.5 px-4 rounded-lg transition focus:ring-4 focus:ring-blue-300`,children:`Sign in`}),o&&(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(),className:`w-full border border-gray-300 text-gray-700 hover:bg-gray-50 font-medium py-2.5 px-4 rounded-lg transition`,children:`Create account`})]})]})})},ji=null;function Mi(){let[e,t]=(0,c.useState)(null);return(0,c.useEffect)(()=>{let e=!1;return ji??=q.getRoutes().then(e=>e.routes),ji.then(n=>!e&&t(n)).catch(()=>{ji=null,e||t([])}),()=>{e=!0}},[]),e}function Ni(){let e=Cr(),t=R();return{sendStrategyRequest:(0,c.useCallback)((t,n={})=>{try{let r=e.executeStrategy(t,n);return n.awaitResponse&&r?.catch?r.catch(e=>{throw console.error(`Awaited strategy request failed:`,e),Fn({message:e?.message||`Request failed. Please try again.`,type:`error`}),e}):r}catch(e){if(console.error(`Error sending strategy request:`,e),Fn({message:`Error sending request. Please try again.`,type:`error`}),n.awaitResponse)return Promise.reject(e)}},[e]),isConnected:t===`connected`,bridge:e}}var Pi=50,Fi=250,Ii=!1;function Li({typeIds:e,parentId:t,where:n,grantedToMe:r=!1,limit:i=Pi,enabled:a=!0}){let[o,s]=(0,c.useState)([]),[l,u]=(0,c.useState)(null),[d,f]=(0,c.useState)(!1),p=(0,c.useRef)(0),m=(0,c.useRef)(0),h=(0,c.useRef)({ids:new Set,bound:null}),g=e.join(`,`),_=n?JSON.stringify(n):``,v=(0,c.useCallback)(async e=>{if(!g)return;let n=p.current;f(!0);try{let a=await q.listEntities({type_ids:g.split(`,`),parent_id:t,where:_?JSON.parse(_):void 0,...r?{granted_to_me:!0}:{},cursor:e,limit:i});if(n!==p.current)return;let o=a?.entities??[];Ii=!0;try{I.mergeEntities(o)}finally{Ii=!1}let c=o.map(e=>e.entity_id);s(t=>e?[...t,...c]:c),u(a?.next_cursor??null)}catch(e){console.error(`Failed to list entities:`,e),n===p.current&&In(`Could not load entities`,e)}finally{n===p.current&&f(!1)}},[g,t,_,r,i]),y=(0,c.useCallback)(()=>{p.current+=1,m.current=Date.now(),v(null)},[v]);(0,c.useEffect)(()=>{a&&(s([]),u(null),y())},[a,y]),(0,c.useEffect)(()=>{h.current={ids:new Set(o),bound:l===null?null:o[o.length-1]??null}},[o,l]),(0,c.useEffect)(()=>{if(!a||!g)return;let e=new Set(g.split(`,`)),n,r=()=>{clearTimeout(n),n=setTimeout(y,Fi)},i=oe(r),o=le(e=>{m.current<e&&r()}),c=P.subscribe((n,i)=>{if(Ii||n.entitiesById===i.entitiesById)return;let a=t=>e.has(t?.entity_type_id),o=Object.keys(n.entitiesById).filter(e=>n.entitiesById[e].forbidden&&a(i.entitiesById[e])),c=e=>{let r=n.entitiesById[e];if(!a(r))return!1;let{ids:i,bound:o}=h.current;if(!i.has(e)&&o!==null&&e>o)return!1;if(_)return!0;let s=typeof t!=`string`||r.parent_id===t;return i.has(e)?!s:s};(o.length>0||Object.keys(n.entitiesById).some(e=>n.entitiesById[e]!==i.entitiesById[e]&&c(e))||Object.keys(i.entitiesById).some(e=>!(e in n.entitiesById)&&h.current.ids.has(e)))&&(o.length>0&&s(e=>e.filter(e=>!o.includes(e))),r())});return()=>{c(),i(),o(),clearTimeout(n)}},[a,g,t,_,y]);let b=(0,c.useCallback)(()=>{l&&!d&&v(l)},[l,v,d]);return{ids:o,hasMore:l!==null,loading:d,loadMore:b,refresh:y}}k(()=>({contents:{},state:`loading`,error:null}));var Ri=k(()=>({contents:{},state:`loading`,error:null})),zi=null,Bi=async()=>Ri.getState().state===`hasValue`?Ri.getState().contents:zi||(Ri.setState(e=>({...e,state:`loading`,error:null})),zi=q.getEntityDirectory().then(e=>{let t=e?.entities||e||{};return Ri.setState({contents:t,state:`hasValue`,error:null}),t}).catch(e=>(console.error(`Failed to fetch available entities:`,e),Ri.setState({contents:{},state:`hasError`,error:e}),{})).finally(()=>{zi=null}),zi),Vi=()=>L(Ri),Hi=()=>Vi(),Q=class{constructor(){this.reset()}reset(){return this.request={strategy_name:``,target_entity_id:null,param_config:{}},this}withStrategyName(e){return this.request.strategy_name=e,this}withTargetEntity(e){return this.request.target_entity_id=e,this}withParams(e){return this.request.param_config={...this.request.param_config,...e},this}build(){return{...this.request}}},$={builder(){return new Q},createGrant(e,t,n){return new Q().withStrategyName(`CreateGrant`).withTargetEntity(e).withParams({subject_id:t,role_name:n}).build()},changeGrantRole(e,t){return new Q().withStrategyName(`ChangeGrantRole`).withTargetEntity(e).withParams({role_name:t}).build()},revokeGrant(e){return new Q().withStrategyName(`RevokeGrant`).withTargetEntity(e).build()},setAttributes(e,t){return new Q().withStrategyName(`SetAttributes`).withTargetEntity(e).withParams({attribute_map:t}).build()},removeAttribute(e,t){return new Q().withStrategyName(`RemoveAttribute`).withTargetEntity(e).withParams({attribute_name:t}).build()},createEntity(e,t,n={},r=null){let i={entity_type_id:t,initial_attributes:n};return r&&(i.entity_uuid=r),new Q().withStrategyName(`CreateEntity`).withTargetEntity(e).withParams(i).build()},createGroup(e,{parentId:t=null,key:n=null,adminManaged:r=!1}={}){return new Q().withStrategyName(`CreateGroup`).withTargetEntity(t).withParams({name:e,key:n,admin_managed:r}).build()},setNewUserDefaults(e,t,n){return new Q().withStrategyName(`SetNewUserDefaults`).withTargetEntity(e).withParams({group_ids:t,roles:n}).build()},hideEntity(e,t=!0){return $.setAttributes(e,{hidden:t})},deleteEntity(e){return new Q().withStrategyName(`DeleteEntity`).withTargetEntity(e).build()},setViewState(e,{position:t,state:n,component:r}={}){let i=e?{state:n||{}}:{...t,state:n||{}};return r!==void 0&&(i.component=r),new Q().withStrategyName(`SetViewState`).withTargetEntity(e||null).withParams(i).build()},createView(e,{renders:t=null,component:n=null,state:r={}}={}){return new Q().withStrategyName(`CreateView`).withTargetEntity(e||null).withParams({renders:t,component:n,state:r}).build()},reparentChild(e,t){return new Q().withStrategyName(`ReparentChild`).withTargetEntity(e).withParams({parent_id:t}).build()},detachChild(e){return $.reparentChild(e,null)},moveChildBefore(e,t){return new Q().withStrategyName(`ReorderChild`).withTargetEntity(e).withParams({before_child_id:t}).build()},moveChildAfter(e,t){return new Q().withStrategyName(`ReorderChild`).withTargetEntity(e).withParams({after_child_id:t}).build()}};function Ui(e){return e.startsWith(`/`)?e.split(/[?#]/)[0].replace(/\/+$/,``)||`/`:null}function Wi(e,t=`web`){let n=Ui(e);return n?{client:t,address:n,placement:[]}:null}function Gi(e,t=`web`){return{client:t,view:e,placement:[]}}function Ki(e,t,n){if(!t)throw Error(`A view slot must be a non-empty string`);if(e.placement.length>=64)throw Error(`View placement is deeper than 64 steps`);return{...e,placement:[...e.placement,{slot:t,renders:n??null}]}}function qi(e){let{client:t,address:n,view:r,placement:i}=e;return n===void 0?{client:t,view:r,placement:i}:{client:t,address:n,placement:i}}var Ji=(0,c.createContext)(null);function Yi(){return(0,d.useInRouterContext)()?(0,d.useLocation)().pathname:null}function Xi(e){let t=Yi(),n=(0,c.useMemo)(()=>e&&t?Wi(t):null,[e,t]),r=er(n);return(0,c.useMemo)(()=>n?{position:n,view:r}:null,[n,r])}function Zi(){let e=(0,c.useContext)(Ji),t=Xi(!e);return e??t}var Qi=e=>{let t=e.slice(e.lastIndexOf(`.`)+1).replace(/_/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)};function $i(e,t){let n=Zi(),r=n?.position??null,i=!!n?.route;return(0,c.useMemo)(()=>r&&!i?Ki(r,e,t):r,[r,i,e,t])}function ea({position:e,children:t}){let n=er(e),r=(0,c.useMemo)(()=>({position:e,view:n}),[e,n]);return(0,u.jsx)(Ji.Provider,{value:r,children:t})}function ta({address:e,children:t}){let n=(0,c.useMemo)(()=>Wi(e),[e]),r=er(n),i=(0,c.useMemo)(()=>({position:n,view:r,route:!0}),[n,r]);return(0,u.jsx)(Ji.Provider,{value:i,children:t})}function na(e,t,n={}){if(!e)throw Error(`A view name must be a non-empty string`);let r=({slot:n,...r})=>{let i=$i(n??e,r.entityId);return(0,u.jsx)(ea,{position:i,children:(0,u.jsx)(t,{...r})})};return r.displayName=`View(${e})`,Object.assign(r,{viewName:e,defaultFor:Object.freeze([...n.defaultFor??[]]),entry:!!n.entry,label:n.label??Qi(e),Component:t})}function ra(e){return typeof e==`function`&&typeof e.viewName==`string`&&`Component`in e}var ia=25;function aa({typeIds:e,onPick:t,exclude:n=[],labelFor:r=Z,disabled:i=!1,placeholder:a=`Search…`,className:o=``,autoFocus:s=!1,listPlacement:l=`above`}){let{ids:d,hasMore:f,loading:p,loadMore:m}=Li({typeIds:e,limit:ia}),h=Er(d),[g,_]=(0,c.useState)(``),[v,y]=(0,c.useState)(!1),b=(0,c.useMemo)(()=>{let e=g.trim().toLowerCase();return h.filter(t=>!n.includes(t.entity_id)&&(!e||r(t).toLowerCase().includes(e)))},[h,n,g,r]);return(0,c.useEffect)(()=>{g&&b.length<ia&&f&&m()},[g,b.length,f,m]),(0,u.jsxs)(`div`,{className:`graphcore-entity-picker relative ${o}`,children:[(0,u.jsx)(`input`,{type:`search`,value:g,disabled:i,placeholder:a,autoFocus:s,onFocus:()=>y(!0),onBlur:()=>y(!1),onChange:e=>_(e.target.value),className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 outline-none focus:border-slate-500`}),v&&(0,u.jsxs)(`ul`,{className:`absolute z-10 max-h-56 ${l===`above`?`bottom-full mb-1`:`top-full mt-1`} w-full overflow-y-auto divide-y divide-slate-100 rounded-md border border-slate-200 bg-white shadow-lg`,onMouseDown:e=>e.preventDefault(),onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<40&&m()},children:[b.map(e=>(0,u.jsx)(`li`,{children:(0,u.jsx)(`button`,{type:`button`,disabled:i,onClick:()=>{t(e),y(!1)},className:`w-full px-3 py-2 text-left text-sm text-slate-800 hover:bg-slate-50 disabled:opacity-50`,children:r(e)})},e.entity_id)),(p||b.length===0&&!f)&&(0,u.jsx)(`li`,{className:`px-3 py-2 text-xs text-slate-500`,children:p?`Loading…`:`No matches`})]})]})}var oa=(e,t,n)=>$.builder().withStrategyName(e).withTargetEntity(t).withParams(n).build();function sa({entityId:e}){if(!e)throw Error(`This view needs an entity to show.`);let{sendStrategyRequest:t}=Ni(),n=X(e),r=n?.member_ids??[],i=Er(r),[a,o]=(0,c.useState)(!1),s=async(n,r)=>{o(!0);try{await t(oa(n,e,r),{awaitResponse:!0})}finally{o(!1)}};return n?(0,u.jsxs)(`section`,{className:`graphcore-group-view space-y-6 p-6`,children:[(0,u.jsxs)(`label`,{className:`block space-y-1`,children:[(0,u.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-slate-500`,children:`Group name`}),(0,u.jsx)(`input`,{type:`text`,defaultValue:n.name??``,disabled:a,onBlur:e=>{let t=e.target.value.trim();t&&t!==n.name&&s(`ModifyGroup`,{name:t})},onKeyDown:e=>e.key===`Enter`&&e.currentTarget.blur(),className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-lg font-semibold text-slate-900`},n.name??``)]}),(0,u.jsxs)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:[i.length===0&&(0,u.jsx)(`li`,{className:`px-4 py-3 text-sm text-slate-500`,children:`No members yet.`}),i.map(e=>(0,u.jsxs)(`li`,{className:`flex items-center justify-between px-4 py-3 text-sm`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:Z(e)}),(0,u.jsx)(`button`,{type:`button`,disabled:a,onClick:()=>void s(`RemoveMember`,{principal_entity_id:e.entity_id}),className:`rounded-md px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-50`,children:`Remove`})]},e.entity_id))]}),(0,u.jsx)(aa,{typeIds:[Y.USER],exclude:r,disabled:a,placeholder:`Add a person…`,onPick:e=>void s(`AddMember`,{principal_entity_id:e.entity_id})})]}):(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500`,children:`Loading group…`})}var ca=na(`group_view`,sa,{defaultFor:[Y.GROUP]}),la=new Map;function ua(e,t){let n=la.get(e),[r,i]=(0,c.useState)(n||null),[a,o]=(0,c.useState)(!n),[s,l]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=(0,c.useCallback)(async()=>{la.has(e)||o(!0),d(null);try{let t=await q.getAccess(e);la.set(e,t),i(t)}catch(e){d(e?.message||`Unable to load access`)}finally{o(!1)}},[e]);(0,c.useEffect)(()=>{f()},[f]),(0,c.useEffect)(()=>oe(t=>{t===e&&f()}),[e,f]),(0,c.useEffect)(()=>le(()=>{f()}),[f]);let p=!!r?.can_manage,m=(0,c.useMemo)(()=>p&&r?.grants||[],[p,r]);(0,c.useEffect)(()=>{Bi()},[]);let h=X(e),g=Hi().contents,_=h?.entity_type_id?g[h.entity_type_id]:void 0,v=!!_?.shareable,y=_?.roles||[],b=_?.public_permissions||[],x=(0,c.useMemo)(()=>Object.entries(g).filter(([,e])=>e?.principal||e?.group).map(([e])=>e),[g]),S=(0,c.useCallback)(e=>`${Z(e)} (${g[e.entity_type_id]?.group?`group`:`person`})`,[g]),C=Er((0,c.useMemo)(()=>m.map(e=>e.subject_id).filter(e=>e!==`*`),[m])),w=(0,c.useMemo)(()=>{let e={"*":`Anyone signed in`};for(let t of C)e[t.entity_id]=Z(t);return e},[C]),T=(0,c.useMemo)(()=>m.find(e=>e.subject_id===`*`&&e.provenance===`direct`),[m]),E=(0,c.useCallback)(async e=>{l(!0);try{await t(e,{awaitResponse:!0}),await f()}finally{l(!1)}},[f,t]);return{summary:r,canManage:p,grants:m,shareable:v,roles:y,publicPermissions:b,subjectTypeIds:x,subjectLabel:S,labelsById:w,publicGrant:T,loading:a,busy:s,error:u,refresh:f,grant:(t,n)=>E($.createGrant(e,t,n)),changeRole:(e,t)=>E($.changeGrantRole(e,t)),revoke:e=>E($.revokeGrant(e)),setPublicRead:()=>E($.createGrant(e,`*`,`viewer`)),revokePublicRead:()=>T?.grant_entity_id?E($.revokeGrant(T.grant_entity_id)):Promise.resolve()}}var da=`/admin`,fa=`graphcore.admins`,pa=`member`,ma=[{id:`members`,label:`Members`},{id:`groups`,label:`Groups`},{id:`roles`,label:`Roles`},{id:`new-users`,label:`New users`}];function ha(e){let{ids:t,hasMore:n,loading:r,loadMore:i,refresh:a}=Li({typeIds:[e],limit:100});return(0,c.useEffect)(()=>{n&&!r&&i()},[n,r,i]),{entities:Er(t),refresh:a}}function ga({sendStrategyRequest:e,className:t=``}){let{sendStrategyRequest:n}=Ni(),r=e??n,i=Lr();return i?(0,u.jsx)(_a,{deploymentId:i,send:r,className:t}):(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500 ${t}`,children:`Loading deployment…`})}function _a({deploymentId:e,send:t,className:n}){let r=ua(e,t),[i,a]=(0,c.useState)(`members`),[o,s]=(0,c.useState)(null),l=ha(Y.USER),d=ha(Y.GROUP),f=Hi().contents[Y.DEPLOYMENT]?.roles||[];if(r.loading)return(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500 ${n}`,children:`Loading…`});if(!r.summary?.can_manage)return(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-600 ${n}`,children:`Only deployment administrators can open this page.`});let p=async e=>{try{await t(e,{awaitResponse:!0}),s(null)}catch(e){s(e?.message||`The change was refused.`)}await Promise.all([r.refresh(),l.refresh(),d.refresh()])},m=r.summary.grants;return(0,u.jsxs)(`section`,{className:`graphcore-admin-panel space-y-6 p-6 ${n}`,children:[(0,u.jsxs)(`header`,{className:`space-y-1`,children:[(0,u.jsx)(`h1`,{className:`text-xl font-semibold text-slate-900`,children:`Deployment administration`}),(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Decide who can create things in this deployment, organise people into groups, and set what new users receive.`})]}),o&&(0,u.jsxs)(`div`,{role:`alert`,className:`flex items-start justify-between gap-3 rounded-lg border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-900`,children:[(0,u.jsx)(`span`,{children:o}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>s(null),className:`shrink-0 text-xs font-semibold`,children:`Dismiss`})]}),(0,u.jsx)(`nav`,{className:`flex gap-1 border-b border-slate-200`,role:`tablist`,children:ma.map(({id:e,label:t})=>(0,u.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":i===e,onClick:()=>a(e),className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium ${i===e?`border-slate-900 text-slate-900`:`border-transparent text-slate-500 hover:text-slate-700`}`,children:t},e))}),i===`members`&&(0,u.jsx)(ya,{users:l.entities,groups:d.entities,grants:m,run:p}),i===`groups`&&(0,u.jsx)(ba,{groups:d.entities,grants:m,roles:f,send:t,run:p,deploymentId:e}),i===`roles`&&(0,u.jsx)(wa,{roles:f}),i===`new-users`&&(0,u.jsx)(Ta,{deploymentId:e,groups:d.entities,grants:m,roles:f,run:p})]})}var va=(e,t)=>e.filter(e=>e.subject_id===t&&e.provenance===`direct`).map(e=>e.role);function ya({users:e,groups:t,grants:n,run:r}){let[i,a]=(0,c.useState)(!1),o=t.find(e=>e.key===fa),s=va(n,`*`).includes(pa),l=new Set(t.filter(e=>va(n,e.entity_id).length>0).map(e=>e.entity_id)),d=e.map(e=>{let r=t.filter(t=>(t.member_ids||[]).includes(e.entity_id)),i=va(n,e.entity_id);return{user:e,memberOf:r,direct:i,hasAccess:s||i.length>0||r.some(e=>l.has(e.entity_id)),isAdmin:r.some(e=>e===o)}}),f=i?d.filter(e=>!e.hasAccess):d;return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:i,onChange:()=>a(!i)}),`Only people with no access yet`]}),s&&(0,u.jsx)(`p`,{className:`rounded-lg bg-blue-50 px-4 py-3 text-sm text-blue-800`,children:`Everyone signed in is a member, so everyone has access. Turn this off under New users to approve people individually.`}),(0,u.jsxs)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:[f.length===0&&(0,u.jsx)(`li`,{className:`px-4 py-3 text-sm text-slate-500`,children:`Nobody here.`}),f.map(({user:e,memberOf:t,direct:n,hasAccess:i,isAdmin:a})=>(0,u.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 px-4 py-3 text-sm`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:Z(e)}),a&&(0,u.jsx)(`span`,{className:`rounded bg-slate-900 px-1.5 py-0.5 text-xs text-white`,children:`Admin`}),!i&&(0,u.jsx)(`span`,{className:`rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800`,children:`No access yet`}),(0,u.jsx)(`span`,{className:`text-xs text-slate-500`,children:[...t.map(e=>e.name||e.key),...n].join(` · `)}),o&&!a&&(0,u.jsx)(`button`,{type:`button`,onClick:()=>void r($.builder().withStrategyName(`AddMember`).withTargetEntity(o.entity_id).withParams({principal_entity_id:e.entity_id}).build()),className:`ml-auto rounded-md px-2 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-100`,children:`Make admin`})]},e.entity_id))]})]})}function ba({groups:e,grants:t,roles:n,send:r,run:i,deploymentId:a}){let[o,s]=(0,c.useState)(``),[l,d]=(0,c.useState)(null);return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`A group gives many people the same access at once. Each group has at most one role on the deployment, and everyone in the group has it. Changing a group's role replaces its current role for everyone in it. To combine permissions, use a role that bundles them or add people to several groups.`}),(0,u.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),o.trim()&&i($.createGroup(o.trim(),{adminManaged:!0})).then(()=>s(``))},children:[(0,u.jsx)(`input`,{value:o,onChange:e=>s(e.target.value),placeholder:`New group name`,className:`flex-1 rounded-md border border-slate-300 px-3 py-2 text-sm`}),(0,u.jsx)(`button`,{type:`submit`,className:`rounded-md bg-slate-900 px-3 py-2 text-sm font-medium text-white`,children:`Create group`})]}),(0,u.jsx)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:e.map(e=>{let r=t.find(t=>t.subject_id===e.entity_id&&t.provenance===`direct`),o=l===e.entity_id;return(0,u.jsxs)(`li`,{className:`px-4 py-3 text-sm`,children:[(0,u.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>d(o?null:e.entity_id),"aria-expanded":o,className:`font-medium text-slate-900 hover:underline`,children:e.name||e.key||e.entity_id}),e.key&&(0,u.jsxs)(`span`,{className:`rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600`,children:[`Built-in · `,e.key]}),(0,u.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[(e.member_ids||[]).length,` members`]}),(0,u.jsxs)(`span`,{className:`ml-auto text-xs text-slate-500`,children:[`Role on the deployment: `,(0,u.jsx)(`span`,{className:`font-mono`,children:r?.role??`none`})]})]}),o&&(0,u.jsxs)(`div`,{className:`mt-3 space-y-3 rounded-lg bg-slate-50 p-3`,children:[(0,u.jsx)(Sa,{group:e,grant:r,roles:n,run:i,deploymentId:a}),(0,u.jsx)(ca,{entityId:e.entity_id}),!e.key&&(0,u.jsx)(Ca,{group:e,run:i})]})]},e.entity_id)})})]})}var xa=``;function Sa({group:e,grant:t,roles:n,run:r,deploymentId:i}){let a=t?.role??xa,[o,s]=(0,c.useState)(null),l=e.name||e.key||`this group`,d=e=>e===xa?`no role`:e,f=async()=>{o!==null&&(o===xa?t?.grant_entity_id&&await r($.revokeGrant(t.grant_entity_id)):await r($.createGrant(i,e.entity_id,o)),s(null))};return(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsxs)(`label`,{className:`flex flex-wrap items-center gap-2 text-xs text-slate-700`,children:[(0,u.jsx)(`span`,{className:`font-medium`,children:`Role on the deployment`}),(0,u.jsxs)(`select`,{value:o??a,onChange:e=>s(e.target.value===a?null:e.target.value),className:`rounded-md border border-slate-300 bg-white px-2 py-1 text-xs`,children:[(0,u.jsx)(`option`,{value:xa,children:`No role`}),n.map(e=>(0,u.jsx)(`option`,{value:e.name,children:e.name},e.name))]})]}),o!==null&&(0,u.jsxs)(`div`,{role:`alertdialog`,"aria-label":`Confirm role change`,className:`space-y-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-900`,children:[(0,u.jsxs)(`p`,{children:[a===xa?(0,u.jsxs)(u.Fragment,{children:[`Give `,(0,u.jsx)(`strong`,{children:l}),` the role `,(0,u.jsx)(`strong`,{children:d(o)}),`?`]}):(0,u.jsxs)(u.Fragment,{children:[`Replace `,(0,u.jsx)(`strong`,{children:l}),`'s role `,(0,u.jsx)(`strong`,{children:d(a)}),` with `,(0,u.jsx)(`strong`,{children:d(o)}),`?`]}),` `,`This changes access for everyone in the group.`]}),(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>void f(),className:`rounded-md bg-slate-900 px-2 py-1 font-medium text-white`,children:o===xa?`Remove role`:a===xa?`Give role`:`Replace role`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>s(null),className:`rounded-md border border-slate-300 bg-white px-2 py-1 font-medium text-slate-700`,children:`Cancel`})]})]})]})}function Ca({group:e,run:t}){let[n,r]=(0,c.useState)(!1),i=e.name||`this group`;return n?(0,u.jsxs)(`div`,{role:`alertdialog`,"aria-label":`Confirm group deletion`,className:`space-y-2 rounded-lg border border-red-300 bg-red-50 p-3 text-xs text-red-900`,children:[(0,u.jsxs)(`p`,{children:[`Delete `,(0,u.jsx)(`strong`,{children:i}),`? Everyone in it loses the access the group gave them, here and on anything shared with the group. This cannot be undone.`]}),(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>void t($.deleteEntity(e.entity_id)),className:`rounded-md bg-red-700 px-2 py-1 font-medium text-white`,children:`Delete group`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(!1),className:`rounded-md border border-slate-300 bg-white px-2 py-1 font-medium text-slate-700`,children:`Cancel`})]})]}):(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(!0),className:`rounded-md px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-50`,children:`Delete group`})}function wa({roles:e}){return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Roles are defined by the installed apps. Grant them to people or groups from Members, Groups, or New users.`}),(0,u.jsx)(`ul`,{className:`space-y-3`,children:e.map(e=>(0,u.jsxs)(`li`,{className:`rounded-xl border border-slate-200 p-4`,children:[(0,u.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,u.jsx)(`span`,{className:`font-mono text-sm font-semibold text-slate-900`,children:e.name}),e.description&&(0,u.jsx)(`span`,{className:`text-sm text-slate-600`,children:e.description})]}),(0,u.jsx)(`ul`,{className:`mt-2 space-y-1 text-xs text-slate-600`,children:(e.permission_details??e.permissions.map(e=>({name:e,description:``}))).map(e=>(0,u.jsxs)(`li`,{children:[(0,u.jsx)(`span`,{className:`font-mono`,children:e.name}),e.description&&(0,u.jsxs)(`span`,{children:[` - `,e.description]})]},e.name))})]},e.name))})]})}function Ta({deploymentId:e,groups:t,grants:n,roles:r,run:i}){let a=X(e),[o,s]=(0,c.useState)([]),[l,d]=(0,c.useState)([]);(0,c.useEffect)(()=>{s(a?.new_user_group_ids??[]),d(a?.new_user_roles??[])},[a?.new_user_group_ids,a?.new_user_roles]);let f=(0,c.useMemo)(()=>n.find(e=>e.subject_id===`*`&&e.role===pa&&e.provenance===`direct`),[n]),p=(e,t)=>e.includes(t)?e.filter(e=>e!==t):[...e,t];return(0,u.jsxs)(`div`,{className:`space-y-6`,children:[(0,u.jsxs)(`label`,{className:`flex items-start gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:!!f,onChange:()=>void i(f?.grant_entity_id?$.revokeGrant(f.grant_entity_id):$.createGrant(e,`*`,pa)),className:`mt-0.5`}),(0,u.jsxs)(`span`,{children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-800`,children:`Everyone signed in is a member`}),(0,u.jsx)(`span`,{className:`block text-slate-500`,children:`Turn off to approve people yourself: new users can sign in but create nothing until they get a role, directly or through a group.`})]})]}),(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsx)(`h2`,{className:`text-sm font-semibold text-slate-800`,children:`Add new users to these groups`}),(0,u.jsx)(`p`,{className:`text-xs text-slate-500`,children:`Prefer a group when you may want to change what new users can do later, or give access to many people at once.`}),t.map(e=>(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:o.includes(e.entity_id),onChange:()=>s(p(o,e.entity_id))}),e.name||e.key]},e.entity_id))]}),(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsx)(`h2`,{className:`text-sm font-semibold text-slate-800`,children:`Give new users these roles directly`}),(0,u.jsx)(`p`,{className:`text-xs text-slate-500`,children:`Use a direct role for a one-off; it is granted to each person separately.`}),r.map(e=>(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:l.includes(e.name),onChange:()=>d(p(l,e.name))}),(0,u.jsx)(`span`,{className:`font-mono`,children:e.name}),e.description&&(0,u.jsx)(`span`,{className:`text-slate-500`,children:e.description})]},e.name))]}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>void i($.setNewUserDefaults(e,o,l)),className:`rounded-md bg-slate-900 px-3 py-2 text-sm font-medium text-white`,children:`Save new-user settings`})]})}function Ea(e=!0){let t=Lr(),[n,r]=(0,c.useState)(!1);return(0,c.useEffect)(()=>{if(!e||!t){r(!1);return}let n=!1;return q.getAccess(t).then(e=>{n||r(!!e?.can_manage)}).catch(()=>{n||r(!1)}),()=>{n=!0}},[t,e]),n}function Da(e){return[{to:`/`,label:`home`},...e.map(e=>e.pattern).filter(e=>e!==`/`&&!e.includes(`{`)).map(e=>({to:e,label:e.slice(1)}))]}var Oa=({isActive:e})=>`rounded-md px-2.5 py-1 text-sm ${e?`bg-gray-900 text-white`:`text-gray-600 hover:bg-gray-100`}`,ka=`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm hover:bg-gray-100`;function Aa({adminHref:e}){let{isAuthenticated:t,username:n,principalEntityId:r,logout:i}=Pr(),a=Ea(t),o=X(r),[s,l]=(0,c.useState)(!1),[f,p]=(0,c.useState)(!1),m=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(!s)return;let e=e=>{m.current?.contains(e.target)||l(!1)},t=e=>e.key===`Escape`&&l(!1);return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[s]);let h=o?.username||n||`User`;return(0,u.jsxs)(`div`,{ref:m,className:`relative`,children:[(0,u.jsxs)(`button`,{type:`button`,"aria-haspopup":`menu`,"aria-expanded":s,onClick:()=>l(e=>!e),className:`flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100`,children:[h,(0,u.jsx)(Yr,{className:`h-2.5 w-2.5 text-gray-400`})]}),s&&(0,u.jsxs)(`div`,{role:`menu`,className:`absolute right-0 z-50 mt-1 w-64 rounded-lg border border-gray-200 bg-white p-1 shadow-lg`,children:[r&&(0,u.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:async()=>{if(r)try{await navigator.clipboard.writeText(r),p(!0),setTimeout(()=>p(!1),2e3)}catch(e){console.error(`Failed to copy user entity ID:`,e)}},title:`Copy user entity ID`,className:ka,children:[f?(0,u.jsx)(Xr,{className:`h-3 w-3 shrink-0 text-green-600`}):(0,u.jsx)(Jr,{className:`h-3 w-3 shrink-0 text-gray-500`}),(0,u.jsx)(`span`,{className:`truncate font-mono text-xs text-gray-600`,children:r})]}),a&&(0,u.jsxs)(d.Link,{to:e,role:`menuitem`,onClick:()=>l(!1),className:`${ka} text-gray-700`,children:[(0,u.jsx)(Ur,{className:`h-3.5 w-3.5 text-gray-500`}),`Admin`]}),(0,u.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:i,className:`${ka} text-red-600 hover:bg-red-50`,children:[(0,u.jsx)(Gr,{className:`h-3.5 w-3.5`}),`Logout`]})]})]})}var ja=({title:e=`graphcore`,places:t,className:n=``,adminHref:r=da})=>{let{isAuthenticated:i}=Pr(),a=Mi();if(!i)return null;let o=Da(a??[]),s=t===!1?[]:Array.isArray(t)?t:t?t(o):o;return(0,u.jsxs)(`div`,{className:`flex items-center gap-4 border-b border-gray-200 bg-white px-4 py-2 ${n}`,children:[(0,u.jsx)(`h1`,{className:`text-sm font-semibold tracking-tight text-gray-900`,children:e}),s.length>0&&(0,u.jsx)(`nav`,{"aria-label":`Places`,className:`flex items-center gap-1`,children:s.map(e=>(0,u.jsx)(d.NavLink,{to:e.to,end:e.to===`/`,className:Oa,children:e.label},e.to))}),(0,u.jsx)(`div`,{className:`ml-auto`,children:(0,u.jsx)(Aa,{adminHref:r})})]})},Ma=({entityTypeId:e,className:t=`w-4 h-4`,size:n})=>{let r=Nn(e);return c.default.createElement(r,{className:t,size:n})},Na={light:{wrapper:`border border-gray-200 bg-white shadow-xs`,input:`border-gray-200 bg-white text-gray-900 placeholder:text-gray-400 focus:border-blue-400 focus:ring-blue-100`,icon:`text-gray-400`,list:`border border-gray-200 bg-gray-50/70`,option:`border-transparent text-gray-700 hover:border-blue-200 hover:bg-blue-50`,optionActive:`border-blue-200 bg-blue-50 text-blue-900 shadow-xs`,optionMeta:`text-gray-400`,optionMetaActive:`text-blue-500`,empty:`text-gray-500`},dark:{wrapper:`border border-gray-700 bg-gray-800 shadow-xs`,input:`border-gray-600 bg-gray-700 text-white placeholder:text-gray-400 focus:border-blue-500 focus:ring-blue-500/20`,icon:`text-gray-400`,list:`border border-gray-700 bg-gray-900/50`,option:`border-transparent text-gray-200 hover:border-blue-500/40 hover:bg-blue-500/10`,optionActive:`border-blue-500/40 bg-blue-500/15 text-white shadow-xs`,optionMeta:`text-gray-400`,optionMetaActive:`text-blue-300`,empty:`text-gray-400`}},Pa=({availableViewTypes:e,selectedValue:t,onSelect:n,theme:r=`light`,placeholder:i=`Search view types...`,autoFocus:a=!1})=>{let[o,s]=(0,c.useState)(``),l=Na[r]||Na.light,d=(0,c.useMemo)(()=>Object.entries(e||{}),[e]),f=(0,c.useMemo)(()=>{let e=o.trim().toLowerCase();return e?d.filter(([t,n])=>String(n).toLowerCase().includes(e)||t.toLowerCase().includes(e)):d},[o,d]);return(0,u.jsxs)(`div`,{className:`rounded-xl p-3 ${l.wrapper}`,children:[(0,u.jsxs)(`div`,{className:`relative`,children:[(0,u.jsx)(Kr,{className:`absolute left-3 top-1/2 -translate-y-1/2 ${l.icon}`}),(0,u.jsx)(`input`,{type:`text`,value:o,onChange:e=>s(e.target.value),placeholder:i,className:`w-full rounded-lg border py-2.5 pl-10 pr-3 text-sm outline-hidden transition focus:ring-4 ${l.input}`,autoFocus:a})]}),(0,u.jsx)(`div`,{className:`mt-3 max-h-64 overflow-y-auto rounded-xl p-2 ${l.list}`,children:f.length>0?(0,u.jsx)(`div`,{className:`space-y-2`,children:f.map(([e,r])=>{let i=t===e;return(0,u.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:`flex w-full items-start justify-between rounded-lg border px-3 py-2.5 text-left transition ${i?l.optionActive:l.option}`,children:[(0,u.jsxs)(`span`,{className:`min-w-0`,children:[(0,u.jsx)(`span`,{className:`block truncate text-sm font-medium`,children:String(r)}),(0,u.jsx)(`span`,{className:`mt-0.5 block truncate text-xs ${i?l.optionMetaActive:l.optionMeta}`,children:e})]}),i&&(0,u.jsx)(Xr,{className:`ml-3 mt-0.5 shrink-0 text-xs`})]},e)})}):(0,u.jsx)(`div`,{className:`px-3 py-6 text-center text-sm ${l.empty}`,children:`No view types match your search.`})})]})};function Fa(e){let t=Zi(),{sendStrategyRequest:n}=Ni(),r=(0,c.useRef)(e);r.current=e;let i=t?.view?.state,a=(0,c.useMemo)(()=>({...r.current,...i&&typeof i==`object`&&!Array.isArray(i)?i:{}}),[i]),o=t?.view?.entity_id??null,s=t?.position??null;return[a,(0,c.useCallback)((e,t)=>{if(!o&&!s)return Promise.resolve(void 0);let r={position:s?qi(s):void 0,state:e};t!==void 0&&(r.component=t);let i=Promise.resolve(n($.setViewState(o,r),{awaitResponse:!0}));return i.catch(()=>void 0),i},[s,n,o])]}function Ia(){let{sendStrategyRequest:e}=Ni();return(0,c.useCallback)(async(t={})=>{try{return(await e($.createView(null,t),{awaitResponse:!0}))?.view_entity_id??null}catch{return null}},[e])}function La(){(0,c.useEffect)(()=>{Bi()},[]);let e=Hi().contents;return(0,c.useMemo)(()=>Object.keys(e).filter(e=>e!==Y.VIEW).sort(),[e])}var Ra=[{key:`entity_ide`,label:`Entity IDE`,icon:Dn,state:{sidebar_config:{allow_create:!0}}}],za=`flex min-w-0 flex-col items-center gap-2 rounded-xl border border-gray-200 bg-white p-5 text-center shadow-xs transition-colors`;function Ba({viewId:e,onRemove:t}){let n=(0,d.useNavigate)(),r=Hr(),i=X(e),a=F(t=>t.notFoundEntityIds.has(e)),o=a||i?.forbidden,s=typeof i?.component==`string`?i.component:null,c=o?a?`View not found`:`No access`:i&&Ar(i,`name`)||s&&r.get(s)?.label||s||`View`;return(0,u.jsxs)(`div`,{className:`group relative`,children:[(0,u.jsxs)(`button`,{type:`button`,disabled:!!o,onClick:()=>n(ri(e)),className:`${za} w-full hover:border-blue-300 hover:shadow-md disabled:cursor-default disabled:opacity-60`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 text-blue-600`,children:(0,u.jsx)(Ma,{entityTypeId:i?.entity_type_id,className:`h-5 w-5`})}),(0,u.jsx)(`span`,{className:`line-clamp-2 w-full break-words text-sm font-medium text-gray-900`,children:c})]}),(0,u.jsx)(`button`,{type:`button`,title:`Remove from gallery`,onClick:t,className:`absolute right-1 top-1 rounded-sm p-0.5 text-gray-400 opacity-0 hover:text-gray-700 group-hover:opacity-100`,children:(0,u.jsx)(On,{className:`h-4 w-4`})})]})}function Va(){let e=(0,d.useNavigate)(),t=Hr(),[{views:n},r]=Fa({views:[]}),i=Ia(),a=Er(n),o=(0,c.useRef)(n),s=(0,c.useRef)(n);(0,c.useEffect)(()=>{o.current=n,s.current=n},[n]);let l=La(),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useMemo)(()=>{let e=new Set(a.filter(e=>Ra.some(t=>t.key===e.component)).map(e=>e.entity_id));return n.filter(t=>!e.has(t))},[n,a]),S=(0,c.useMemo)(()=>Object.fromEntries(t.keys().map(e=>[e,t.get(e).label])),[t]),C=async e=>{s.current=e;try{await r({views:e})}catch(e){throw s.current=o.current,e}},w=async(e,t)=>{if(y)return null;b(e);try{let e=await i(t);return e&&await C([...s.current,e]),e}catch{return null}finally{b(null)}},T=e=>void C(s.current.filter(t=>t!==e)).catch(()=>void 0),E=async t=>{let n=a.find(e=>e.component===t);if(n){e(ri(n.entity_id));return}let r=Ra.find(e=>e.key===t),i=await w(t,{component:t,state:r?.state??{}});i&&e(ri(i))},D=()=>{m(!1),g(``),v(null)};return(0,u.jsxs)(`div`,{className:`h-full overflow-y-auto bg-gray-50 p-6`,children:[(0,u.jsxs)(`div`,{className:`mb-6`,children:[(0,u.jsx)(`h1`,{className:`text-2xl font-bold text-gray-900`,children:`My Views`}),(0,u.jsx)(`p`,{className:`text-gray-600`,children:`Select a view to explore your data`})]}),(0,u.jsxs)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-4`,children:[Ra.map(e=>{let t=e.icon,n=y===e.key;return(0,u.jsxs)(`button`,{type:`button`,onClick:()=>E(e.key),disabled:n,className:`flex flex-col items-center gap-2 rounded-xl border border-gray-200 bg-white p-5 text-center shadow-xs transition-colors hover:border-blue-300 hover:shadow-md disabled:cursor-wait`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100 text-blue-600`,children:n?(0,u.jsx)(mn,{className:`h-5 w-5 animate-spin`}):(0,u.jsx)(t,{className:`h-5 w-5`})}),(0,u.jsx)(`span`,{className:`truncate text-sm font-medium text-gray-900`,children:e.label}),(0,u.jsx)(`span`,{className:`text-xs text-gray-500`,children:n?`Creating…`:`Quick start view`})]},e.key)}),x.map(e=>(0,u.jsx)(Ba,{viewId:e,onRemove:()=>T(e)},e)),(0,u.jsxs)(`button`,{type:`button`,onClick:()=>m(!0),className:`flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-gray-300 p-5 text-center text-gray-500 transition-colors hover:border-blue-400 hover:text-blue-600`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-lg bg-gray-100`,children:(0,u.jsx)(An,{className:`h-5 w-5`})}),(0,u.jsx)(`span`,{className:`text-sm font-medium`,children:`New View`})]})]}),p&&(0,f.createPortal)((0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:D}),(0,u.jsxs)(`div`,{className:`relative w-full max-w-sm space-y-3 rounded-xl border border-gray-200 bg-white p-4 shadow-2xl`,onClick:e=>e.stopPropagation(),children:[(0,u.jsx)(`h3`,{className:`text-sm font-semibold text-gray-900`,children:`Create a new view`}),(0,u.jsx)(Pa,{availableViewTypes:S,selectedValue:h,onSelect:g,theme:`light`,autoFocus:!0}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{className:`mb-1 text-xs font-medium text-gray-500`,children:[`Shows `,_?Z(_):`no entity`]}),l.length>0&&(0,u.jsx)(aa,{typeIds:l,onPick:v,placeholder:`Pick an entity (optional)…`},l.join(`,`))]}),(0,u.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:D,className:`rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50`,children:`Cancel`}),(0,u.jsx)(`button`,{type:`button`,onClick:async()=>{(h||_)&&(await w(`custom`,{component:h||null,renders:_?.entity_id??null}),D())},disabled:!h&&!_||y!==null,className:`rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400`,children:`Create`})]})]})]}),document.body)]})}var Ha=na(`view_gallery`,Va,{entry:!0}),Ua=e=>e.replace(/(^|-)\w/g,e=>e.toUpperCase());function Wa({entityId:e,sendStrategyRequest:t,className:n=``}){let r=ua(e,t),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)({}),{summary:l}=r,d=i||r.roles[0]?.name;if(r.loading)return(0,u.jsx)(`div`,{className:`min-h-[28rem] p-6 text-sm text-slate-500 ${n}`,children:`Loading access…`});if(r.error)return(0,u.jsx)(`div`,{className:`min-h-[28rem] p-6 text-sm text-red-600 ${n}`,role:`alert`,children:r.error});if(!l||!r.shareable)return null;let f=r.publicPermissions.includes(`Read`),p=async()=>{s({busy:!0});try{let{token:t}=await q.createInvite(e,d);s({url:Ei(t)})}catch(e){s({error:e?.message||`Unable to create invite link`})}};return(0,u.jsxs)(`section`,{className:`graphcore-access-panel min-h-[28rem] space-y-6 p-6 ${n}`,children:[(0,u.jsxs)(`div`,{className:`flex min-h-5 items-center justify-between gap-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Choose who can view this and what they can do with it.`}),r.busy&&(0,u.jsx)(`span`,{className:`shrink-0 text-xs font-medium text-slate-400`,"aria-live":`polite`,children:`Saving…`})]}),f&&(0,u.jsx)(`p`,{className:`rounded-lg bg-blue-50 px-4 py-3 text-sm text-blue-800`,children:`Public read is enabled by application policy.`}),r.canManage?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`label`,{className:`flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm font-medium text-slate-800`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:!!r.publicGrant||f,disabled:r.busy||f,onChange:()=>void(r.publicGrant?r.revokePublicRead():r.setPublicRead()),className:`h-4 w-4 rounded border-slate-300 text-slate-900 focus:ring-slate-500`}),(0,u.jsx)(`span`,{children:`Anyone signed in can view`})]}),(0,u.jsx)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:r.grants.map(e=>(0,u.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 px-4 py-3 text-sm`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:r.labelsById[e.subject_id]??e.subject_id}),(0,u.jsx)(`span`,{className:`text-xs text-slate-500`,children:e.provenance}),e.provenance===`direct`&&e.grant_entity_id&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`select`,{value:e.role,disabled:r.busy,onChange:t=>void r.changeRole(e.grant_entity_id,t.target.value),className:`ml-auto rounded-md border border-slate-300 bg-white px-2 py-1 text-sm text-slate-700`,children:r.roles.map(e=>(0,u.jsx)(`option`,{value:e.name,children:Ua(e.name)},e.name))}),(0,u.jsx)(`button`,{type:`button`,disabled:r.busy,onClick:()=>void r.revoke(e.grant_entity_id),className:`rounded-md px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-50`,children:`Revoke`})]})]},`${e.subject_id}-${e.provenance}`))}),(0,u.jsxs)(`div`,{className:`space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-4`,children:[(0,u.jsx)(`select`,{className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm`,value:d??``,disabled:r.busy,onChange:e=>a(e.target.value),children:r.roles.map(e=>(0,u.jsx)(`option`,{value:e.name,children:Ua(e.name)},e.name))}),r.subjectTypeIds.length>0&&(0,u.jsx)(aa,{typeIds:r.subjectTypeIds,exclude:r.grants.map(e=>e.subject_id),labelFor:r.subjectLabel,disabled:r.busy||!d,placeholder:`Share with a person or group…`,onPick:e=>void r.grant(e.entity_id,d)}),(0,u.jsx)(`button`,{type:`button`,disabled:r.busy||o.busy||!d,onClick:()=>void p(),className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100`,children:`Create invite link`}),o.url&&(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`input`,{readOnly:!0,"aria-label":`Invite link`,value:o.url,onFocus:e=>e.target.select(),className:`min-w-0 flex-1 rounded-md border border-slate-300 bg-white px-3 py-2 text-xs text-slate-700`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>void navigator.clipboard?.writeText(o.url),className:`rounded-md bg-slate-900 px-3 py-2 text-xs font-semibold text-white`,children:`Copy`})]}),o.url&&(0,u.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[`Single use, expires in 7 days. Shown once; anyone with it can join as `,Ua(d),`.`]}),o.error&&(0,u.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:o.error})]})]}):(0,u.jsx)(`p`,{className:`rounded-lg bg-slate-50 px-4 py-3 text-sm text-slate-600`,children:`Only people who can manage access can see who has access.`})]})}function Ga({path:e,component:t}){if(typeof e!=`string`||!e.startsWith(`/`))throw Error(`definePage: path must start with "/", got ${JSON.stringify(e)}`);if(!t)throw Error(`definePage: ${e} has no component`);return Object.freeze({kind:`graphcore.page`,path:qa(e),component:t})}function Ka(e){return typeof e==`object`&&!!e&&e.kind===`graphcore.page`}function qa(e){return e.length>1?e.replace(/\/+$/,``):e}function Ja(e){let t=new Map;for(let{app:n,exports:r}of e)for(let e of Object.values(r))for(let r of(Array.isArray(e)?e:[e]).filter(Ka)){let e=t.get(r.path);if(e)throw Error(`Pages from "${e.app}" and "${n}" both claim the path "${r.path}"`);t.set(r.path,{page:r,app:n})}return[...t.values()].map(({page:e})=>e)}function Ya(e){return e==null||e===``?`Empty`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e,null,2)}function Xa(e){if(typeof e!=`string`)return null;try{let t=new URL(e);if(t.protocol===`http:`||t.protocol===`https:`)return e}catch{return null}return null}function Za(e){let t=Xa(e);return t?(0,u.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,className:`text-blue-600 underline break-all hover:text-blue-700`,children:t}):Ya(e)}function Qa({entityId:e}){let t=X(e),n=Z(t),r=Mr(t),i=Object.entries(kr(t));return(0,u.jsxs)(`div`,{className:`bg-white text-gray-900 border border-gray-200 rounded-xl shadow-xs overflow-hidden`,children:[(0,u.jsxs)(`div`,{className:`px-5 py-4 border-b border-gray-200`,children:[(0,u.jsx)(`div`,{className:`text-xs font-medium uppercase tracking-wide text-gray-500`,children:r}),(0,u.jsx)(`h2`,{className:`mt-1 text-xl font-semibold text-gray-900`,children:n})]}),(0,u.jsx)(`div`,{className:`p-5`,children:i.length===0?(0,u.jsx)(`div`,{className:`text-sm text-gray-500`,children:`No additional attributes.`}):(0,u.jsx)(`dl`,{className:`space-y-3`,children:i.map(([e,t])=>(0,u.jsxs)(`div`,{className:`rounded-lg border border-gray-200 bg-gray-50 p-3`,children:[(0,u.jsx)(`dt`,{className:`text-xs font-medium uppercase tracking-wide text-gray-500`,children:e}),(0,u.jsx)(`dd`,{className:`mt-1 whitespace-pre-wrap wrap-break-word text-sm text-gray-900`,children:Za(t)})]},e))})})]})}var $a=(0,c.createContext)([]);function eo(){return(0,c.useContext)($a)}function to({token:e,children:t}){let n=eo(),r=(0,c.useMemo)(()=>e?[...n,e]:n,[n,e]);return(0,u.jsx)($a.Provider,{value:r,children:t})}var no=class extends c.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`Visualization error:`,e,t)}render(){return this.state.hasError?typeof this.props.fallback==`function`?this.props.fallback(this.state.error):this.props.fallback||(0,u.jsx)(`div`,{className:`p-4 text-red-500 border border-red-300 rounded-sm bg-red-50`,children:`Something went wrong with this visualization.`}):this.props.children}};function ro({className:e=``}){return(0,u.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#16161e] select-none ${e}`,children:(0,u.jsxs)(`div`,{className:`flex flex-col items-center gap-2 px-6 py-5 rounded-xl bg-[#1e1e26] border border-white/10`,children:[(0,u.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`text-gray-500`,children:[(0,u.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`,ry:`2`}),(0,u.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),(0,u.jsx)(`span`,{className:`text-xs font-medium text-gray-500`,children:`No permission`})]})})}function io(e,t,n){return t&&e.get(t)?t:n?e.defaultViewFor(n):null}function ao({label:e}){return(0,u.jsxs)(`div`,{className:`flex items-center justify-center p-4 text-gray-400`,children:[(0,u.jsx)(`div`,{className:`mr-2 h-5 w-5 animate-spin rounded-full border-b-2 border-gray-400`}),(0,u.jsx)(`span`,{children:e})]})}function oo({cause:e,className:t=``}){return e===`forbidden`?(0,u.jsx)(ro,{className:t}):(0,u.jsx)(`div`,{className:`flex h-full w-full items-center justify-center p-4 text-xs font-medium text-gray-500 ${t}`,children:`Entity not found`})}function so(){let e=Hr();return(0,c.useMemo)(()=>Object.fromEntries(e.keys().map(t=>[t,e.get(t).label])),[e])}function co({current:e}){let[,t]=Fa({}),n=so(),[r,i]=(0,c.useState)(!1);return(0,u.jsxs)(`div`,{className:`pointer-events-none absolute bottom-1 right-1 z-10`,children:[(0,u.jsx)(`button`,{type:`button`,title:`Change view`,onClick:()=>i(e=>!e),className:`rounded-sm border border-gray-200 bg-white/90 px-1.5 text-xs text-gray-500 shadow-xs transition-opacity hover:text-gray-900 group-hover:pointer-events-auto group-hover:opacity-100 ${r?`pointer-events-auto opacity-100`:`opacity-0`}`,children:`⋯`}),r&&(0,u.jsx)(`div`,{className:`pointer-events-auto absolute bottom-full right-0 mb-1 w-64 nodrag`,children:(0,u.jsx)(Pa,{availableViewTypes:n,selectedValue:e??``,onSelect:e=>{i(!1),t({},e)},theme:`light`,placeholder:`Search views...`,autoFocus:!0})})]})}function lo(){let[,e]=Fa({}),t=so();return(0,u.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,u.jsx)(`h3`,{className:`text-sm font-semibold text-gray-900`,children:`Choose a view`}),(0,u.jsx)(Pa,{availableViewTypes:t,selectedValue:``,onSelect:t=>void e({},t),theme:`light`,placeholder:`Search views...`})]})}function uo({name:e,entityId:t,className:n}){let r=Hr(),i=eo(),a=`${t??``}:${e??``}`;if(i.includes(a))return(0,u.jsx)(`div`,{className:`rounded-sm border border-amber-200 bg-amber-50 p-4 text-amber-700`,children:`Recursive view render blocked to prevent infinite loop.`});let o=e&&r.get(e)?.Component||Qa;return(0,u.jsx)(to,{token:a,children:(0,u.jsxs)(`div`,{className:`group relative h-full min-h-0 ${n??``}`,children:[(0,u.jsx)(co,{current:e}),(0,u.jsx)(no,{fallback:e=>(0,u.jsxs)(`div`,{className:`rounded-sm border border-red-200 bg-red-50 p-4 text-red-600`,children:[(0,u.jsx)(`div`,{className:`font-semibold`,children:`Error rendering view`}),(0,u.jsx)(`div`,{className:`mt-1 text-sm`,children:e?.message||`Unknown error`})]}),children:(0,u.jsx)(o,{entityId:t})})]})})}function fo({entity:e,slot:t,className:n}){let r=$i(t??`entity`,e.entity_id);return(0,u.jsx)(ea,{position:r,children:(0,u.jsx)(po,{entity:e,className:n})})}function po({entity:e,className:t}){let n=Hr(),r=Zi()?.view;if(r===void 0)return(0,u.jsx)(ao,{label:`Loading view…`});let i=io(n,typeof r?.component==`string`?r.component:null,e.entity_type_id);return(0,u.jsx)(uo,{name:i,entityId:e.entity_id,className:t})}function mo({view:e,className:t}){let n=Hr(),r=(0,c.useMemo)(()=>Gi(e.entity_id),[e.entity_id]),i=er(r)??e,a=typeof i.renders==`string`?i.renders:null,o=X(a),s=F(e=>a?e.notFoundEntityIds.has(a):!1),l=(0,c.useMemo)(()=>({position:r,view:i}),[r,i]),d;if(o?.forbidden)d=(0,u.jsx)(oo,{cause:`forbidden`,className:t});else if(s)d=(0,u.jsx)(oo,{cause:`not_found`,className:t});else if(a&&!o)d=(0,u.jsx)(ao,{label:`Loading entity…`});else{let e=io(n,typeof i.component==`string`?i.component:null,o?.entity_type_id);d=!e&&!a?(0,u.jsx)(lo,{}):(0,u.jsx)(uo,{name:e,entityId:a,className:t})}return(0,u.jsx)(to,{token:`view:${i.entity_id}`,children:(0,u.jsx)(Ji.Provider,{value:l,children:d})})}function ho({entityId:e,slot:t,className:n}){let r=X(e),i=F(t=>e?t.notFoundEntityIds.has(e):!1),a=eo();return e?r?.forbidden?(0,u.jsx)(oo,{cause:`forbidden`,className:n}):i?(0,u.jsx)(oo,{cause:`not_found`,className:n}):r?r.entity_type_id===Y.VIEW?a.includes(`view:${r.entity_id}`)?(0,u.jsx)(`div`,{className:`rounded-sm border border-amber-200 bg-amber-50 p-4 text-amber-700`,children:`Recursive view render blocked to prevent infinite loop.`}):(0,u.jsx)(mo,{view:r,className:n}):(0,u.jsx)(fo,{entity:r,slot:t,className:n}):(0,u.jsx)(ao,{label:`Loading entity…`}):null}var go=()=>{let e=ii((0,d.useParams)()),t=(0,d.useNavigate)(),{pathname:n}=(0,d.useLocation)(),{isAuthenticated:r}=Pr(),{isConnected:i}=Ni();return r?i?(0,u.jsx)(`div`,{className:`h-full min-h-0`,children:(0,u.jsx)(vi,{address:n,children:(0,u.jsx)(ta,{address:n,children:(0,u.jsx)(ho,{entityId:e,className:`h-full`})})})}):(0,u.jsx)(`div`,{className:`h-full flex items-center justify-center bg-gray-50 text-gray-500`,children:(0,u.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,u.jsx)(`div`,{className:`animate-spin rounded-full h-6 w-6 border-b-2 border-gray-400`}),(0,u.jsx)(`span`,{children:`Connecting to server…`})]})}):(0,u.jsx)(`div`,{className:`h-full flex items-center justify-center bg-gray-50`,children:(0,u.jsxs)(`div`,{className:`max-w-lg p-8 bg-white rounded-lg border border-gray-200 text-center`,children:[(0,u.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900 mb-2`,children:`Authentication Required`}),(0,u.jsx)(`p`,{className:`text-gray-600 mb-6`,children:`You need to be logged in to view this entity.`}),(0,u.jsx)(`button`,{onClick:()=>t(`/`),className:`px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors`,children:`Go to Home`})]})})},_o=()=>{let{pathname:e}=(0,d.useLocation)(),t=ai(e);return(0,u.jsx)(d.Navigate,{to:t?ri(t):`/`,replace:!0})},vo=new Set([`/`,`/e/{entity}`]),yo=e=>e.replace(`{entity}`,`:entityBackend/:entityLocal`);function bo({viewName:e}){let{pathname:t}=(0,d.useLocation)(),{entityBackend:n,entityLocal:r}=(0,d.useParams)(),i=Hr(),a=n&&r?`gc://${n}/${r}`:null,o=i.get(e)??(e===`home`?i.get(Ha.viewName):void 0),s;return s=o?(0,u.jsx)(o,{entityId:a}):a?(0,u.jsx)(ho,{entityId:a,className:`h-full`}):(0,u.jsxs)(`div`,{className:`p-6 text-sm text-gray-500`,children:[`No view "`,e,`" is available for `,t]}),(0,u.jsx)(vi,{address:t,children:(0,u.jsx)(ta,{address:t,children:(0,u.jsx)(`div`,{className:`h-full min-h-0`,children:s})})})}function xo({fallback:e=null}){let t=Mi();return(0,u.jsxs)(d.Routes,{children:[(0,u.jsx)(d.Route,{index:!0,element:(0,u.jsx)(bo,{viewName:`home`})}),(t??[]).filter(e=>!vo.has(e.pattern)).map(e=>(0,u.jsx)(d.Route,{path:yo(e.pattern),element:(0,u.jsx)(bo,{viewName:e.view_name})},e.pattern)),(0,u.jsx)(d.Route,{path:`*`,element:t?e:null})]})}function So({topBar:e=(0,u.jsx)(ja,{})}){let{isAuthenticated:t,principalEntityId:n}=Pr();return!t||!n?(0,u.jsx)(Ai,{}):(0,u.jsxs)(d.Routes,{children:[(0,u.jsx)(d.Route,{path:ei,element:(0,u.jsx)(`div`,{className:`h-screen w-screen overflow-hidden bg-gray-50`,children:(0,u.jsx)(go,{})})}),(0,u.jsxs)(d.Route,{path:`/*`,element:(0,u.jsxs)(`div`,{className:`h-screen w-screen overflow-hidden bg-gray-50 flex flex-col`,children:[e,(0,u.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,u.jsx)(d.Outlet,{})})]}),children:[(0,u.jsx)(d.Route,{path:da.slice(1),element:(0,u.jsx)(`div`,{className:`h-full overflow-auto`,children:(0,u.jsx)(ga,{})})}),(0,u.jsx)(d.Route,{path:Ti.slice(1),element:(0,u.jsx)(ki,{})}),(0,u.jsx)(d.Route,{path:`*`,element:(0,u.jsx)(xo,{fallback:(0,u.jsx)(_o,{})})})]})]})}var Co=[`/admin`,`/auth/callback`];function wo(e){return e.split(`/`).filter(Boolean).flatMap(e=>e===`{entity}`?[null,null]:e===`*`?[`*`]:e.startsWith(`:`)?[null]:[e])}function To(e,t){for(let n=0;;n+=1){if(e[n]===`*`||t[n]===`*`)return!0;if(n>=e.length||n>=t.length)return e.length===t.length;if(e[n]!==null&&t[n]!==null&&e[n]!==t[n])return!1}}function Eo(e,t,n){if(n)return[];let r=[...t,...Co,`/e/{entity}`],i=[];for(let t of e)for(let e of r)To(wo(t.path),wo(e))&&i.push({page:t.path,route:e});return i}function Do(){let[e,t]=(0,c.useState)(()=>window.location.pathname);return(0,c.useEffect)(()=>{let e=()=>t(window.location.pathname);return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[]),e}function Oo(e,t){return e===t||e.startsWith(`${t}/`)}function ko({pages:e,basePath:t}){let n=Mi();return(0,c.useEffect)(()=>{if(!n)return;let r=Eo(e,n.map(e=>e.pattern),t);if(!r.length)return;let i=r.map(({page:e,route:t})=>`page ${e} hides ${t}`).join(`; `);console.error(`GraphCore: pages collide with app routes: ${i}. Mount the app under a basePath.`),Fn({message:`Pages collide with app routes: ${i}`,type:`error`})},[n,e,t]),null}function Ao(){return(0,u.jsx)(`div`,{className:`p-8 text-sm text-gray-500`,children:`Page not found.`})}function jo({registry:e,pages:t=[],config:n,basePath:r,app:i=(0,u.jsx)(So,{}),notFound:a=(0,u.jsx)(Ao,{})}){let o=v(r);y(o);let s=Do(),c=(0,u.jsxs)(Ci,{...n,registry:e,basePath:o,children:[(0,u.jsx)(ko,{pages:t,basePath:o}),i]});return o&&Oo(s,o)?(0,u.jsx)(d.BrowserRouter,{basename:o,children:c}):(0,u.jsx)(d.BrowserRouter,{children:(0,u.jsxs)(d.Routes,{children:[t.map(e=>(0,u.jsx)(d.Route,{path:e.path,element:(0,u.jsx)(e.component,{})},e.path)),(0,u.jsx)(d.Route,{path:`*`,element:o?a:c})]})})}var Mo=({attributeName:e,onConfirm:t,onCancel:n})=>(0,u.jsx)(`div`,{className:`fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50`,children:(0,u.jsxs)(`div`,{className:`bg-white border border-gray-200 rounded-xl p-6 shadow-2xl max-w-md w-full mx-4`,children:[(0,u.jsx)(`h3`,{className:`text-lg font-semibold text-gray-900 mb-4`,children:`Delete Attribute`}),(0,u.jsxs)(`p`,{className:`text-gray-600 mb-6`,children:[`Are you sure you want to delete the attribute `,(0,u.jsxs)(`span`,{className:`font-mono text-blue-600`,children:[`"`,e,`"`]}),`?`]}),(0,u.jsxs)(`div`,{className:`flex justify-end gap-3`,children:[(0,u.jsx)(`button`,{onClick:n,className:`px-4 py-2 bg-white border border-gray-200 hover:bg-gray-50 hover:border-gray-300 text-gray-700 rounded-lg transition-colors`,children:`Cancel`}),(0,u.jsx)(`button`,{onClick:t,className:`px-4 py-2 bg-red-50 border border-red-200 hover:bg-red-100 text-red-600 rounded-lg transition-colors font-medium`,children:`Delete`})]})]})}),No=({label:e,value:t,onUpdate:n,onDebounced:r})=>{let[i,a]=(0,c.useState)(()=>JSON.stringify(t,null,2)),[o,s]=(0,c.useState)(null);return(0,c.useEffect)(()=>{a(JSON.stringify(t,null,2))},[t]),(0,u.jsxs)(`div`,{className:`w-full`,children:[(0,u.jsx)(`textarea`,{"aria-label":e,value:i,onChange:e=>{a(e.target.value);try{let t=JSON.parse(e.target.value);s(null),r(t)}catch{s(`Invalid JSON`)}},onBlur:()=>{try{let e=JSON.parse(i);s(null),n(e)}catch{s(`Invalid JSON - not saved`)}},className:`w-full bg-white border ${o?`border-red-300`:`border-gray-300`} rounded-lg px-3 py-2 text-sm text-gray-900 font-mono focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-y min-h-[60px]`}),o&&(0,u.jsx)(`p`,{className:`text-xs text-red-600 mt-1`,children:o})]})},Po=({label:e,value:t,onUpdate:n,onDebounced:r})=>{let[i,a]=(0,c.useState)(t??``);return(0,c.useEffect)(()=>{a(t??``)},[t]),(0,u.jsx)(`input`,{type:`text`,"aria-label":e,value:i,onChange:e=>{a(e.target.value),r(e.target.value)},onBlur:e=>n(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),n(i))},className:`w-full bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`})};function Fo({entityId:e}){let{sendStrategyRequest:t}=Ni();if(!e)throw Error(`This view needs an entity to show.`);let n=e,r=X(n),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(``),[l,d]=(0,c.useState)(null),f=(0,c.useRef)(new Map);(0,c.useEffect)(()=>()=>{f.current.forEach(clearTimeout),f.current.clear()},[n]);let p=(0,c.useMemo)(()=>Object.entries(kr(r)).map(([e,t])=>({key:e,value:t})).sort((e,t)=>e.key.localeCompare(t.key)),[r]),m=jr(r),h=e=>Object.prototype.hasOwnProperty.call(kr(r),e),g=(0,c.useCallback)(e=>{let t=e.trim();if(t===``)return``;try{return JSON.parse(t)}catch{return e}},[]),_=(0,c.useCallback)((e,r)=>{if(!n)return;clearTimeout(f.current.get(e)),f.current.delete(e);let i=$.setAttributes(n,{[e]:r});t(i)},[n,t]),v=(0,c.useCallback)((e,t,n=300)=>{clearTimeout(f.current.get(e)),f.current.set(e,setTimeout(()=>_(e,t),n))},[_]),y=(0,c.useCallback)(e=>{n&&(clearTimeout(f.current.get(e)),f.current.delete(e),t($.removeAttribute(n,e)),d(null))},[n,t]),b=(0,c.useCallback)(()=>{let e=i.trim();if(!n||!e||Object.prototype.hasOwnProperty.call(kr(r),e))return;let c=g(o),l=$.setAttributes(n,{[e]:c});t(l),a(``),s(``)},[n,i,o,g,t,r]),x=(0,c.useCallback)((e,t)=>{let n=typeof t;return n===`boolean`?(0,u.jsx)(`input`,{"aria-label":e,type:`checkbox`,checked:t,onChange:t=>_(e,t.target.checked),className:`w-5 h-5 bg-white border border-gray-300 rounded-sm focus:ring-2 focus:ring-blue-500`}):n===`number`?(0,u.jsx)(`input`,{"aria-label":e,type:`number`,defaultValue:t,onChange:t=>{let n=t.target.value===``?0:parseFloat(t.target.value);v(e,n)},onBlur:t=>{let n=t.target.value===``?0:parseFloat(t.target.value);_(e,n)},className:`w-full bg-white border border-gray-300 rounded-lg px-3 py-1.5 text-sm text-gray-900 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`}):n===`object`?(0,u.jsx)(No,{label:e,value:t,onUpdate:t=>_(e,t),onDebounced:t=>v(e,t,500)}):(0,u.jsx)(Po,{label:e,value:t,onUpdate:t=>_(e,t),onDebounced:t=>v(e,t)})},[_,v]);return r?(0,u.jsxs)(`div`,{className:`h-full flex flex-col bg-gray-50 text-gray-900 p-4`,children:[(0,u.jsxs)(`div`,{className:`mb-4`,children:[(0,u.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900`,children:`Entity Attributes`}),(0,u.jsxs)(`p`,{className:`text-sm text-gray-500 mt-1`,children:[`Entity ID: `,(0,u.jsx)(`span`,{className:`font-mono text-gray-700`,children:n})]})]}),(0,u.jsxs)(`section`,{"aria-label":`Fields`,className:`mb-4 overflow-auto rounded-lg border border-gray-200 bg-white p-4`,children:[(0,u.jsx)(`h3`,{className:`mb-3 font-semibold`,children:`Fields`}),(0,u.jsx)(`dl`,{className:`space-y-2`,children:Object.entries(m).map(([e,t])=>(0,u.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,u.jsx)(`dt`,{className:`font-mono text-gray-600`,children:e}),(0,u.jsx)(`dd`,{className:`whitespace-pre-wrap break-all`,children:typeof t==`object`?JSON.stringify(t,null,2):String(t??``)})]},e))})]}),(0,u.jsx)(`h3`,{className:`mb-2 font-semibold`,children:`Attributes`}),(0,u.jsx)(`div`,{role:`region`,"aria-label":`Attributes`,className:`flex-1 overflow-auto bg-white border border-gray-200 rounded-lg shadow-xs`,children:(0,u.jsxs)(`table`,{className:`w-full border-collapse`,children:[(0,u.jsx)(`thead`,{className:`sticky top-0 bg-white border-b border-gray-200`,children:(0,u.jsxs)(`tr`,{children:[(0,u.jsx)(`th`,{className:`text-left px-4 py-3 text-xs font-medium uppercase tracking-wide text-gray-500 w-1/3`,children:`Attribute Name`}),(0,u.jsx)(`th`,{className:`text-left px-4 py-3 text-xs font-medium uppercase tracking-wide text-gray-500`,children:`Value`}),(0,u.jsx)(`th`,{className:`text-center px-4 py-3 text-xs font-medium uppercase tracking-wide text-gray-500 w-20`,children:`Actions`})]})}),(0,u.jsx)(`tbody`,{children:p.length===0?(0,u.jsx)(`tr`,{children:(0,u.jsx)(`td`,{colSpan:3,className:`px-4 py-8 text-center text-gray-500`,children:`No attributes found`})}):p.map(({key:e,value:t})=>(0,u.jsxs)(`tr`,{className:`border-b border-gray-100 hover:bg-gray-50`,children:[(0,u.jsx)(`td`,{className:`px-4 py-3`,children:(0,u.jsx)(`code`,{className:`text-sm text-blue-600 font-mono`,children:e})}),(0,u.jsx)(`td`,{className:`px-4 py-3`,children:x(e,t)}),(0,u.jsx)(`td`,{className:`px-4 py-3 text-center`,children:(0,u.jsx)(`button`,{"aria-label":`Delete ${e}`,onMouseDown:e=>e.preventDefault(),onClick:()=>{clearTimeout(f.current.get(e)),f.current.delete(e),d(e)},className:`text-red-500 hover:text-red-600 transition-colors p-1 rounded-sm`,title:`Delete attribute`,children:(0,u.jsx)(`svg`,{className:`w-5 h-5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,u.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16`})})})})]},`${n}:${e}`))})]})}),(0,u.jsxs)(`div`,{className:`mt-4 pt-4 border-t border-gray-200`,children:[(0,u.jsx)(`h3`,{className:`text-sm font-medium text-gray-700 mb-3`,children:`Add New Attribute`}),(0,u.jsxs)(`div`,{className:`flex gap-3`,children:[(0,u.jsx)(`input`,{type:`text`,placeholder:`Attribute name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),b())},className:`flex-1 bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`}),(0,u.jsx)(`input`,{type:`text`,placeholder:`Value (JSON or string)`,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),b())},className:`flex-1 bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`}),(0,u.jsx)(`button`,{onClick:b,disabled:!i.trim()||h(i.trim()),className:`px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-200 disabled:cursor-not-allowed text-white border border-blue-600 rounded-lg transition-colors font-medium`,children:`Add`})]}),(0,u.jsxs)(`p`,{className:`text-xs text-gray-500 mt-2`,children:[`Tip: Use JSON format for objects, arrays, booleans, or numbers (e.g., `,(0,u.jsx)(`code`,{className:`text-gray-600`,children:`true`}),`, `,(0,u.jsx)(`code`,{className:`text-gray-600`,children:`42`}),`, `,(0,u.jsx)(`code`,{className:`text-gray-600`,children:`{"key": "value"}`}),`)`]})]}),l&&(0,u.jsx)(Mo,{attributeName:l,onConfirm:()=>y(l),onCancel:()=>d(null)})]}):(0,u.jsx)(`div`,{className:`flex items-center justify-center h-full bg-gray-50 text-gray-600 p-4`,children:(0,u.jsxs)(`div`,{className:`text-center`,children:[(0,u.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-4`}),(0,u.jsx)(`div`,{children:`Loading entity...`})]})})}var Io=na(`entity_attributes`,e=>(0,u.jsx)(Fo,{...e},e.entityId)),Lo=e=>`${e.slot??``}@${e.entityId}`;function Ro(e,t){let n=new Set(e.filter(e=>e.entityId===t).map(e=>e.slot));if(!n.has(void 0))return;let r=2;for(;n.has(`panel${r}`);)r+=1;return`panel${r}`}function zo(e){let[t,n]=Fa(e),r=t.panels;return{state:t,update:n,panels:r,addPanel:(0,c.useCallback)(e=>{let t={entityId:e},i=Ro(r,e);return i&&(t.slot=i),n({panels:[...r,t]})},[r,n]),removePanel:(0,c.useCallback)(e=>{let i={...t.sizes};return delete i[e],n({panels:r.filter(t=>Lo(t)!==e),sizes:i})},[r,t.sizes,n])}}function Bo({onPick:e}){let t=La(),[n,r]=(0,c.useState)(!1);return(0,u.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,u.jsx)(`button`,{type:`button`,title:`Add panel`,onClick:()=>r(e=>!e),className:`flex h-7 w-7 items-center justify-center rounded-sm text-gray-500 hover:bg-gray-200 hover:text-gray-900`,children:(0,u.jsx)(An,{className:`h-4 w-4`})}),n&&t.length>0&&(0,u.jsx)(`div`,{className:`absolute right-0 z-20 mt-1 w-72 rounded-lg border border-gray-200 bg-white p-2 shadow-lg nodrag`,children:(0,u.jsx)(aa,{typeIds:t,onPick:t=>{r(!1),e(t.entity_id)},placeholder:`Add an entity…`,autoFocus:!0,listPlacement:`below`},t.join(`,`))})]})}function Vo({onClick:e}){return(0,u.jsx)(`span`,{role:`button`,title:`Remove panel`,className:`shrink-0 rounded-sm p-0.5 opacity-60 hover:bg-gray-200 hover:opacity-100`,onClick:e,children:(0,u.jsx)(On,{className:`h-3.5 w-3.5`})})}var Ho={panels:[],sizes:{}};function Uo({direction:e}){let{state:t,panels:n,addPanel:r,removePanel:i}=zo(Ho),a=e===`row`;return(0,u.jsxs)(`div`,{className:`flex h-full w-full flex-col`,children:[(0,u.jsx)(`div`,{className:`flex shrink-0 items-center justify-end gap-1 border-b border-gray-200 bg-gray-50/70 px-1`,children:(0,u.jsx)(Bo,{onPick:e=>void r(e)})}),n.length===0?(0,u.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-sm text-gray-500`,children:`Empty layout - add a panel to populate`}):(0,u.jsx)(`div`,{className:`flex min-h-0 flex-1 gap-1 bg-gray-200 ${a?`flex-row`:`flex-col`}`,children:n.map(e=>{let n=Lo(e);return(0,u.jsxs)(`div`,{style:{flex:`${t.sizes[n]??1} 1 0`},className:`relative min-h-0 min-w-0 overflow-hidden bg-white`,children:[(0,u.jsx)(`div`,{className:`absolute left-1 top-1 z-10`,children:(0,u.jsx)(Vo,{onClick:()=>void i(n)})}),(0,u.jsx)(ho,{entityId:e.entityId,slot:e.slot,className:`h-full`})]},n)})})]})}var Wo=na(`composite_hbox`,()=>(0,u.jsx)(Uo,{direction:`row`})),Go=na(`composite_vbox`,()=>(0,u.jsx)(Uo,{direction:`column`})),Ko={panels:[],sizes:{},active:null};function qo(){let{state:e,update:t,panels:n,addPanel:r,removePanel:i}=zo(Ko),a=Er((0,c.useMemo)(()=>n.map(e=>e.entityId),[n])),o=(0,c.useMemo)(()=>Object.fromEntries(a.map(e=>[e.entity_id,Z(e)])),[a]),s=n.find(t=>Lo(t)===e.active)??n[0],l=s?Lo(s):null;return(0,u.jsxs)(`div`,{className:`flex h-full w-full flex-col`,children:[(0,u.jsxs)(`div`,{className:`flex shrink-0 items-center overflow-x-auto border-b border-gray-200 bg-gray-50/70`,children:[n.map(e=>{let n=Lo(e),r=o[e.entityId]??e.entityId;return(0,u.jsxs)(`button`,{type:`button`,onClick:()=>void t({active:n}),title:r,className:`flex max-w-48 shrink-0 items-center gap-2 border-r border-gray-200 px-3 py-2 text-sm ${l===n?`bg-white text-gray-900`:`bg-gray-50 text-gray-600 hover:bg-gray-100`}`,children:[(0,u.jsx)(`span`,{className:`truncate`,children:r}),(0,u.jsx)(Vo,{onClick:e=>{e.stopPropagation(),i(n)}})]},n)}),(0,u.jsx)(`div`,{className:`ml-auto px-1`,children:(0,u.jsx)(Bo,{onPick:e=>void r(e)})})]}),(0,u.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:s?(0,u.jsx)(ho,{entityId:s.entityId,slot:s.slot,className:`h-full`},l):(0,u.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-gray-500`,children:`Empty tabbed layout - add a panel to populate`})})]})}var Jo=na(`composite_tabs`,qo);function Yo({entityId:e}){if(!e)throw Error(`This view needs an entity to show.`);let{sendStrategyRequest:t}=Ni(),[n,r]=(0,c.useState)(null),[i,a]=(0,c.useState)(null),[o,s]=(0,c.useState)(null),[l,d]=(0,c.useState)(null),[p,m]=(0,c.useState)(``),[h,g]=(0,c.useState)(!1),_=X(e),v=Dr(e,{}),y=(0,c.useMemo)(()=>(v||[]).filter(e=>e.entity_type_id!==Y.VIEW),[v]);(0,c.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&r(null)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[n]);let b=_||{},x=Z(b),S=Ar(b,`list_purpose`),C=typeof S==`string`?S:``,w=Ar(b,`description`),T=typeof w==`string`?w:``,E=(0,c.useMemo)(()=>y.find(e=>e.entity_id===n),[y,n]),D=(0,c.useMemo)(()=>y.find(e=>e.entity_id===i)||null,[y,i]),O=()=>{s(null),d(null)},k=(e,t)=>{e.stopPropagation(),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),s(t)},A=(e,t)=>{if(!o||o===t)return;e.preventDefault();let n=e.currentTarget.getBoundingClientRect(),r=n.top+n.height/2,i=e.clientY<r?`before`:`after`;d(e=>e?.entityId===t&&e.position===i?e:{entityId:t,position:i})},j=(e,n,r)=>{e&&n&&e!==n&&t(r===`before`?$.moveChildBefore(e,n):$.moveChildAfter(e,n))},M=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=o||e.dataTransfer.getData(`text/plain`),r=l?.entityId===t?l.position:`after`;j(n,t,r),O()},N=e=>{n===e&&r(null),t($.detachChild(e))},ee=e=>{n===e&&r(null),a(e)},te=()=>{i&&(t($.deleteEntity(i)),a(null))},P=async()=>{let n=p.trim();if(n&&!h){g(!0);try{await t($.createEntity(e,Y.ENTITY,{name:n}),{awaitResponse:!0}),m(``)}finally{g(!1)}}};return _?(0,u.jsxs)(`div`,{className:`flex h-full flex-col bg-gray-50 text-gray-900`,children:[(0,u.jsxs)(`div`,{className:`shrink-0 border-b border-gray-200 bg-white px-6 py-4`,children:[(0,u.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight text-gray-900`,children:x}),T&&(0,u.jsx)(`p`,{className:`mt-1 text-sm text-gray-600`,children:T})]}),C&&(0,u.jsx)(`span`,{className:`rounded-full border border-gray-200 bg-gray-50 px-3 py-1 text-xs font-medium text-gray-600`,children:C})]}),(0,u.jsxs)(`div`,{className:`mt-3 flex items-center gap-2`,children:[(0,u.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P())},placeholder:`New entity name…`,disabled:h,className:`flex-1 max-w-xs rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-900 placeholder-gray-400 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50`}),(0,u.jsx)(`button`,{type:`button`,onClick:P,disabled:!p.trim()||h,className:`rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400`,children:h?`Creating…`:`+ New Entity`}),(0,u.jsxs)(`span`,{className:`ml-auto text-xs font-medium text-gray-500`,children:[y.length,` `,y.length===1?`item`:`items`]})]})]}),(0,u.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1.5`,children:y.length===0?(0,u.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-center text-gray-500`,children:[(0,u.jsx)(`h3`,{className:`text-lg font-medium text-gray-900`,children:`No items yet`}),(0,u.jsx)(`p`,{className:`mt-1 max-w-sm text-sm text-gray-600`,children:`Add child entities to this list to build a durable artifact.`})]}):(0,u.jsx)(`div`,{className:`overflow-hidden rounded-md border border-gray-200 bg-white`,children:y.map(e=>{let t=e||{},n=e.entity_id,i=o===n,a=l?.entityId===n&&l.position===`before`,s=l?.entityId===n&&l.position===`after`;return(0,u.jsxs)(`div`,{onDragOver:e=>A(e,n),onDrop:e=>M(e,n),onDragEnd:O,className:`group flex items-center gap-1 border-b border-gray-200 px-2 py-1 last:border-b-0 hover:bg-gray-50 ${i?`opacity-50`:``} ${a?`border-t-2 border-t-blue-500`:``} ${s?`border-b-2 border-b-blue-500`:``}`,children:[(0,u.jsx)(`div`,{draggable:!0,onDragStart:e=>k(e,n),onDragEnd:O,className:`flex h-5 w-5 shrink-0 cursor-grab items-center justify-center rounded-sm text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 active:cursor-grabbing`,title:`Drag to reorder`,"aria-label":`Drag ${Z(t)} to reorder`,children:(0,u.jsx)(gn,{className:`h-4 w-4`})}),(0,u.jsxs)(`button`,{type:`button`,onClick:()=>r(n),className:`flex min-w-0 flex-1 items-center gap-2 text-left focus:outline-hidden focus:ring-2 focus:ring-inset focus:ring-blue-500`,children:[(0,u.jsx)(`div`,{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-xs bg-gray-100 text-gray-500`,children:(0,u.jsx)(Ma,{entityTypeId:t.entity_type_id,className:`h-3 w-3`})}),(0,u.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,u.jsx)(`div`,{className:`truncate text-sm font-medium leading-5 text-gray-900`,children:Z(t)})})]}),(0,u.jsxs)(`div`,{className:`flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),N(n)},"aria-label":`Remove ${Z(t)} from list`,title:`Remove from list`,className:`rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700`,children:(0,u.jsx)(On,{className:`h-3.5 w-3.5`})}),(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ee(n)},"aria-label":`Delete ${Z(t)}`,title:`Delete entity`,className:`rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-600`,children:(0,u.jsx)(pn,{className:`h-3.5 w-3.5`})})]})]},n)})})}),i&&(0,f.createPortal)((0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/50`,onClick:()=>a(null)}),(0,u.jsxs)(`div`,{className:`relative mx-4 w-full max-w-md rounded-lg border border-gray-200 bg-white p-6 shadow-xl`,onClick:e=>e.stopPropagation(),children:[(0,u.jsxs)(`div`,{className:`mb-4 flex items-center gap-3`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-full border border-amber-200 bg-amber-50`,children:(0,u.jsx)(fn,{className:`h-5 w-5 text-amber-600`})}),(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h3`,{className:`text-lg font-semibold text-gray-900`,children:`Confirm Delete`}),(0,u.jsx)(`p`,{className:`text-sm text-gray-600`,children:`This action cannot be undone`})]})]}),(0,u.jsxs)(`p`,{className:`mb-6 text-gray-700`,children:[`Are you sure you want to delete`,` `,(0,u.jsxs)(`span`,{className:`font-medium text-gray-900`,children:[`"`,Z(D),`"`]}),`? This will permanently delete the entity and all its data.`]}),(0,u.jsxs)(`div`,{className:`flex justify-end gap-3`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>a(null),className:`rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm text-gray-600 transition-colors hover:bg-gray-50`,children:`Cancel`}),(0,u.jsx)(`button`,{type:`button`,onClick:te,className:`rounded-lg bg-red-600 px-4 py-2 text-sm text-white transition-colors hover:bg-red-700`,children:`Delete Entity`})]})]})]}),document.body),n&&(0,f.createPortal)((0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/40 backdrop-blur-xs`,onClick:()=>r(null)}),(0,u.jsxs)(`div`,{className:`relative flex h-[90%] w-[92%] max-w-5xl flex-col rounded-xl border border-gray-200 bg-white shadow-2xl`,onClick:e=>e.stopPropagation(),children:[(0,u.jsxs)(`div`,{className:`flex items-center justify-between border-b border-gray-200 px-4 py-3`,children:[(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h3`,{className:`text-sm font-semibold text-gray-900`,children:Z(E)}),(0,u.jsx)(`div`,{className:`text-xs text-gray-500`,children:Mr(E)})]}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(null),className:`text-2xl leading-none text-gray-400 transition-colors hover:text-gray-600`,title:`Close (Esc)`,children:`×`})]}),(0,u.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-4`,children:(0,u.jsx)(ho,{entityId:n})})]})]}),document.body)]}):(0,u.jsx)(`div`,{className:`flex h-full items-center justify-center bg-gray-50 text-gray-500`,children:`Loading list...`})}var Xo=na(`list_view`,Yo),Zo={ENTITY_ID:`application/x-entity-id`,ENTITY_DATA:`application/x-entity-data`,SOURCE_CONTEXT:`application/x-source-context`},Qo=class{static startDrag(e,t,n={}){let{dragEffect:r=`move`,dragImage:i,dragImageText:a}=n;if(e.dataTransfer.setData(Zo.ENTITY_ID,t.entityId),e.dataTransfer.setData(Zo.ENTITY_DATA,JSON.stringify(t)),t.sourceContext&&e.dataTransfer.setData(Zo.SOURCE_CONTEXT,t.sourceContext),e.dataTransfer.effectAllowed=r,a&&!i){let t=this.createDragImage(a);e.dataTransfer.setDragImage(t,0,0),setTimeout(()=>document.body.removeChild(t),0)}else i&&e.dataTransfer.setDragImage(i,0,0);console.log(`🎯 Entity drag started:`,t)}static handleDrop(e,t){e.preventDefault(),e.stopPropagation();let n=e.dataTransfer.getData(Zo.ENTITY_ID);if(!n)return console.warn(`🚫 No entity ID found in drag data`),!1;let r={entityId:n};try{let t=e.dataTransfer.getData(Zo.ENTITY_DATA);t&&(r=JSON.parse(t))}catch(e){console.warn(`⚠️ Could not parse full drag data, using entity ID only:`,e)}return console.log(`🎯 Entity drop handled:`,r),t(r),!0}static handleDragOver(e,t={}){let{dropEffect:n=`move`,acceptedTypes:r}=t;return!e.dataTransfer.getData(Zo.ENTITY_ID)&&r?!1:(e.preventDefault(),e.dataTransfer.dropEffect=n,!0)}static createDragImage(e){let t=document.createElement(`div`);return t.style.position=`absolute`,t.style.top=`-1000px`,t.style.backgroundColor=`rgba(55, 65, 81, 0.9)`,t.style.color=`white`,t.style.padding=`8px 12px`,t.style.borderRadius=`6px`,t.style.fontSize=`0.875rem`,t.style.fontWeight=`500`,t.style.border=`1px solid rgba(75, 85, 99, 0.5)`,t.style.boxShadow=`0 4px 6px -1px rgba(0, 0, 0, 0.1)`,t.textContent=e,document.body.appendChild(t),t}static hasValidEntityData(e){return!!e.dataTransfer.getData(Zo.ENTITY_ID)}static getEntityId(e){return e.dataTransfer.getData(Zo.ENTITY_ID)||null}};function $o(e){return{onDragOver:t=>{Qo.handleDragOver(t,{dropEffect:e.dropEffect,acceptedTypes:e.acceptedTypes})&&e.onDragOver&&e.onDragOver(t.nativeEvent)},onDrop:t=>{Qo.handleDrop(t,e.onDrop)},onDragEnter:t=>{Qo.hasValidEntityData(t)&&e.onDragEnter&&e.onDragEnter(t.nativeEvent)},onDragLeave:t=>{e.onDragLeave&&e.onDragLeave(t.nativeEvent)}}}var es=Object.values(Y),ts=Kt(`parent_id`,null);function ns(e){if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=es.find(e=>e===t);if(n)return n;let r=new Set;t.endsWith(`Entity`)?r.add(t):(r.add(`${t}Entity`),r.add(`${t.charAt(0).toUpperCase()}${t.slice(1)}Entity`));for(let e of r){let t=es.find(t=>t.endsWith(`.${e}`));if(t)return t}return t.includes(`.`)?t:null}function rs(e){let t=new Set,n=[];return e.forEach(e=>{let r=ns(e);r&&!t.has(r)&&(t.add(r),n.push(r))}),n}var is=new Set([Y.VIEW,Y.GRANT,Y.DEPLOYMENT,Y.STRATEGY_REQUEST]);function as(e){return Object.entries(e).filter(([e,t])=>!is.has(e)&&!t?.principal).map(([e])=>e).sort()}var os=c.default.forwardRef(({position:e,options:t,onSelect:n},r)=>{let[i,a]=(0,c.useState)(``),o=(0,c.useMemo)(()=>{let e=i.trim().toLowerCase();return Object.entries(t).filter(([t,n])=>!e||String(n?.name||t).toLowerCase().includes(e)||t.toLowerCase().includes(e))},[t,i]);return(0,f.createPortal)((0,u.jsxs)(`div`,{ref:r,className:`fixed w-64 bg-white border border-gray-200 rounded-lg shadow-xl z-9999 flex flex-col max-h-96`,style:{top:e.top,left:e.left},children:[(0,u.jsx)(`div`,{className:`p-2 border-b border-gray-200`,children:(0,u.jsx)(`input`,{type:`text`,value:i,onChange:e=>a(e.target.value),placeholder:`Search entity types...`,autoFocus:!0,className:`w-full px-2 py-1 text-xs bg-white text-gray-900 border border-gray-300 rounded-sm focus:outline-hidden focus:ring-1 focus:ring-blue-500 placeholder-gray-500`})}),(0,u.jsx)(`div`,{className:`overflow-y-auto p-2`,children:o.length>0?o.map(([e,t])=>(0,u.jsxs)(`button`,{onClick:()=>n(e),className:`w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-sm transition-colors flex items-center gap-2`,title:e,children:[(0,u.jsx)(Ma,{entityTypeId:e,className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`span`,{className:`truncate`,children:t?.name||e})]},e)):(0,u.jsx)(`div`,{className:`px-3 py-2 text-xs text-gray-500`,children:i?`No matching entity types`:`Loading entity types...`})})]}),document.body)}),ss=({typeId:e,typeName:t,count:n,isExpanded:r,onToggle:i,depth:a})=>(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5 py-0.5 px-2 text-xs text-gray-500 cursor-pointer hover:bg-gray-50 rounded-sm select-none`,style:{paddingLeft:`${a*16+8}px`},onClick:i,children:[(0,u.jsx)(`span`,{className:`text-xs`,children:r?`▼`:`▶`}),(0,u.jsx)(Ma,{entityTypeId:e,className:`w-3.5 h-3.5 shrink-0`}),(0,u.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:t}),(0,u.jsxs)(`span`,{className:`text-gray-400`,children:[`(`,n,`)`]})]}),cs=({entityId:e,parentId:t,selectedEntityId:n=null,onSelect:r,onDoubleClick:i,onPin:a,onDelete:o,onCreateChild:s,expandedEntities:l,onToggleExpanded:d,depth:f=0,onEntityMove:p,onEntityAdd:m,onRemoveChild:h,availableEntities:g={},allowCreate:_=!0,filterTypeIds:v=[],showDeleteAction:y=!0,showCreateChildAction:b=!0,ancestors:S=new Set,groupByEntityType:C=!0,revealEntityId:w,revealAncestors:T})=>{let E=S.has(e),D=(0,c.useMemo)(()=>new Set([...S,e]),[S,e]),O=X(e),[k,A]=(0,c.useState)(!1),[j,M]=(0,c.useState)(!1),[N,ee]=(0,c.useState)(null),[te,P]=(0,c.useState)(!1),[F,I]=(0,c.useState)(new Set),[ne,L]=(0,c.useState)(void 0),re=(0,c.useRef)(null),ie=(0,c.useRef)(null),R=(0,c.useRef)(null),ae=(0,c.useRef)(null),z=l.has(e),oe=Dr(e,{types:v,enabled:!!O?.children_ids?.length}),se=oe.length>0,ce=z?oe:[];if(w!==ne){L(w);let e=new Set;w&&C&&oe.forEach(t=>{(t.entity_id===w||T?.has(t.entity_id))&&e.add(t.entity_type_id||`unknown`)}),I(e)}let le=(0,c.useCallback)(()=>{r?.(e)},[e,r]),ue=(0,c.useCallback)(()=>{i(e)},[e,i]),de=(0,c.useCallback)(t=>{t.preventDefault(),t.stopPropagation(),se&&d(e)},[e,se,d]);(0,c.useCallback)(()=>{a&&a(e)},[e,a]);let B=(0,c.useMemo)(()=>{let e=v.length>0?new Set(v):null;return Object.entries(g).filter(([t])=>!e||e.has(t))},[g,v]),V=(0,c.useMemo)(()=>Object.fromEntries(B),[B]),fe=(0,c.useCallback)(t=>{if(t.stopPropagation(),z||d(e),B.length===1){let[t]=B[0];s&&s(e,t),M(!1);return}let n=!j;if(n&&ie.current){let e=ie.current.getBoundingClientRect();ee({top:e.bottom+4,left:Math.max(8,Math.min(e.right-256,window.innerWidth-256-8))})}M(n)},[B,e,z,s,d,j]),pe=(0,c.useCallback)(t=>{z||d(e),s&&s(e,t),M(!1)},[e,z,s,d]);(0,c.useEffect)(()=>{let e=e=>{let t=e.target;re.current&&!re.current.contains(t)&&R.current&&!R.current.contains(t)&&M(!1)};if(j)return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[j]);let me=(0,c.useCallback)(t=>{t.stopPropagation(),navigator.clipboard?.writeText(e),P(!1)},[e]),he=(0,c.useCallback)(t=>{t.stopPropagation(),window.open(`${window.location.origin}${x(ri(e))}`,`_blank`,`noopener,noreferrer`),P(!1)},[e]),ge=(0,c.useCallback)(n=>{n.stopPropagation(),t&&h&&h(e,t),P(!1)},[e,h,t]);(0,c.useEffect)(()=>{let e=e=>{ae.current&&!ae.current.contains(e.target)&&P(!1)};if(te)return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[te]);let _e=(0,c.useCallback)(n=>{if(!O)return;let r=O.entity_type_id,i=Z(O);Qo.startDrag(n,{entityId:e,entityType:r,sourceContext:`entity-explorer`,sourceParentId:t},{dragEffect:`move`,dragImageText:i})},[O,e,t]),H=$o({dropEffect:`move`,onDrop:t=>{console.log(`Entity dropped on EntityItem:`,t,`target:`,e),A(!1),t.entityId!==e&&(t.sourceContext===`entity-explorer`&&t.sourceParentId?p?.(t.entityId,e,t.sourceParentId):m?.(t.entityId,e))},onDragEnter:()=>{A(!0)},onDragLeave:()=>{A(!1)}});if(!O){let n={paddingLeft:`${f*16+8}px`};return(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5 py-1 px-2 text-xs text-gray-600`,style:n,children:[(0,u.jsx)(`div`,{className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`span`,{className:`flex-1`,children:`(missing)`}),t&&h&&(0,u.jsx)(`button`,{onClick:()=>h(e,t),className:`shrink-0 w-4 h-4 flex items-center justify-center text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-sm transition-all`,title:`Remove missing entity from parent`,children:(0,u.jsx)(On,{className:`w-3.5 h-3.5`})})]})}if(E){let n={paddingLeft:`${f*16+8}px`},r=Z(O);return(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5 py-1 px-2 text-xs text-gray-400 italic`,style:n,title:`Circular reference — this entity already appears above in the tree`,children:[(0,u.jsx)(kn,{className:`w-3.5 h-3.5 shrink-0`}),(0,u.jsxs)(`span`,{className:`truncate flex-1`,children:[r,` (circular ref)`]}),t&&h&&(0,u.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),h(e,t)},className:`shrink-0 w-4 h-4 flex items-center justify-center text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-sm transition-all`,title:`Remove circular reference from parent`,children:(0,u.jsx)(On,{className:`w-3.5 h-3.5`})})]})}let U=O?.entity_type_id||``,ve=n===e,W=Ar(O,`name`),G=U===Y.VIEW?typeof W==`string`&&W?W:O?.component||Z(O):Z(O),ye={paddingLeft:`${f*16+8}px`};return(0,u.jsxs)(`div`,{className:`relative`,children:[(0,u.jsxs)(`div`,{draggable:!0,className:`flex items-center gap-1.5 py-1 px-2 rounded text-sm transition-all cursor-grab select-none hover:bg-gray-100 text-gray-700 w-full ${ve?`bg-blue-50 border border-blue-200 text-blue-700`:``} ${k?`ring-2 ring-blue-500 ring-inset bg-blue-50`:``}`,style:ye,onClick:le,onDoubleClick:ue,onDragStart:_e,...H,title:`${U} • ${G} • Double-click to open • Click pin to dock • Drag to move • Drop entities to add as children • ${e}`,children:[se&&(0,u.jsx)(`div`,{className:`shrink-0 w-4 h-4 flex items-center justify-center text-xs text-gray-500 hover:text-gray-300 cursor-pointer`,onClick:de,title:`Click to expand/collapse`,children:z?`▼`:`▶`}),!se&&(0,u.jsx)(`div`,{className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`div`,{className:`shrink-0`,children:(0,u.jsx)(Ma,{entityTypeId:U,className:`w-4 h-4`})}),(0,u.jsx)(`div`,{className:`truncate min-w-0 font-medium flex-1`,children:G}),_&&b&&(0,u.jsxs)(`div`,{className:`relative shrink-0`,ref:re,children:[(0,u.jsx)(`button`,{ref:ie,onClick:fe,className:`w-6 h-6 flex items-center justify-center text-xs text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-sm transition-all`,title:`Add child entity`,children:`+`}),j&&N&&(0,u.jsx)(os,{ref:R,position:N,options:V,onSelect:pe})]}),y&&(0,u.jsx)(`button`,{onClick:t=>{t.stopPropagation(),console.log(`Delete button clicked for entity:`,e),o&&o(e)},type:`button`,className:`shrink-0 w-6 h-6 flex items-center justify-center text-xs text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-sm transition-all`,title:`Delete entity`,children:(0,u.jsx)(pn,{className:`w-3.5 h-3.5`})}),(0,u.jsxs)(`div`,{className:`relative shrink-0`,ref:ae,children:[(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),P(e=>!e)},className:`w-6 h-6 flex items-center justify-center text-xs text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-sm transition-all`,title:`More actions`,children:(0,u.jsx)(Cn,{className:`w-3.5 h-3.5`})}),te&&(0,u.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded-lg shadow-xl z-9999 p-1`,children:[(0,u.jsxs)(`button`,{type:`button`,onClick:me,className:`w-full px-2 py-1.5 text-xs text-gray-700 hover:bg-gray-50 rounded-sm flex items-center gap-2`,children:[(0,u.jsx)(En,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Copy entity ID`})]}),(0,u.jsxs)(`button`,{type:`button`,onClick:he,className:`w-full px-2 py-1.5 text-xs text-gray-700 hover:bg-gray-50 rounded-sm flex items-center gap-2`,children:[(0,u.jsx)(yn,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Open in new tab`})]}),t&&h&&(0,u.jsxs)(`button`,{type:`button`,onClick:ge,className:`w-full px-2 py-1.5 text-xs text-gray-700 hover:bg-red-50 hover:text-red-600 rounded-sm flex items-center gap-2`,children:[(0,u.jsx)(On,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Remove link from parent`})]})]})]})]}),z&&ce.length>0&&(0,u.jsx)(`div`,{className:`mt-0.5 space-y-0.5`,children:C?(()=>{let t=new Map;return ce.forEach(e=>{let n=e.entity_type_id||`unknown`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),Array.from(t.entries()).map(([t,c])=>{let x=F.has(t),S=g[t]?.name||t.split(`.`).pop()||t;return(0,u.jsxs)(`div`,{children:[(0,u.jsx)(ss,{typeId:t,typeName:S,count:c.length,isExpanded:x,onToggle:()=>I(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),depth:f+1}),x&&c.map(t=>(0,u.jsx)(cs,{entityId:t.entity_id,parentId:e,onDoubleClick:i,onPin:a,onDelete:o,onCreateChild:s,expandedEntities:l,onToggleExpanded:d,onEntityMove:p,onEntityAdd:m,onRemoveChild:h,availableEntities:g,allowCreate:_,filterTypeIds:v,showDeleteAction:y,showCreateChildAction:b,selectedEntityId:n,onSelect:r,depth:f+2,ancestors:D,groupByEntityType:C,revealEntityId:w,revealAncestors:T},t.entity_id))]},t)})})():ce.map(t=>(0,u.jsx)(cs,{entityId:t.entity_id,parentId:e,onDoubleClick:i,onPin:a,onDelete:o,onCreateChild:s,expandedEntities:l,onToggleExpanded:d,onEntityMove:p,onEntityAdd:m,onRemoveChild:h,availableEntities:g,allowCreate:_,filterTypeIds:v,showDeleteAction:y,showCreateChildAction:b,selectedEntityId:n,onSelect:r,depth:f+1,ancestors:D,groupByEntityType:C,revealEntityId:w,revealAncestors:T},t.entity_id))})]})},ls=na(`entity_explorer`,({entityId:e,uiHooks:t,onEntityDelete:n,onEntityOpen:r,onEntitySelect:i,onEntityPin:a,explorerConfig:o})=>{let{sendStrategyRequest:s}=Ni(),l=e||``,[d,p]=Fa({}),m=Hi(),h=m.state===`hasValue`?m.contents:{};(0,c.useEffect)(()=>{Bi()},[]);let{onEntityOpen:g,onEntityPin:_,onEntitySelect:v}=t||{},y=r??g,b=a??_,x=i??v,S=o?.allow_create??!0,C=o?.title||`Explorer`,w=o?.show_delete_action??!0,T=o?.show_create_child_action??!0,E=o?.group_by_entity_type??!0,D=o?.reveal_entity_id??null,O=(0,c.useMemo)(()=>{let e=rs(Array.isArray(o?.filter_entity_types)?o.filter_entity_types:[]);return e.length>0?e:as(h)},[o?.filter_entity_types,h]),k=(0,c.useMemo)(()=>rs(Array.isArray(d.explorer_active_filter_entity_types)?d.explorer_active_filter_entity_types:[]),[d.explorer_active_filter_entity_types]),A=Array.isArray(d.explorer_active_filter_entity_types)?k:O,j=!e,M=Li({typeIds:(0,c.useMemo)(()=>A.length>0?A:Object.keys(h).sort(),[A,h]),where:ts,enabled:j}),[N,ee]=(0,c.useState)(null),te=(0,c.useRef)(null),P=(0,c.useRef)(null),F=(0,c.useCallback)(()=>{ee(e=>{let t=te.current?.getBoundingClientRect();return e||!t?null:{top:t.bottom+4,left:Math.max(8,Math.min(t.left,window.innerWidth-256-8))}})},[]);(0,c.useEffect)(()=>{if(!N)return;let e=e=>{let t=e.target;!P.current?.contains(t)&&!te.current?.contains(t)&&ee(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[N]);let ne=(0,c.useMemo)(()=>Object.fromEntries(Object.entries(h).filter(([e])=>A.length===0||A.includes(e))),[h,A]),[L,re]=(0,c.useState)(!1),[ie,R]=(0,c.useState)(``),[ae,z]=(0,c.useState)(null),oe=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(!L)return;let e=e=>{oe.current&&!oe.current.contains(e.target)&&re(!1)};return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[L]);let se=(0,c.useMemo)(()=>{let e=ie.trim().toLowerCase();return e?Object.entries(h).filter(([t,n])=>String(n?.name||t).toLowerCase().includes(e)||String(t).toLowerCase().includes(e)):Object.entries(h)},[h,ie]),ce=(0,c.useCallback)(e=>{p({explorer_active_filter_entity_types:e})},[p]),le=(0,c.useCallback)(e=>{y?.(e,l)},[y,l]),ue=(0,c.useCallback)(e=>{z(e),x?.(e,l)},[x,l]),de=(0,c.useCallback)(e=>{b?.(e,l)},[b,l]),B=(0,c.useCallback)(e=>{H(e)},[]),V=(0,c.useCallback)((e,t,n)=>{if(console.log(`Moving entity:`,e,`from:`,n,`to:`,t),e===t||n===t)return;let r=$.reparentChild(e,t);s(r)},[s]),fe=(0,c.useCallback)((e,t)=>{if(console.log(`Adding entity:`,e,`to:`,t),e===t)return;let n=$.reparentChild(e,t);s(n)},[s]),pe=(0,c.useCallback)(async(e,t)=>{try{let n=(await Promise.resolve(s($.createEntity(e,t),{awaitResponse:!0})))?.child_entity;n&&(e&&ge(t=>new Set(t).add(e)),z(n),x?.(n,e??``))}catch(e){console.error(`Failed to create entity:`,e)}},[x,s]),me=(0,c.useCallback)((e,t)=>{console.log(`Removing child:`,e,`from parent:`,t);let n=$.detachChild(e);s(n)},[s]),[he,ge]=(0,c.useState)(new Set([l])),[_e,H]=(0,c.useState)(null),U=X(l),ve=X(_e||l),W=(0,c.useMemo)(()=>!_e||!ve?`this entity`:Z(ve),[_e,ve]),G=(0,c.useMemo)(()=>{if(!D)return new Set;let e=new Set,t=new Set,n=[D];for(;n.length>0;){let r=n.shift();if(t.has(r))continue;if(t.add(r),r===l)break;let i=I.readEntity(r);for(let r of i?.parent_ids??[])r&&!t.has(r)&&(e.add(r),n.push(r))}return e},[D,l]);(0,c.useEffect)(()=>{D&&(ge(e=>new Set([...e,...G])),z(D))},[D,G]);let ye=(0,c.useCallback)(e=>{ge(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),be=(0,c.useMemo)(()=>_e?(0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/50`,onClick:()=>H(null)}),(0,u.jsxs)(`div`,{className:`relative bg-white border border-gray-200 rounded-lg shadow-xl p-6 max-w-md w-full mx-4`,onClick:e=>e.stopPropagation(),children:[(0,u.jsxs)(`div`,{className:`flex items-center gap-3 mb-4`,children:[(0,u.jsx)(`div`,{className:`w-10 h-10 rounded-full bg-amber-50 border border-amber-200 flex items-center justify-center`,children:(0,u.jsx)(fn,{className:`w-5 h-5 text-amber-600`})}),(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h3`,{className:`text-lg font-semibold text-gray-900`,children:`Confirm Delete`}),(0,u.jsx)(`p`,{className:`text-sm text-gray-600`,children:`This action cannot be undone`})]})]}),(0,u.jsxs)(`p`,{className:`text-gray-700 mb-6`,children:[`Are you sure you want to delete `,(0,u.jsxs)(`span`,{className:`font-medium text-gray-900`,children:[`"`,W,`"`]}),`? This will permanently delete the entity and all its data.`]}),(0,u.jsxs)(`div`,{className:`flex gap-3 justify-end`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>H(null),className:`px-4 py-2 text-sm bg-white hover:bg-gray-50 text-gray-600 border border-gray-200 rounded-lg transition-colors`,children:`Cancel`}),(0,u.jsx)(`button`,{type:`button`,onClick:async()=>{let e=_e;H(null);try{await s($.deleteEntity(e),{awaitResponse:!0}),n?.(e)}catch{}},className:`px-4 py-2 text-sm bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors`,children:`Delete Entity`})]})]})]}):null,[_e,W,n,s]);return!j&&!U?(0,u.jsxs)(`div`,{className:`p-4 text-center text-gray-500 text-sm`,children:[(0,u.jsx)(kn,{className:`w-6 h-6 mb-2 mx-auto text-red-500`}),(0,u.jsx)(`div`,{children:`No root entity found`}),(0,u.jsxs)(`div`,{className:`text-xs text-gray-600 mt-1`,children:[`Entity ID: `,l]})]}):(0,u.jsxs)(`div`,{className:`h-full flex flex-col bg-white text-gray-900`,children:[(0,u.jsxs)(`div`,{className:`flex-1 overflow-y-auto overflow-x-visible p-2`,children:[(0,u.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,u.jsxs)(`div`,{className:`text-xs text-gray-500 flex items-center gap-1.5`,children:[(0,u.jsx)(xn,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:C})]}),(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[j&&S&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`button`,{ref:te,type:`button`,onClick:F,className:`px-2 py-1 text-xs bg-white hover:bg-gray-50 text-gray-700 border border-gray-200 rounded-lg transition-colors`,title:`Create a top-level entity`,children:`+ New`}),N&&(0,u.jsx)(os,{ref:P,position:N,options:ne,onSelect:e=>{ee(null),pe(null,e)}})]}),(0,u.jsxs)(`div`,{className:`relative`,ref:oe,children:[(0,u.jsxs)(`button`,{onClick:()=>{re(e=>!e),R(``)},className:`px-2 py-1 text-xs bg-white hover:bg-gray-50 text-gray-700 border border-gray-200 rounded-lg transition-colors flex items-center gap-1`,title:`Explorer filter settings`,children:[(0,u.jsx)(hn,{className:`w-3 h-3`}),(0,u.jsx)(`span`,{children:`Settings`})]}),L&&(0,u.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 w-56 max-w-[calc(100vw-1rem)] bg-white border border-gray-200 rounded-lg shadow-xl z-9999`,children:[(0,u.jsx)(`div`,{className:`p-2 border-b border-gray-200 text-xs font-medium text-gray-700`,children:`Filter entity types`}),(0,u.jsx)(`div`,{className:`p-2 border-b border-gray-200`,children:(0,u.jsx)(`input`,{type:`text`,value:ie,onChange:e=>R(e.target.value),placeholder:`Search types...`,className:`w-full px-2 py-1 text-xs bg-white text-gray-900 border border-gray-300 rounded-sm focus:outline-hidden focus:ring-1 focus:ring-blue-500 placeholder-gray-500`})}),(0,u.jsxs)(`div`,{className:`p-2 border-b border-gray-200 flex gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,className:`px-2 py-1 text-xs border border-gray-200 rounded-sm hover:bg-gray-50`,onClick:()=>ce([]),children:`Show all`}),(0,u.jsx)(`button`,{type:`button`,className:`px-2 py-1 text-xs border border-gray-200 rounded-sm hover:bg-gray-50`,onClick:()=>ce(O),children:`Reset default`})]}),(0,u.jsxs)(`div`,{className:`max-h-64 overflow-auto p-2 space-y-1`,children:[se.map(([e,t])=>{let n=A.includes(e);return(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-gray-700 cursor-pointer`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>{let t=A.includes(e)?A.filter(t=>t!==e):[...A,e];ce(t)}}),(0,u.jsx)(Ma,{entityTypeId:e,className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{className:`truncate`,children:t?.name||e})]},e)}),se.length===0&&(0,u.jsx)(`div`,{className:`text-xs text-gray-500 px-1 py-1`,children:`No matching entity types`})]})]})]})]})]}),j?(0,u.jsxs)(u.Fragment,{children:[M.ids.map(e=>(0,u.jsx)(cs,{entityId:e,parentId:void 0,selectedEntityId:ae,onSelect:ue,onDoubleClick:le,onPin:de,onDelete:B,onCreateChild:pe,expandedEntities:he,onToggleExpanded:ye,onEntityMove:V,onEntityAdd:fe,onRemoveChild:me,availableEntities:h,allowCreate:S,filterTypeIds:A,showDeleteAction:w,showCreateChildAction:T,groupByEntityType:E,revealEntityId:D||void 0,revealAncestors:G,depth:0},e)),M.ids.length===0&&!M.loading&&(0,u.jsx)(`div`,{className:`px-2 py-1 text-xs text-gray-500`,children:`No top-level entities`}),M.hasMore&&(0,u.jsx)(`button`,{type:`button`,onClick:M.loadMore,disabled:M.loading,className:`mt-1 w-full px-2 py-1 text-xs text-gray-500 hover:text-gray-900 hover:bg-gray-50 rounded-sm`,children:M.loading?`Loading…`:`Load more`})]}):(0,u.jsx)(cs,{entityId:l,parentId:void 0,selectedEntityId:ae,onSelect:ue,onDoubleClick:le,onPin:de,onDelete:B,onCreateChild:pe,expandedEntities:he,onToggleExpanded:ye,onEntityMove:V,onEntityAdd:fe,onRemoveChild:me,availableEntities:h,allowCreate:S,filterTypeIds:A,showDeleteAction:w,showCreateChildAction:T,groupByEntityType:E,revealEntityId:D||void 0,revealAncestors:G,depth:0})]}),be&&(0,f.createPortal)(be,document.body)]})}),us={open_tab_entity_ids:[],active_tab_entity_id:null,root_entity_id:null,sidebar_config:{}},ds=Object.values(Y);function fs(e){let t=Ar(e,`docName`);if(typeof t==`string`&&t.trim())return t;if(e?.entity_type_id===Y.VIEW){let t=Ar(e,`name`);if(typeof t==`string`&&t.trim())return t;if(typeof e.component==`string`&&e.component)return e.component}return Z(e)}function ps(e){if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=ds.find(e=>e===t);if(n)return n;let r=new Set;t.endsWith(`Entity`)?r.add(t):(r.add(`${t}Entity`),r.add(`${t.charAt(0).toUpperCase()}${t.slice(1)}Entity`));for(let e of r){let t=ds.find(t=>t.endsWith(`.${e}`));if(t)return t}return t.includes(`.`)?t:null}function ms(e){let t=new Set,n=[];return e.forEach(e=>{let r=ps(e);r&&!t.has(r)&&(t.add(r),n.push(r))}),n}function hs({entityId:e,sidebarConfig:t,rootEntityId:n,explorerTitle:r,uiHooks:i}){let[a,o]=Fa(us),s={...a.sidebar_config||{},...t||{}},l=n||a.root_entity_id||e||null,d=!!s.allow_create,f=(0,c.useMemo)(()=>ms(Array.isArray(s.filter_entity_types)?s.filter_entity_types:[]),[s.filter_entity_types]),p=(0,c.useMemo)(()=>Array.isArray(a.open_tab_entity_ids)?a.open_tab_entity_ids.filter(e=>typeof e==`string`):[],[a.open_tab_entity_ids]),m=typeof a.active_tab_entity_id==`string`?a.active_tab_entity_id:null,h=(0,c.useCallback)((e,t)=>{o({open_tab_entity_ids:e,active_tab_entity_id:t})},[o]),g=(0,c.useCallback)(e=>{let t=p.includes(e)?p:[...p,e];h(t,e)},[p,h]),_=(0,c.useCallback)(e=>{let t=p.indexOf(e),n=p.filter(t=>t!==e),r=m;m===e&&(r=n.length===0?null:n[Math.min(t,n.length-1)]),h(n,r)},[m,p,h]),v=(0,c.useCallback)(e=>{p.includes(e)&&_(e)},[_,p]);return(0,u.jsxs)(`div`,{className:`h-full w-full flex bg-gray-50 text-gray-900`,children:[(0,u.jsx)(`div`,{className:`w-80 min-w-[260px] max-w-[520px] border-r border-gray-200 bg-white flex flex-col`,children:(0,u.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto`,children:(0,u.jsx)(ls,{entityId:l,onEntityDelete:v,uiHooks:{...i,onEntitySelect:g,onEntityOpen:g},explorerConfig:{title:r||`Explorer`,allow_create:d,filter_entity_types:f,show_delete_action:s.show_delete_action,show_create_child_action:s.show_create_child_action,reveal_entity_id:m||void 0},className:`h-full w-full`})})}),(0,u.jsxs)(`div`,{className:`flex-1 min-w-0 flex flex-col bg-white`,children:[(0,u.jsx)(`div`,{className:`shrink-0 border-b border-gray-200 bg-gray-50/70`,children:p.length===0?(0,u.jsx)(`div`,{className:`px-4 py-2 text-sm text-gray-500`,children:`Select an entity from the explorer to open a tab.`}):(0,u.jsx)(`div`,{className:`flex overflow-x-auto`,children:p.map(e=>(0,u.jsx)(gs,{entityId:e,isActive:e===m,onSelect:()=>{h(p,e)},onClose:()=>_(e)},e))})}),(0,u.jsx)(`div`,{className:`flex-1 min-h-0`,children:m?(0,u.jsx)(ho,{entityId:m,className:`h-full w-full`},m):(0,u.jsx)(`div`,{className:`h-full flex items-center justify-center text-gray-500`,children:(0,u.jsxs)(`div`,{className:`text-center`,children:[(0,u.jsx)(wn,{className:`w-10 h-10 mx-auto mb-3 text-gray-300`}),(0,u.jsx)(`div`,{className:`text-sm`,children:`No entity open`})]})})})]})]})}var gs=({entityId:e,isActive:t,onSelect:n,onClose:r})=>{let i=X(e),a=fs(i||{});return(0,u.jsxs)(`button`,{type:`button`,onClick:n,className:`group flex items-center gap-2 px-3 py-2 border-r border-gray-200 text-sm max-w-72 ${t?`bg-white text-gray-900`:`bg-gray-50 text-gray-600 hover:bg-gray-100`}`,title:a,children:[(0,u.jsx)(Ma,{entityTypeId:i?.entity_type_id,className:`w-3.5 h-3.5 shrink-0`}),(0,u.jsx)(`span`,{className:`truncate`,children:a}),(0,u.jsx)(`span`,{role:`button`,className:`opacity-60 hover:opacity-100 p-0.5 rounded-sm hover:bg-gray-200`,onClick:e=>{e.stopPropagation(),r()},children:(0,u.jsx)(On,{className:`w-3.5 h-3.5`})})]})},_s=na(`entity_ide`,hs);function vs(){let e=new Map,t=new Map,n=[],r={register(n){if(!ra(n))throw Error(`ViewRegistry.register takes a component declared with defineView`);let r=n.viewName;if(e.has(r))throw Error(`ViewRegistry: a view named "${r}" is already registered`);for(let e of n.defaultFor){let n=t.get(e);if(n)throw Error(`ViewRegistry: "${r}" and "${n}" both claim defaultFor ${e}`)}e.set(r,n);for(let e of n.defaultFor)t.set(e,r)},use(e){for(let t of Object.values(e.exports))ra(t)&&(r.register(t),t.entry&&n.push({app:e.app,viewKey:t.viewName}))},get(t){return e.get(t)??null},defaultViewFor(e){return t.get(e)??null},entryPoints(){return[...n]},keys(){return Array.from(e.keys())}};return r}var ys={app:`graphcore`,exports:{EntityAttributesView:Io,CompositeHBox:Wo,CompositeVBox:Go,CompositeTabs:Jo,ListView:Xo,EntityExplorer:ls,EntityIDE:_s,GroupView:ca,ViewGallery:Ha}};exports.ADMIN_ROUTE=da,exports.AccessPanel=Wa,exports.AdminPanel=ga,exports.AgentMirror=vi,exports.AppRoutes=xo,exports.AuthPage=Ai,exports.BaseEntity=Qa,exports.CompositeHBox=Wo,exports.CompositeTabs=Jo,exports.CompositeVBox=Go,exports.ENTITY_ROUTE=ei,exports.EntityAttributesView=Io,exports.EntityExplorer=ls,exports.EntityIDE=_s,exports.EntityLinkRedirect=_o,exports.EntityPicker=aa,exports.EntityRoute=go,exports.EntityView=ho,exports.GraphCoreApp=So,exports.GraphCoreProvider=Ci,exports.GraphCoreRouter=jo,exports.GroupView=ca,exports.INVITE_ROUTE=Ti,exports.InviteRoute=ki,exports.ListView=Xo,exports.StrategyError=ae,exports.StrategyRequests=$,exports.TopBar=ja,exports.ViewGallery=Ha,exports.allOf=Xt,exports.anyOf=Zt,exports.baseViews=ys,exports.collectPages=Ja,exports.containsAny=Yt,exports.containsValue=Jt,exports.createViewRegistry=vs,exports.definePage=Ga,exports.defineView=na,exports.entityGraph=Sr,exports.entityIdFromParams=ii,exports.entityPath=ri,exports.equal=Kt,exports.findEntityId=ai,exports.getAttr=Ar,exports.getAttributes=kr,exports.getBasePath=b,exports.getDisplayName=Z,exports.getFields=jr,exports.inValues=qt,exports.inviteUrl=Ei,exports.onResync=le,exports.pageCollisions=Eo,exports.typeShortName=Mr,exports.useAccess=ua,exports.useAuth=Pr,exports.useBridgeStatus=R,exports.useChildren=Dr,exports.useCreateView=Ia,exports.useDeploymentEntityId=Lr,exports.useEntities=Er,exports.useEntity=X,exports.useEntityQuery=Li,exports.useGraphCoreBridge=Cr,exports.useIsDeploymentAdmin=Ea,exports.useOffersRegistration=wi,exports.usePendingInvite=Oi,exports.useRecursiveChildren=Or,exports.useStrategyRequest=wr,exports.useViewRegistry=Hr,exports.useViewState=Fa,exports.useWebSocketConsumer=Ni,exports.webPath=x;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=s(c,1);c=s(c);let u=require("react/jsx-runtime"),d=require("react-router-dom"),f=require("react-dom");var p=null,m=null,h=null,g=``;function _(e,t,n){p=e,m=t,h=n??null}function v(e){let t=(e??``).trim().replace(/^\/+|\/+$/g,``);return t?`/${t}`:``}function y(e){g=v(e)}function b(){return g}function x(e){return e===`/`?g||`/`:`${g}${e}`}function S(){if(!p)throw Error(`GraphCoreProvider is missing required apiUrl config.`);return p}function C(){if(!m)throw Error(`GraphCoreProvider is missing required wsUrl config.`);return m}function w(){return h!==null}var T=(0,c.createContext)(null),E=T.Provider,D=()=>(0,c.useContext)(T),O=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},k=(e=>e?O(e):O),A=100,j=new Map;function M(e){j.delete(e.key),j.set(e.key,e),j.size>A&&j.delete(j.keys().next().value)}function N(e){return j.get(e)}function ee(){j.clear()}function te(e,t,n){let r=(0,c.useRef)(void 0);return(0,c.useSyncExternalStore)(e.subscribe,()=>{let i=t(e.getState());return n&&r.current!==void 0&&n(r.current,i)?r.current:(r.current=i,i)},()=>t(e.getInitialState()))}var P=e=>e?Array.isArray(e)?e.reduce((e,t)=>(t?.entity_id&&(e[t.entity_id]=t),e),{}):Object.entries(e).reduce((e,[t,n])=>((n?.entity_id||t)&&(e[n.entity_id||t]=n),e),{}):{},ne=(e,t)=>!e?.deleted&&!e?.forbidden&&!t?.forbidden&&typeof e?.version==`number`&&typeof t?.version==`number`&&e.version<t.version,re=(e,t={})=>{let n=e?.entity_type_id,r=Array.isArray(t.types)?t.types.filter(Boolean):[],i=Array.isArray(t.excludeTypes)?t.excludeTypes.filter(Boolean):[];return!(r.length>0&&!r.includes(n)||i.length>0&&i.includes(n))},ie=(e,t)=>{if(!t)return[];let n=e.entitiesById[t];return Array.isArray(n?.children_ids)?n.children_ids.filter(Boolean):[]},ae=(e,t,n={})=>{if(!t||n.enabled===!1)return null;let r=(i,a=new Set)=>{if(a.has(i))return null;a.add(i);let o=e.entitiesById[i];if(!o)return null;let s=ie(e,i).reduce((e,t)=>{let n=r(t,new Set(a));return n&&(e[t]=n),e},{});return re(o,n)||Object.keys(s).length>0||n.includeRoot&&i===t?{entity:o,children:s}:null};return r(t)},F=k(()=>({entitiesById:{},entityIds:[],requestedEntityIds:new Set,notFoundEntityIds:new Set,idsByKey:{},requestedKeys:new Set,notFoundKeys:new Set})),I=(e,t)=>te(F,e,t),L={getEntityIds(){return F.getState().entityIds},readEntity(e){return e?F.getState().entitiesById[e]??null:null},readEntities(e){let t=F.getState().entitiesById;return(e||[]).map(e=>e?t[e]??null:null)},readChildren(e,t={}){if(!e||t.enabled===!1)return[];let n=F.getState();return ie(n,e).map(e=>n.entitiesById[e]??null).filter(e=>!!e&&!e.forbidden).filter(e=>re(e,t))},readRecursiveChildren(e,t={}){return ae(F.getState(),e,t)},mergeEntities(e){let t=P(e),n=new Set(F.getState().entityIds);return F.setState(e=>{let r={...e.entitiesById},i=new Set(e.requestedEntityIds),a=new Set(e.notFoundEntityIds);return Object.entries(t).forEach(([e,t])=>{i.delete(e),a.delete(e),!ne(t,r[e])&&(t?.deleted===!0?(delete r[e],n.delete(e)):(r[e]=t,n.add(e)))}),{entitiesById:r,entityIds:[...n],requestedEntityIds:i,notFoundEntityIds:a}}),F.getState().entityIds},removeEntity(e){e&&F.setState(t=>{if(!t.entitiesById[e])return t;let n={...t.entitiesById};delete n[e];let r=new Set(t.requestedEntityIds),i=new Set(t.notFoundEntityIds);return r.delete(e),i.delete(e),{entitiesById:n,entityIds:t.entityIds.filter(t=>t!==e),requestedEntityIds:r,notFoundEntityIds:i}})},clearEntities(){ee(),F.setState({entitiesById:{},entityIds:[],requestedEntityIds:new Set,notFoundEntityIds:new Set,idsByKey:{},requestedKeys:new Set,notFoundKeys:new Set})},markRequested(e){e&&F.setState(t=>{let n=new Set(t.requestedEntityIds),r=new Set(t.notFoundEntityIds);return n.add(e),r.delete(e),{requestedEntityIds:n,notFoundEntityIds:r}})},clearRequestedEntity(e){e&&F.setState(t=>{if(!t.requestedEntityIds.has(e))return t;let n=new Set(t.requestedEntityIds);return n.delete(e),{requestedEntityIds:n}})},clearRequestedEntities(){F.setState({requestedEntityIds:new Set,requestedKeys:new Set})},isRequested(e){return F.getState().requestedEntityIds.has(e)},markNotFound(e){e&&F.setState(t=>{let n=new Set(t.requestedEntityIds),r=new Set(t.notFoundEntityIds);return n.delete(e),r.add(e),{requestedEntityIds:n,notFoundEntityIds:r}})},isNotFound(e){return F.getState().notFoundEntityIds.has(e)},clearEntityFlags(e){e?F.setState(t=>{let n=new Set(t.requestedEntityIds),r=new Set(t.notFoundEntityIds);return n.delete(e),r.delete(e),{requestedEntityIds:n,notFoundEntityIds:r}}):F.setState({requestedEntityIds:new Set,notFoundEntityIds:new Set})},readIdForKey(e){return F.getState().idsByKey[e]??null},resolveKey(e,t){F.setState(n=>{let r=new Set(n.requestedKeys);return r.delete(e),{idsByKey:{...n.idsByKey,[e]:t},requestedKeys:r}})},markKeyRequested(e){F.setState(t=>({requestedKeys:new Set(t.requestedKeys).add(e)}))},isKeyRequested(e){return F.getState().requestedKeys.has(e)},markKeyNotFound(e){F.setState(t=>{let n=new Set(t.requestedKeys);return n.delete(e),{requestedKeys:n,notFoundKeys:new Set(t.notFoundKeys).add(e)}})},isKeyNotFound(e){return F.getState().notFoundKeys.has(e)}},oe=e=>e;function R(e,t=oe){let n=l.default.useSyncExternalStore(e.subscribe,l.default.useCallback(()=>t(e.getState()),[e,t]),l.default.useCallback(()=>t(e.getInitialState()),[e,t]));return l.default.useDebugValue(n),n}var se=k(()=>`idle`),ce=e=>{se.setState(e)},z=()=>R(se,e=>e),le=class extends Error{constructor(e,t={}){super(e),this.name=`StrategyError`,this.code=t.code??void 0,this.details=t.details??{},this.strategyRequestId=t.strategyRequestId??void 0}},ue=new Set;function de(e){return ue.add(e),()=>{ue.delete(e)}}function fe(e){ue.forEach(t=>t(e))}var pe=new Set;function me(e){return pe.add(e),()=>{pe.delete(e)}}function he(e){pe.forEach(t=>t(e))}var ge=()=>({isAuthenticated:!1,token:null,principalEntityId:null,username:null,isLoading:!1,error:null}),_e=k(()=>({...ge(),isLoading:!0})),B=e=>{_e.setState(e)},ve=()=>R(_e),V=class extends Error{};V.prototype.name=`InvalidTokenError`;function ye(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function be(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return ye(t)}catch{return atob(t)}}function xe(e,t){if(typeof e!=`string`)throw new V(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new V(`Invalid token specified: missing part #${n+1}`);let i;try{i=be(r)}catch(e){throw new V(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new V(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var Se={debug:()=>void 0,info:()=>void 0,warn:()=>void 0,error:()=>void 0},H,U,Ce=(e=>(e[e.NONE=0]=`NONE`,e[e.ERROR=1]=`ERROR`,e[e.WARN=2]=`WARN`,e[e.INFO=3]=`INFO`,e[e.DEBUG=4]=`DEBUG`,e))(Ce||{});(e=>{function t(){H=3,U=Se}e.reset=t;function n(e){if(!(0<=e&&e<=4))throw Error(`Invalid log level`);H=e}e.setLevel=n;function r(e){U=e}e.setLogger=r})(Ce||={});var W=class e{constructor(e){this._name=e}debug(...t){H>=4&&U.debug(e._format(this._name,this._method),...t)}info(...t){H>=3&&U.info(e._format(this._name,this._method),...t)}warn(...t){H>=2&&U.warn(e._format(this._name,this._method),...t)}error(...t){H>=1&&U.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){let t=Object.create(this);return t._method=e,t.debug(`begin`),t}static createStatic(t,n){let r=new e(`${t}.${n}`);return r.debug(`begin`),r}static _format(e,t){let n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){H>=4&&U.debug(e._format(t),...n)}static info(t,...n){H>=3&&U.info(e._format(t),...n)}static warn(t,...n){H>=2&&U.warn(e._format(t),...n)}static error(t,...n){H>=1&&U.error(e._format(t),...n)}};Ce.reset();var we=class{static decode(e){try{return xe(e)}catch(e){throw W.error(`JwtUtils.decode`,e),e}}static async generateSignedJwt(e,t,n){let r=`${G.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e)))}.${G.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:`ECDSA`,hash:{name:`SHA-256`}},n,new TextEncoder().encode(r));return`${r}.${G.encodeBase64Url(new Uint8Array(i))}`}static async generateSignedJwtWithHmac(e,t,n){let r=`${G.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e)))}.${G.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign(`HMAC`,n,new TextEncoder().encode(r));return`${r}.${G.encodeBase64Url(new Uint8Array(i))}`}},Te=`10000000-1000-4000-8000-100000000000`,Ee=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join(``)),De=class e{static _randomWord(){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return Te.replace(/[018]/g,t=>(+t^e._randomWord()&15>>t/4).toString(16)).replace(/-/g,``)}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw Error(`Crypto.subtle is available only in secure contexts (HTTPS).`);try{let t=new TextEncoder().encode(e);return Ee(await crypto.subtle.digest(`SHA-256`,t)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}catch(e){throw W.error(`CryptoUtils.generateCodeChallenge`,e),e}}static generateBasicAuth(e,t){return Ee(new TextEncoder().encode([e,t].join(`:`)))}static async hash(e,t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case`RSA`:n={e:t.e,kty:t.kty,n:t.n};break;case`EC`:n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case`OKP`:n={crv:t.crv,kty:t.kty,x:t.x};break;case`oct`:n={crv:t.k,kty:t.kty};break;default:throw Error(`Unknown jwk type`)}let r=await e.hash(`SHA-256`,JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:i,nonce:a}){let o,s,c={jti:window.crypto.randomUUID(),htm:r??`GET`,htu:t,iat:Math.floor(Date.now()/1e3)};n&&(o=await e.hash(`SHA-256`,n),s=e.encodeBase64Url(o),c.ath=s),a&&(c.nonce=a);try{let e=await crypto.subtle.exportKey(`jwk`,i.publicKey),t={alg:`ES256`,typ:`dpop+jwt`,jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await we.generateSignedJwt(t,c,i.privateKey)}catch(e){throw e instanceof TypeError?Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{let n=await crypto.subtle.exportKey(`jwk`,t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(e){throw e instanceof TypeError?Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!1,[`sign`,`verify`])}static async generateClientAssertionJwt(t,n,r,i=`HS256`){let a=Math.floor(Date.now()/1e3),o={alg:i,typ:`JWT`},s={iss:t,sub:t,aud:r,jti:e.generateUUIDv4(),exp:a+300,iat:a},c={HS256:`SHA-256`,HS384:`SHA-384`,HS512:`SHA-512`}[i];if(!c)throw Error(`Unsupported algorithm: ${i}. Supported algorithms are: HS256, HS384, HS512`);let l=new TextEncoder,u=await crypto.subtle.importKey(`raw`,l.encode(n),{name:`HMAC`,hash:c},!1,[`sign`]);return await we.generateSignedJwtWithHmac(o,s,u)}};De.encodeBase64Url=e=>Ee(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`);var G=De,Oe=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new W(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){let t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug(`raise:`,...e);for(let t of this._callbacks)await t(...e)}},ke=class{static center({...e}){return e.width??=[800,720,600,480].find(e=>e<=window.outerWidth/1.618)??360,e.left??=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2)),e.height!=null&&(e.top??=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2))),e}static serialize(e){return Object.entries(e).filter(([,e])=>e!=null).map(([e,t])=>`${e}=${typeof t==`boolean`?t?`yes`:`no`:t}`).join(`,`)}},Ae=class e extends Oe{constructor(){super(...arguments),this._logger=new W(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{let t=this._expiration-e.getEpochTime();this._logger.debug(`timer completes in`,t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){let n=this._logger.create(`init`);t=Math.max(Math.floor(t),1);let r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle){n.debug(`skipping since already initialized for expiration at`,this.expiration);return}this.cancel(),n.debug(`using duration`,t),this._expiration=r;let i=Math.min(t,5);this._timerHandle=setInterval(this._callback,i*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create(`cancel`),this._timerHandle&&=(clearInterval(this._timerHandle),null)}},je=class{static readParams(e,t=`query`){if(!e)throw TypeError(`Invalid URL`);let n=new URL(e,`http://127.0.0.1`)[t===`fragment`?`hash`:`search`];return new URLSearchParams(n.slice(1))}},Me=`;`,Ne=class extends Error{constructor(e,t){if(super(e.error_description||e.error||``),this.form=t,this.name=`ErrorResponse`,!e.error)throw W.error(`ErrorResponse`,`No error passed`),Error(`No error passed`);this.error=e.error,this.error_description=e.error_description??null,this.error_uri=e.error_uri??null,this.state=e.userState,this.session_state=e.session_state??null,this.url_state=e.url_state}},Pe=class extends Error{constructor(e){super(e),this.name=`ErrorTimeout`}},Fe=class{constructor(e){this._logger=new W(`AccessTokenEvents`),this._expiringTimer=new Ae(`Access token expiring`),this._expiredTimer=new Ae(`Access token expired`),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){let t=this._logger.create(`load`);if(e.access_token&&e.expires_in!==void 0){let n=e.expires_in;if(t.debug(`access token present, remaining duration:`,n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug(`registering expiring timer, raising in`,e,`seconds`),this._expiringTimer.init(e)}else t.debug(`canceling existing expiring timer because we're past expiration.`),this._expiringTimer.cancel();let r=n+1;t.debug(`registering expired timer, raising in`,r,`seconds`),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug(`unload: canceling existing access token timers`),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},Ie=class{constructor(e,t,n,r,i){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=i,this._logger=new W(`CheckSessionIFrame`),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data===`error`?(this._logger.error(`error message from check session op iframe`),this._stopOnError&&this.stop()):e.data===`changed`?(this._logger.debug(`changed message from check session op iframe`),this.stop(),this._callback()):this._logger.debug(e.data+` message from check session op iframe`))};let a=new URL(n);this._frame_origin=a.origin,this._frame=window.document.createElement(`iframe`),this._frame.style.visibility=`hidden`,this._frame.style.position=`fixed`,this._frame.style.left=`-1000px`,this._frame.style.top=`0`,this._frame.width=`0`,this._frame.height=`0`,this._frame.src=a.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener(`message`,this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create(`start`),this.stop(),this._session_state=e;let t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+` `+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._logger.create(`stop`),this._session_state=null,this._timer&&=(clearInterval(this._timer),null)}},Le=class{constructor(){this._logger=new W(`InMemoryWebStorage`),this._data={}}clear(){this._logger.create(`clear`),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},Re=class extends Error{constructor(e,t){super(t),this.name=`ErrorDPoPNonce`,this.nonce=e}},ze=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new W(`JsonService`),this._contentTypes=[],this._contentTypes.push(...e,`application/json`),t&&this._contentTypes.push(`application/jwt`)}async fetchWithTimeout(e,t={}){let{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);let i=new AbortController,a=setTimeout(()=>i.abort(),n*1e3);try{return await fetch(e,{...t,signal:i.signal})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?new Pe(`Network timed out`):e}finally{clearTimeout(a)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){let i=this._logger.create(`getJson`),a={Accept:this._contentTypes.join(`, `)};t&&(i.debug(`token passed, setting Authorization header`),a.Authorization=`Bearer `+t),this._appendExtraHeaders(a);let o;try{i.debug(`url:`,e),o=await this.fetchWithTimeout(e,{method:`GET`,headers:a,timeoutInSeconds:r,credentials:n})}catch(e){throw i.error(`Network Error`),e}i.debug(`HTTP response received, status`,o.status);let s=o.headers.get(`Content-Type`);if(s&&!this._contentTypes.find(e=>s.startsWith(e))&&i.throw(Error(`Invalid response Content-Type: ${s??`undefined`}, from URL: ${e}`)),o.ok&&this._jwtHandler&&s?.startsWith(`application/jwt`))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){throw i.error(`Error parsing JSON response`,e),o.ok?e:Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw i.error(`Error from server:`,c),c.error?new Ne(c):Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`);return c}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:i,extraHeaders:a}){let o=this._logger.create(`postForm`),s={Accept:this._contentTypes.join(`, `),"Content-Type":`application/x-www-form-urlencoded`,...a};n!==void 0&&(s.Authorization=`Basic `+n),this._appendExtraHeaders(s);let c;try{o.debug(`url:`,e),c=await this.fetchWithTimeout(e,{method:`POST`,headers:s,body:t,timeoutInSeconds:r,credentials:i})}catch(e){throw o.error(`Network error`),e}o.debug(`HTTP response received, status`,c.status);let l=c.headers.get(`Content-Type`);if(l&&!this._contentTypes.find(e=>l.startsWith(e)))throw Error(`Invalid response Content-Type: ${l??`undefined`}, from URL: ${e}`);let u=await c.text(),d={};if(u)try{d=JSON.parse(u)}catch(e){throw o.error(`Error parsing JSON response`,e),c.ok?e:Error(`${c.statusText} (${c.status})`)}if(!c.ok)throw o.error(`Error from server:`,d),c.headers.has(`dpop-nonce`)?new Re(c.headers.get(`dpop-nonce`),`${JSON.stringify(d)}`):d.error?new Ne(d,t):Error(`${c.statusText} (${c.status}): ${JSON.stringify(d)}`);return d}_appendExtraHeaders(e){let t=this._logger.create(`appendExtraHeaders`),n=Object.keys(this._extraHeaders),r=[`accept`,`content-type`],i=[`authorization`];n.length!==0&&n.forEach(n=>{if(r.includes(n.toLocaleLowerCase())){t.warn(`Protected header could not be set`,n,r);return}if(i.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n)){t.warn(`Header could not be overridden`,n,i);return}let a=typeof this._extraHeaders[n]==`function`?this._extraHeaders[n]():this._extraHeaders[n];a&&a!==``&&(e[n]=a)})}},Be=class{constructor(e){this._settings=e,this._logger=new W(`MetadataService`),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new ze([`application/jwk-set+json`],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug(`using signingKeys from settings`),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug(`using metadata from settings`),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug(`using fetchRequestCredentials from settings`),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){let e=this._logger.create(`getMetadata`);if(this._metadata)return e.debug(`using cached values`),this._metadata;if(!this._metadataUrl)throw e.throw(Error(`No authority or metadataUrl configured on settings`)),null;e.debug(`getting metadata from`,this._metadataUrl);let t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug(`merging remote JSON with seed metadata`),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty(`issuer`)}getAuthorizationEndpoint(){return this._getMetadataProperty(`authorization_endpoint`)}getUserInfoEndpoint(){return this._getMetadataProperty(`userinfo_endpoint`)}getTokenEndpoint(e=!0){return this._getMetadataProperty(`token_endpoint`,e)}getCheckSessionIframe(){return this._getMetadataProperty(`check_session_iframe`,!0)}getEndSessionEndpoint(){return this._getMetadataProperty(`end_session_endpoint`,!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty(`revocation_endpoint`,e)}getKeysEndpoint(e=!0){return this._getMetadataProperty(`jwks_uri`,e)}async _getMetadataProperty(e,t=!1){let n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug(`resolved`),r[e]===void 0){if(t===!0){n.warn(`Metadata does not contain optional property`);return}n.throw(Error(`Metadata does not contain property `+e))}return r[e]}async getSigningKeys(){let e=this._logger.create(`getSigningKeys`);if(this._signingKeys)return e.debug(`returning signingKeys from cache`),this._signingKeys;let t=await this.getKeysEndpoint(!1);e.debug(`got jwks_uri`,t);let n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug(`got key set`,n),!Array.isArray(n.keys))throw e.throw(Error(`Missing keys on keyset`)),null;return this._signingKeys=n.keys,this._signingKeys}},Ve=class{constructor({prefix:e=`oidc.`,store:t=localStorage}={}){this._logger=new W(`WebStorageStateStore`),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create(`getAllKeys`);let e=await this._store.length,t=[];for(let n=0;n<e;n++){let e=await this._store.key(n);e&&e.indexOf(this._prefix)===0&&t.push(e.substr(this._prefix.length))}return t}},He=`code`,Ue=`openid`,We=`client_secret_post`,Ge=900,Ke=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:i,client_id:a,client_secret:o,response_type:s=He,scope:c=Ue,redirect_uri:l,post_logout_redirect_uri:u,client_authentication:d=We,token_endpoint_auth_signing_alg:f=`HS256`,prompt:p,display:m,max_age:h,ui_locales:g,acr_values:_,resource:v,response_mode:y,filterProtocolClaims:b=!0,loadUserInfo:x=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:C=Ge,mergeClaimsStrategy:w={array:`replace`},disablePKCE:T=!1,stateStore:E,revokeTokenAdditionalContentTypes:D,fetchRequestCredentials:O,refreshTokenAllowedScope:k,extraQueryParams:A={},extraTokenParams:j={},extraHeaders:M={},dpop:N,omitScopeWhenRequesting:ee=!1}){if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith(`/`)||(this.metadataUrl+=`/`),this.metadataUrl+=`.well-known/openid-configuration`)),this.metadata=n,this.metadataSeed=i,this.signingKeys=r,this.client_id=a,this.client_secret=o,this.response_type=s,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=u,this.client_authentication=d,this.token_endpoint_auth_signing_alg=f,this.prompt=p,this.display=m,this.max_age=h,this.ui_locales=g,this.acr_values=_,this.resource=v,this.response_mode=y,this.filterProtocolClaims=b??!0,this.loadUserInfo=!!x,this.staleStateAgeInSeconds=C,this.mergeClaimsStrategy=w,this.omitScopeWhenRequesting=ee,this.disablePKCE=!!T,this.revokeTokenAdditionalContentTypes=D,this.fetchRequestCredentials=O||`same-origin`,this.requestTimeoutInSeconds=S,E)this.stateStore=E;else{let e=typeof window<`u`?window.localStorage:new Le;this.stateStore=new Ve({store:e})}if(this.refreshTokenAllowedScope=k,this.extraQueryParams=A,this.extraTokenParams=j,this.extraHeaders=M,this.dpop=N,this.dpop&&!this.dpop?.store)throw Error(`A DPoPStore is required when dpop is enabled`)}},qe=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new W(`UserInfoService`),this._getClaimsFromJwt=async e=>{let t=this._logger.create(`_getClaimsFromJwt`);try{let n=we.decode(e);return t.debug(`JWT decoding successful`),n}catch(e){throw t.error(`Error parsing JWT response`),e}},this._jsonService=new ze(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){let t=this._logger.create(`getClaims`);e||this._logger.throw(Error(`No token passed`));let n=await this._metadataService.getUserInfoEndpoint();t.debug(`got userinfo url`,n);let r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug(`got claims`,r),r}},Je=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new W(`TokenClient`),this._jsonService=new ze(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e=`authorization_code`,redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...a}){let o=this._logger.create(`exchangeCode`);n||o.throw(Error(`A client_id is required`)),t||o.throw(Error(`A redirect_uri is required`)),a.code||o.throw(Error(`A code is required`));let s=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[e,t]of Object.entries(a))t!=null&&s.set(e,t);if((this._settings.client_authentication===`client_secret_basic`||this._settings.client_authentication===`client_secret_jwt`)&&r==null)throw o.throw(Error(`A client_secret is required`)),null;let c,l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case`client_secret_basic`:c=G.generateBasicAuth(n,r);break;case`client_secret_post`:s.append(`client_id`,n),r&&s.append(`client_secret`,r);break;case`client_secret_jwt`:{let e=await G.generateClientAssertionJwt(n,r,l,this._settings.token_endpoint_auth_signing_alg);s.append(`client_id`,n),s.append(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),s.append(`client_assertion`,e);break}}o.debug(`got token endpoint`);let u=await this._jsonService.postForm(l,{body:s,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug(`got response`),u}async exchangeCredentials({grant_type:e=`password`,client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...i}){let a=this._logger.create(`exchangeCredentials`);t||a.throw(Error(`A client_id is required`));let o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set(`scope`,r);for(let[e,t]of Object.entries(i))t!=null&&o.set(e,t);if((this._settings.client_authentication===`client_secret_basic`||this._settings.client_authentication===`client_secret_jwt`)&&n==null)throw a.throw(Error(`A client_secret is required`)),null;let s,c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case`client_secret_basic`:s=G.generateBasicAuth(t,n);break;case`client_secret_post`:o.append(`client_id`,t),n&&o.append(`client_secret`,n);break;case`client_secret_jwt`:{let e=await G.generateClientAssertionJwt(t,n,c,this._settings.token_endpoint_auth_signing_alg);o.append(`client_id`,t),o.append(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),o.append(`client_assertion`,e);break}}a.debug(`got token endpoint`);let l=await this._jsonService.postForm(c,{body:o,basicAuth:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return a.debug(`got response`),l}async exchangeRefreshToken({grant_type:e=`refresh_token`,client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:i,...a}){let o=this._logger.create(`exchangeRefreshToken`);t||o.throw(Error(`A client_id is required`)),a.refresh_token||o.throw(Error(`A refresh_token is required`));let s=new URLSearchParams({grant_type:e});for(let[e,t]of Object.entries(a))Array.isArray(t)?t.forEach(t=>s.append(e,t)):t!=null&&s.set(e,t);if((this._settings.client_authentication===`client_secret_basic`||this._settings.client_authentication===`client_secret_jwt`)&&n==null)throw o.throw(Error(`A client_secret is required`)),null;let c,l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case`client_secret_basic`:c=G.generateBasicAuth(t,n);break;case`client_secret_post`:s.append(`client_id`,t),n&&s.append(`client_secret`,n);break;case`client_secret_jwt`:{let e=await G.generateClientAssertionJwt(t,n,l,this._settings.token_endpoint_auth_signing_alg);s.append(`client_id`,t),s.append(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),s.append(`client_assertion`,e);break}}o.debug(`got token endpoint`);let u=await this._jsonService.postForm(l,{body:s,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug(`got response`),u}async revoke(e){let t=this._logger.create(`revoke`);e.token||t.throw(Error(`A token is required`));let n=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${e.token_type_hint??`default token type`}`);let r=new URLSearchParams;for(let[t,n]of Object.entries(e))n!=null&&r.set(t,n);r.set(`client_id`,this._settings.client_id),this._settings.client_secret&&r.set(`client_secret`,this._settings.client_secret),await this._jsonService.postForm(n,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),t.debug(`got response`)}},Ye=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new W(`ResponseValidator`),this._userInfoService=new qe(this._settings,this._metadataService),this._tokenClient=new Je(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){let r=this._logger.create(`validateSigninResponse`);this._processSigninState(e,t),r.debug(`state processed`),await this._processCode(e,t,n),r.debug(`code processed`),e.isOpenId&&this._validateIdTokenAttributes(e,``,t.nonce),r.debug(`tokens validated`),await this._processClaims(e,t?.skipUserInfo,e.isOpenId),r.debug(`claims processed`)}async validateCredentialsResponse(e,t){let n=this._logger.create(`validateCredentialsResponse`),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),n.debug(`tokens validated`),await this._processClaims(e,t,r),n.debug(`claims processed`)}async validateRefreshResponse(e,t){let n=this._logger.create(`validateRefreshResponse`);e.userState=t.data,e.session_state??=t.session_state,e.scope??=t.scope,e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug(`ID Token validated`)),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);let r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug(`claims processed`)}validateSignoutResponse(e,t){let n=this._logger.create(`validateSignoutResponse`);if(t.id!==e.state&&n.throw(Error(`State does not match`)),n.debug(`state validated`),e.userState=t.data,e.error)throw n.warn(`Response was error`,e.error),new Ne(e)}_processSigninState(e,t){let n=this._logger.create(`_processSigninState`);if(t.id!==e.state&&n.throw(Error(`State does not match`)),t.client_id||n.throw(Error(`No client_id on state`)),t.authority||n.throw(Error(`No authority on state`)),this._settings.authority!==t.authority&&n.throw(Error(`authority mismatch on settings vs. signin state`)),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(Error(`client_id mismatch on settings vs. signin state`)),n.debug(`state validated`),e.userState=t.data,e.url_state=t.url_state,e.scope??=t.scope,e.error)throw n.warn(`Response was error`,e.error),new Ne(e);t.code_verifier&&!e.code&&n.throw(Error(`Expected code in response`))}async _processClaims(e,t=!1,n=!0){let r=this._logger.create(`_processClaims`);if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){r.debug(`not loading user info`);return}r.debug(`loading user info`);let i=await this._userInfoService.getClaims(e.access_token);r.debug(`user info claims received from user info endpoint`),n&&i.sub!==e.profile.sub&&r.throw(Error(`subject from UserInfo response does not match subject in ID Token`)),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),r.debug(`user info claims received, updated profile:`,e.profile)}async _processCode(e,t,n){let r=this._logger.create(`_processCode`);if(e.code){r.debug(`Validating code`);let i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,i)}else r.debug(`No code to process`)}_validateIdTokenAttributes(e,t,n){let r=this._logger.create(`_validateIdTokenAttributes`);r.debug(`decoding ID Token JWT`);let i=we.decode(e.id_token??``);if(i.sub||r.throw(Error(`ID Token is missing a subject claim`)),n&&i.nonce!==n&&r.throw(Error(`nonce in id_token does not match nonce in client storage`)),t){let e=we.decode(t);i.sub!==e.sub&&r.throw(Error(`sub in id_token does not match current sub`)),i.auth_time&&i.auth_time!==e.auth_time&&r.throw(Error(`auth_time in id_token does not match original auth_time`)),i.azp&&i.azp!==e.azp&&r.throw(Error(`azp in id_token does not match original azp`)),!i.azp&&e.azp&&r.throw(Error(`azp not in id_token, but present in original id_token`))}e.profile=i}},Xe=class e{constructor(e){this.id=e.id||G.generateUUIDv4(),this.data=e.data,this.created=e.created&&e.created>0?e.created:Ae.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new W(`State`).create(`toStorageString`),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return W.createStatic(`State`,`fromStorageString`),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){let r=W.createStatic(`State`,`clearStaleState`),i=Ae.getEpochTime()-n,a=await t.getAllKeys();r.debug(`got keys`,a);for(let n=0;n<a.length;n++){let o=a[n],s=await t.get(o),c=!1;if(s)try{let t=await e.fromStorageString(s);r.debug(`got item from key:`,o,t.created),t.created<=i&&(c=!0)}catch(e){r.error(`Error parsing state for key:`,o,e),c=!0}else r.debug(`no item in storage for key:`,o),c=!0;c&&(r.debug(`removed item for key:`,o),t.remove(o))}}},Ze=class e extends Xe{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo,this.nonce=e.nonce}static async create(t){let n=t.code_verifier===!0?G.generateCodeVerifier():t.code_verifier||void 0,r=n?await G.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new W(`SigninState`).create(`toStorageString`),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(t){W.createStatic(`SigninState`,`fromStorageString`);let n=JSON.parse(t);return e.create(n)}},Qe=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:i,response_type:a,scope:o,state_data:s,response_mode:c,request_type:l,client_secret:u,nonce:d,url_state:f,resource:p,skipUserInfo:m,extraQueryParams:h,extraTokenParams:g,disablePKCE:_,dpopJkt:v,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error(`create: No url passed`),Error(`url`);if(!r)throw this._logger.error(`create: No client_id passed`),Error(`client_id`);if(!i)throw this._logger.error(`create: No redirect_uri passed`),Error(`redirect_uri`);if(!a)throw this._logger.error(`create: No response_type passed`),Error(`response_type`);if(!o)throw this._logger.error(`create: No scope passed`),Error(`scope`);if(!n)throw this._logger.error(`create: No authority passed`),Error(`authority`);let x=await Ze.create({data:s,request_type:l,url_state:f,code_verifier:!_,client_id:r,authority:n,redirect_uri:i,response_mode:c,client_secret:u,scope:o,extraTokenParams:g,skipUserInfo:m,nonce:d}),S=new URL(t);S.searchParams.append(`client_id`,r),S.searchParams.append(`redirect_uri`,i),S.searchParams.append(`response_type`,a),y||S.searchParams.append(`scope`,o),d&&S.searchParams.append(`nonce`,d),v&&S.searchParams.append(`dpop_jkt`,v);let C=x.id;f&&(C=`${C}${Me}${f}`),S.searchParams.append(`state`,C),x.code_challenge&&(S.searchParams.append(`code_challenge`,x.code_challenge),S.searchParams.append(`code_challenge_method`,`S256`)),p&&(Array.isArray(p)?p:[p]).forEach(e=>S.searchParams.append(`resource`,e));for(let[e,t]of Object.entries({response_mode:c,...b,...h}))t!=null&&S.searchParams.append(e,t.toString());return new e({url:S.href,state:x})}};Qe._logger=new W(`SigninRequest`);var $e=Qe,et=`openid`,tt=class{constructor(e){if(this.access_token=``,this.token_type=``,this.profile={},this.state=e.get(`state`),this.session_state=e.get(`session_state`),this.state){let e=decodeURIComponent(this.state).split(Me);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Me))}this.error=e.get(`error`),this.error_description=e.get(`error_description`),this.error_uri=e.get(`error_uri`),this.code=e.get(`code`)}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-Ae.getEpochTime()}set expires_in(e){typeof e==`string`&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+Ae.getEpochTime())}get isOpenId(){return this.scope?.split(` `).includes(et)||!!this.id_token}},nt=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:i,request_type:a,client_id:o,url_state:s}){if(this._logger=new W(`SignoutRequest`),!e)throw this._logger.error(`ctor: No url passed`),Error(`url`);let c=new URL(e);if(n&&c.searchParams.append(`id_token_hint`,n),o&&c.searchParams.append(`client_id`,o),r&&(c.searchParams.append(`post_logout_redirect_uri`,r),t||s)){this.state=new Xe({data:t,request_type:a,url_state:s});let e=this.state.id;s&&(e=`${e}${Me}${s}`),c.searchParams.append(`state`,e)}for(let[e,t]of Object.entries({...i}))t!=null&&c.searchParams.append(e,t.toString());this.url=c.href}},rt=class{constructor(e){if(this.state=e.get(`state`),this.state){let e=decodeURIComponent(this.state).split(Me);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Me))}this.error=e.get(`error`),this.error_description=e.get(`error_description`),this.error_uri=e.get(`error_uri`)}},it=[`nbf`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`at_hash`],at=[`sub`,`iss`,`aud`,`exp`,`iat`],ot=class{constructor(e){this._settings=e,this._logger=new W(`ClaimsService`)}filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:it;for(let n of e)at.includes(n)||delete t[n]}return t}mergeClaims(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(n[e]!==r){if(Array.isArray(n[e])||Array.isArray(r)){if(this._settings.mergeClaimsStrategy.array==`replace`)n[e]=r;else{let t=Array.isArray(n[e])?n[e]:[n[e]];for(let e of Array.isArray(r)?r:[r])t.includes(e)||t.push(e);n[e]=t}}else n[e]=typeof n[e]==`object`&&typeof r==`object`?this.mergeClaims(n[e],r):r}return n}},st=class{constructor(e,t){this.keys=e,this.nonce=t}},ct=class{constructor(e,t){this._logger=new W(`OidcClient`),this.settings=e instanceof Ke?e:new Ke(e),this.metadataService=t??new Be(this.settings),this._claimsService=new ot(this.settings),this._validator=new Ye(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Je(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:i,login_hint:a,skipUserInfo:o,nonce:s,url_state:c,response_type:l=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:f=this.settings.prompt,display:p=this.settings.display,max_age:m=this.settings.max_age,ui_locales:h=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:x,omitScopeWhenRequesting:S=this.settings.omitScopeWhenRequesting}){let C=this._logger.create(`createSigninRequest`);if(l!==`code`)throw Error(`Only the Authorization Code flow (with PKCE) is supported`);let w=await this.metadataService.getAuthorizationEndpoint();C.debug(`Received authorization endpoint`,w);let T=await $e.create({url:w,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:u,state_data:e,url_state:c,prompt:f,display:p,max_age:m,ui_locales:h,id_token_hint:i,login_hint:a,acr_values:g,dpopJkt:x,resource:_,request:t,request_uri:n,extraQueryParams:y,extraTokenParams:b,request_type:r,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:s,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:S});await this.clearStaleState();let E=T.state;return await this.settings.stateStore.set(E.id,E.toStorageString()),T}async readSigninResponseState(e,t=!1){let n=this._logger.create(`readSigninResponseState`),r=new tt(je.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(Error(`No state in response`)),null;let i=await this.settings.stateStore[t?`remove`:`get`](r.state);if(!i)throw n.throw(Error(`No matching state found in storage`)),null;return{state:await Ze.fromStorageString(i),response:r}}async processSigninResponse(e,t,n=!0){let r=this._logger.create(`processSigninResponse`),{state:i,response:a}=await this.readSigninResponseState(e,n);if(r.debug(`received state from storage; validating response`),this.settings.dpop&&this.settings.dpop.store){let e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(a,i,t)}catch(e){if(e instanceof Re&&this.settings.dpop){let n=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=n,await this._validator.validateSigninResponse(a,i,t)}else throw e}return a}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await G.generateDPoPKeys(),r=new st(n,t),await e.set(this.settings.client_id,r)),await G.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:`POST`,keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){let i=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),a=new tt(new URLSearchParams);return Object.assign(a,i),await this._validator.validateCredentialsResponse(a,n),a}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:a}){let o=this._logger.create(`useRefreshToken`),s;if(this.settings.refreshTokenAllowedScope===void 0)s=e.scope;else{let t=this.settings.refreshTokenAllowedScope.split(` `);s=(e.scope?.split(` `)||[]).filter(e=>t.includes(e)).join(` `)}if(this.settings.dpop&&this.settings.dpop.store){let e=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:e}}let c;try{c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:s,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...a})}catch(o){if(o instanceof Re&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:s,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...a});else throw o}let l=new tt(new URLSearchParams);return Object.assign(l,c),o.debug(`validating response`,l),await this._validator.validateRefreshResponse(l,{...e,scope:s}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:i,post_logout_redirect_uri:a=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){let s=this._logger.create(`createSignoutRequest`),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw s.throw(Error(`No end session endpoint`)),null;s.debug(`Received end session endpoint`,c),!n&&a&&!t&&(n=this.settings.client_id);let l=new nt({url:c,id_token_hint:t,client_id:n,post_logout_redirect_uri:a,state_data:e,extraQueryParams:o,request_type:r,url_state:i});await this.clearStaleState();let u=l.state;return u&&(s.debug(`Signout request has state to persist`),await this.settings.stateStore.set(u.id,u.toStorageString())),l}async readSignoutResponseState(e,t=!1){let n=this._logger.create(`readSignoutResponseState`),r=new rt(je.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug(`No state in response`),r.error)throw n.warn(`Response was error:`,r.error),new Ne(r);return{state:void 0,response:r}}let i=await this.settings.stateStore[t?`remove`:`get`](r.state);if(!i)throw n.throw(Error(`No matching state found in storage`)),null;return{state:await Xe.fromStorageString(i),response:r}}async processSignoutResponse(e){let t=this._logger.create(`processSignoutResponse`),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug(`Received state from storage; validating response`),this._validator.validateSignoutResponse(r,n)):t.debug(`No state from storage; skipping response validation`),r}clearStaleState(){return this._logger.create(`clearStaleState`),Xe.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create(`revokeToken`),await this._tokenClient.revoke({token:e,token_type_hint:t})}},lt=class{constructor(e){this._userManager=e,this._logger=new W(`SessionMonitor`),this._start=async e=>{let t=e.session_state;if(!t)return;let n=this._logger.create(`_start`);if(e.profile?(this._sub=e.profile.sub,n.debug(`session_state`,t,`, sub`,this._sub)):(this._sub=void 0,n.debug(`session_state`,t,`, anonymous user`)),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{let e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug(`initializing check session iframe`);let r=this._userManager.settings.client_id,i=this._userManager.settings.checkSessionIntervalInSeconds,a=this._userManager.settings.stopCheckSessionOnError,o=new Ie(this._callback,r,e,i,a);await o.load(),this._checkSessionIFrame=o,o.start(t)}else n.warn(`no check session iframe found in the metadata`)}catch(e){n.error(`Error from getCheckSessionIframe:`,e instanceof Error?e.message:e)}},this._stop=()=>{let e=this._logger.create(`_stop`);if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){let t=setInterval(async()=>{clearInterval(t);try{let e=await this._userManager.querySessionStatus();if(e){let t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error(`error from querySessionStatus`,t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{let e=this._logger.create(`_callback`);try{let t=await this._userManager.querySessionStatus(),n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug(`same sub still logged in at OP, session state has changed, restarting check session iframe; session_state`,t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug(`different subject signed into OP`,t.sub):e.debug(`subject no longer signed into OP`),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug(`no change in session detected, no event to raise`)}catch(t){this._sub&&(e.debug(`Error calling queryCurrentSigninSession; raising signed out event`,t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(Error(`No user manager passed`)),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create(`_init`);let e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){let e=await this._userManager.querySessionStatus();if(e){let t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},ut=class e{constructor(e){this.id_token=e.id_token,this.session_state=e.session_state??null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-Ae.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+Ae.getEpochTime())}get expired(){let e=this.expires_in;if(e!==void 0)return e<=0}get scopes(){return this.scope?.split(` `)??[]}toStorageString(){return new W(`User`).create(`toStorageString`),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return W.createStatic(`User`,`fromStorageString`),new e(JSON.parse(t))}},dt=`oidc-client`,ft=class{constructor(){this._abort=new Oe(`Window navigation aborted`),this._disposeHandlers=new Set,this._window=null}async navigate(e){let t=this._logger.create(`navigate`);if(!this._window)throw Error(`Attempted to navigate on a disposed window`);t.debug(`setting URL in window`),this._window.location.replace(e.url);let{url:n,keepOpen:r}=await new Promise((n,r)=>{let i=i=>{let a=i.data,o=e.scriptOrigin??window.location.origin;if(i.origin===o&&a?.source===dt){try{let n=je.readParams(a.url,e.response_mode).get(`state`);if(n||t.warn(`no state found in response url`),i.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(Error(`Invalid response from window`))}n(a)}};window.addEventListener(`message`,i,!1),this._disposeHandlers.add(()=>window.removeEventListener(`message`,i,!1));let a=new BroadcastChannel(`oidc-client-popup-${e.state}`);a.addEventListener(`message`,i,!1),this._disposeHandlers.add(()=>a.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),r(e)}))});return t.debug(`got response from window`),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create(`_dispose`);for(let e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){let i={source:dt,url:t,keepOpen:n},a=new W(`_notifyParent`);if(e)a.debug(`With parent. Using parent.postMessage.`),e.postMessage(i,r);else{a.debug(`No parent. Using BroadcastChannel.`);let e=new URL(t).searchParams.get(`state`);if(!e)throw Error(`No parent and no state in URL. Can't complete notification.`);let n=new BroadcastChannel(`oidc-client-popup-${e}`);n.postMessage(i),n.close()}}},pt={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},mt=`_blank`,ht=60,gt=2,_t=10,vt=class extends Ke{constructor(e){let{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=pt,popupWindowTarget:i=mt,redirectMethod:a=`assign`,redirectTarget:o=`self`,iframeNotifyParentOrigin:s=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:u=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:f=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:m=!1,monitorSession:h=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:_=gt,query_status_response_type:v=`code`,stopCheckSessionOnError:y=!0,revokeTokenTypes:b=[`access_token`,`refresh_token`],revokeTokensOnSignout:x=!1,includeIdTokenInSilentSignout:S=!1,accessTokenExpiringNotificationTimeInSeconds:C=ht,maxSilentRenewTimeoutRetries:w,userStore:T}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=i,this.redirectMethod=a,this.redirectTarget=o,this.iframeNotifyParentOrigin=s,this.iframeScriptOrigin=c,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=d||l||_t,this.automaticSilentRenew=f,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=m,this.monitorSession=h,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=y,this.query_status_response_type=v,this.revokeTokenTypes=b,this.revokeTokensOnSignout=x,this.includeIdTokenInSilentSignout=S,this.accessTokenExpiringNotificationTimeInSeconds=C,this.maxSilentRenewTimeoutRetries=w,T)this.userStore=T;else{let e=typeof window<`u`?window.sessionStorage:new Le;this.userStore=new Ve({store:e})}}},yt=class e extends ft{constructor({silentRequestTimeoutInSeconds:t=_t}){super(),this._logger=new W(`IFrameWindow`),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){let e=window.document.createElement(`iframe`);return e.style.visibility=`hidden`,e.style.position=`fixed`,e.style.left=`-1000px`,e.style.top=`0`,e.width=`0`,e.height=`0`,window.document.body.appendChild(e),e}async navigate(e){this._logger.debug(`navigate: Using timeout of:`,this._timeoutInSeconds);let t=setTimeout(()=>void this._abort.raise(new Pe(`IFrame timed out without a response`)),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&=(this._frame.parentNode&&(this._frame.addEventListener(`load`,e=>{var t;let n=e.target;(t=n.parentNode)==null||t.removeChild(n),this._abort.raise(Error(`IFrame removed from DOM`))},!0),(e=this._frame.contentWindow)==null||e.location.replace(`about:blank`)),null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},bt=class{constructor(e){this._settings=e,this._logger=new W(`IFrameNavigator`)}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new yt({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create(`callback`),yt.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},xt=500,St=1e3,Ct=class extends ft{constructor({popupWindowTarget:e=mt,popupWindowFeatures:t={},popupSignal:n,popupAbortOnClose:r}){super(),this._logger=new W(`PopupWindow`);let i=ke.center({...pt,...t});this._window=window.open(void 0,e,ke.serialize(i)),this.abortOnClose=!!r,n&&n.addEventListener(`abort`,()=>{this._abort.raise(Error(n.reason??`Popup aborted`))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{!this._window||typeof this._window.closed!=`boolean`||this._window.closed?this._abort.raise(Error(`Popup blocked by user`)):this.close()},t.closePopupWindowAfterInSeconds*St)}async navigate(e){var t;(t=this._window)==null||t.focus();let n=setInterval(()=>{(!this._window||this._window.closed)&&(this._logger.debug(`Popup closed by user or isolated by redirect`),r(),this._disposeHandlers.delete(r),this.abortOnClose&&this._abort.raise(Error(`Popup closed by user`)))},xt),r=()=>clearInterval(n);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(Error(`Popup closed`)))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),!t&&!window.opener&&window.close()}},wt=class{constructor(e){this._settings=e,this._logger=new W(`PopupNavigator`)}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n,popupAbortOnClose:r}){return new Ct({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n,popupAbortOnClose:r})}async callback(e,{keepOpen:t=!1}){this._logger.create(`callback`),Ct.notifyOpener(e,t)}},Tt=class{constructor(e){this._settings=e,this._logger=new W(`RedirectNavigator`)}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){this._logger.create(`prepare`);let n=window.self;t===`top`&&(n=window.top??window.self);let r=n.location[e].bind(n.location),i;return{navigate:async e=>(this._logger.create(`navigate`),await new Promise((t,n)=>{i=n,window.addEventListener(`pageshow`,()=>t(window.location.href)),r(e.url)})),close:()=>{this._logger.create(`close`),i?.(Error(`Redirect aborted`)),n.stop()}}}async callback(){}},Et=class extends Fe{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new W(`UserManagerEvents`),this._userLoaded=new Oe(`User loaded`),this._userUnloaded=new Oe(`User unloaded`),this._silentRenewError=new Oe(`Silent renew error`),this._userSignedIn=new Oe(`User signed in`),this._userSignedOut=new Oe(`User signed out`),this._userSessionChanged=new Oe(`User session changed`)}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Dt=class{constructor(e){this._userManager=e,this._logger=new W(`SilentRenewService`),this._isStarted=!1,this._retryTimer=new Ae(`Retry Silent Renew`),this._timeoutRetryCount=0,this._tokenExpiring=async()=>{let e=this._logger.create(`_tokenExpiring`);try{await this._userManager.signinSilent(),this._timeoutRetryCount=0,e.debug(`silent token renewal successful`)}catch(t){if(t instanceof Pe){this._timeoutRetryCount++;let n=this._userManager.settings.maxSilentRenewTimeoutRetries;if(n!==void 0&&this._timeoutRetryCount>n){e.error(`Timeout retry limit reached (${this._timeoutRetryCount} > ${n}), raising silentRenewError:`,t),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(t);return}e.warn(`ErrorTimeout from signinSilent (attempt ${this._timeoutRetryCount}), retry in 5s:`,t),this._retryTimer.init(5);return}e.error(`Error from signinSilent:`,t),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(t)}}}async start(){let e=this._logger.create(`start`);if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error(`getUser error`,t)}}}stop(){this._isStarted&&=(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),!1)}},Ot=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},kt=class{constructor(e,t,n,r){this._logger=new W(`UserManager`),this.settings=new vt(e),this._client=new ct(e),this._redirectNavigator=t??new Tt(this.settings),this._popupNavigator=n??new wt(this.settings),this._iframeNavigator=r??new bt(this.settings),this._events=new Et(this.settings),this._silentRenewService=new Dt(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new lt(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){let t=this._logger.create(`getUser`),n=await this._loadUser();return n?(t.info(`user loaded`),await this._events.load(n,e),n):(t.info(`user not found in storage`),null)}async removeUser(){let e=this._logger.create(`removeUser`);await this.storeUser(null),e.info(`user removed from storage`),await this._events.unload()}async signinRedirect(e={}){this._logger.create(`signinRedirect`);let{redirectMethod:t,...n}=e,r;this.settings.dpop?.bind_authorization_code&&(r=await this.generateDPoPJkt(this.settings.dpop));let i=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:`si:r`,dpopJkt:r,...n},i)}async signinRedirectCallback(e=window.location.href){let t=this._logger.create(`signinRedirectCallback`),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info(`success, signed in subject`,n.profile.sub):t.info(`no subject`),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){let r=this._logger.create(`signinResourceOwnerCredential`),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug(`got signin response`);let a=await this._buildUser(i);return a.profile&&a.profile.sub?r.info(`success, signed in subject`,a.profile.sub):r.info(`no subject`),a}async signinPopup(e={}){let t=this._logger.create(`signinPopup`),n;this.settings.dpop?.bind_authorization_code&&(n=await this.generateDPoPJkt(this.settings.dpop));let{popupWindowFeatures:r,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o,...s}=e,c=this.settings.popup_redirect_uri;c||t.throw(Error(`No popup_redirect_uri configured`));let l=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o}),u=await this._signin({request_type:`si:p`,redirect_uri:c,display:`popup`,dpopJkt:n,...s},l);return u&&(u.profile&&u.profile.sub?t.info(`success, signed in subject`,u.profile.sub):t.info(`no subject`)),u}async signinPopupCallback(e=window.location.href,t=!1){let n=this._logger.create(`signinPopupCallback`);await this._popupNavigator.callback(e,{keepOpen:t}),n.info(`success`)}async signinSilent(e={}){let t=this._logger.create(`signinSilent`),{silentRequestTimeoutInSeconds:n,...r}=e,i=await this._loadUser();if(!e.forceIframeAuth&&i?.refresh_token){t.debug(`using refresh token`);let e=new Ot(i);return await this._useRefreshToken({state:e,redirect_uri:r.redirect_uri,resource:r.resource,extraTokenParams:r.extraTokenParams,timeoutInSeconds:n})}let a;this.settings.dpop?.bind_authorization_code&&(a=await this.generateDPoPJkt(this.settings.dpop));let o=this.settings.silent_redirect_uri;o||t.throw(Error(`No silent_redirect_uri configured`));let s;i&&this.settings.validateSubOnSilentRenew&&(t.debug(`subject prior to silent renew:`,i.profile.sub),s=i.profile.sub);let c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});return i=await this._signin({request_type:`si:s`,redirect_uri:o,prompt:`none`,id_token_hint:this.settings.includeIdTokenInSilentRenew?i?.id_token:void 0,dpopJkt:a,...r},c,s),i&&(i.profile?.sub?t.info(`success, signed in subject`,i.profile.sub):t.info(`no subject`)),i}async _useRefreshToken(e){let t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new ut({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){let t=this._logger.create(`signinSilentCallback`);await this._iframeNavigator.callback(e),t.info(`success`)}async signinCallback(e=window.location.href){let{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case`si:r`:return await this.signinRedirectCallback(e);case`si:p`:await this.signinPopupCallback(e);break;case`si:s`:await this.signinSilentCallback(e);break;default:throw Error(`invalid request_type in state`)}}async signoutCallback(e=window.location.href,t=!1){let{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case`so:r`:return await this.signoutRedirectCallback(e);case`so:p`:await this.signoutPopupCallback(e,t);break;case`so:s`:await this.signoutSilentCallback(e);break;default:throw Error(`invalid request_type in state`)}}async querySessionStatus(e={}){let t=this._logger.create(`querySessionStatus`),{silentRequestTimeoutInSeconds:n,...r}=e,i=this.settings.silent_redirect_uri;i||t.throw(Error(`No silent_redirect_uri configured`));let a=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),s=await this._signinStart({request_type:`si:s`,redirect_uri:i,prompt:`none`,id_token_hint:this.settings.includeIdTokenInSilentRenew?a?.id_token:void 0,response_type:this.settings.query_status_response_type,scope:`openid`,skipUserInfo:!0,...r},o);try{let e=await this._client.processSigninResponse(s.url,{});return t.debug(`got signin response`),e.session_state&&e.profile.sub?(t.info(`success for subject`,e.profile.sub),{session_state:e.session_state,sub:e.profile.sub}):(t.info(`success, user not authenticated`),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof Ne)switch(e.error){case`login_required`:case`consent_required`:case`interaction_required`:case`account_selection_required`:return t.info(`success for anonymous user`),{session_state:e.session_state}}throw e}}async _signin(e,t,n){let r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){let n=this._logger.create(`_signinStart`);try{let r=await this._client.createSigninRequest(e);return n.debug(`got signin request`),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug(`error after preparing navigator, closing navigator window`),t.close(),e}}async _signinEnd(e,t){let n=this._logger.create(`_signinEnd`),r=await this._client.processSigninResponse(e,{});return n.debug(`got signin response`),await this._buildUser(r,t)}async _buildUser(e,t){let n=this._logger.create(`_buildUser`),r=new ut(e);if(t){if(t!==r.profile.sub)throw n.debug(`current user does not match user returned from signin. sub from signin:`,r.profile.sub),new Ne({...e,error:`login_required`});n.debug(`current user matches user returned from signin`)}return await this.storeUser(r),n.debug(`user stored`),await this._events.load(r),r}async signoutRedirect(e={}){let t=this._logger.create(`signoutRedirect`),{redirectMethod:n,...r}=e,i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:`so:r`,post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},i),t.info(`success`)}async signoutRedirectCallback(e=window.location.href){let t=this._logger.create(`signoutRedirectCallback`),n=await this._signoutEnd(e);return t.info(`success`),n}async signoutPopup(e={}){let t=this._logger.create(`signoutPopup`),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i,...a}=e,o=this.settings.popup_post_logout_redirect_uri,s=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i});await this._signout({request_type:`so:p`,post_logout_redirect_uri:o,state:o==null?void 0:{},...a},s),t.info(`success`)}async signoutPopupCallback(e=window.location.href,t=!1){let n=this._logger.create(`signoutPopupCallback`);await this._popupNavigator.callback(e,{keepOpen:t}),n.info(`success`)}async _signout(e,t){let n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){let n=this._logger.create(`_signoutStart`);try{let r=await this._loadUser();n.debug(`loaded current user from storage`),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);let i=e.id_token_hint||r&&r.id_token;i&&(n.debug(`setting id_token_hint in signout request`),e.id_token_hint=i),await this.removeUser(),n.debug(`user removed, creating signout request`);let a=await this._client.createSignoutRequest(e);return n.debug(`got signout request`),await t.navigate({url:a.url,state:a.state?.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug(`error after preparing navigator, closing navigator window`),t.close(),e}}async _signoutEnd(e){let t=this._logger.create(`_signoutEnd`),n=await this._client.processSignoutResponse(e);return t.debug(`got signout response`),n}async signoutSilent(e={}){let t=this._logger.create(`signoutSilent`),{silentRequestTimeoutInSeconds:n,...r}=e,i=this.settings.includeIdTokenInSilentSignout?(await this._loadUser())?.id_token:void 0,a=this.settings.popup_post_logout_redirect_uri,o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:`so:s`,post_logout_redirect_uri:a,id_token_hint:i,...r},o),t.info(`success`)}async signoutSilentCallback(e=window.location.href){let t=this._logger.create(`signoutSilentCallback`);await this._iframeNavigator.callback(e),t.info(`success`)}async revokeTokens(e){let t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){let n=this._logger.create(`_revokeInternal`);if(!e)return;let r=t.filter(t=>typeof e[t]==`string`);if(!r.length)n.debug(`no need to revoke due to no token(s)`);else{for(let t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),t!==`access_token`&&(e[t]=null);await this.storeUser(e),n.debug(`user stored`),await this._events.load(e)}}startSilentRenew(){this._logger.create(`startSilentRenew`),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){let e=this._logger.create(`_loadUser`),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug(`user storageString loaded`),ut.fromStorageString(t)):(e.debug(`no user storageString`),null)}async storeUser(e){let t=this._logger.create(`storeUser`);if(e){t.debug(`storing user`);let n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug(`removing user`),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,r){let i=await(this.settings.dpop?.store)?.get(this.settings.client_id);if(i)return await G.generateDPoPProof({url:e,accessToken:t?.access_token,httpMethod:n,keyPair:i.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);return t||(t=new st(await G.generateDPoPKeys()),await e.store.set(this.settings.client_id,t)),await G.generateDPoPJkt(t.keys)}},At=`/auth/callback`,jt=`Your session ended. Sign in again.`,Mt=class extends Error{constructor(){super(jt),this.name=`SessionEndedError`}},Nt=null,Pt=null,Ft=null,It=new Set;async function Lt(){let e=await fetch(`${S()}/graphcore/api/auth/client/`);if(!e.ok)throw Error(`The backend did not say where to sign in`);let{issuer:t,client_id:n}=await e.json();if(!t||!n)throw Error(`The backend named no issuer or client to sign in with`);return{authority:t,clientId:n}}function Rt(){return Nt||(Nt=Lt().then(({authority:e,clientId:t})=>new kt({authority:e,client_id:t,redirect_uri:`${window.location.origin}${x(At)}`,post_logout_redirect_uri:`${window.location.origin}${x(`/`)}`,response_type:`code`,scope:`openid`,automaticSilentRenew:!0})),Nt.catch(()=>{Nt=null})),Nt}function zt(){let{pathname:e,search:t}=window.location;return e===x(`/auth/callback`)&&new URLSearchParams(t).has(`state`)}async function Bt(){try{return!!(await(await Rt()).metadataService.getMetadata()).prompt_values_supported?.includes(`create`)}catch{return!1}}async function Vt(){let e=await(await Rt()).signinRedirectCallback(),t=e.state?.returnTo??`/`;return window.history.replaceState(null,``,t),window.dispatchEvent(new PopStateEvent(`popstate`)),e}async function Ht(e={}){let{pathname:t,search:n,hash:r}=window.location;await(await Rt()).signinRedirect({state:{returnTo:`${t}${n}${r}`},...e.createAccount?{prompt:`create`}:{}})}async function Ut(){let e=await Rt(),t=await e.getUser();if(!t)return null;if(!t.expired)return t;try{return await e.signinSilent()}catch{return await e.removeUser(),null}}function Wt(){return Ft||=(async()=>{let e=await Rt();try{let t=await e.signinSilent();if(t)return t.access_token}catch(e){console.warn(`Session renewal failed:`,e)}return await e.removeUser(),It.forEach(e=>e()),null})().finally(()=>{Ft=null}),Ft}async function Gt(){return(await(await Rt()).getUser())?.expired?(await Wt(),!0):!1}function Kt(e){return It.add(e),()=>It.delete(e)}async function qt(){try{return await Vt()}catch(e){return console.warn(`Ignoring a sign-in callback that cannot be completed:`,e),window.history.replaceState(null,``,x(`/`)),Ut()}}function Jt(){return Pt||=zt()?qt():Ut(),Pt}function Yt(e){let t=t=>{t.persisted&&e()};return window.addEventListener(`pageshow`,t),()=>window.removeEventListener(`pageshow`,t)}async function Xt(){let e=await Rt(),t=await e.getUser();await e.removeUser(),t&&await e.signoutRedirect({id_token_hint:t.id_token})}async function Zt(e,t){if(e.status===401)return new Mt;let n=await e.json().catch(()=>null);return Error(n?.error||`${t} (HTTP ${e.status})`)}var K=new class{async me(e){let t=await fetch(`${S()}/graphcore/api/auth/me/`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`This deployment did not accept the sign-in`);return t.json()}async getIdentity(){let e=await fetch(`${S()}/graphcore/.well-known/graphcore/`);if(!e.ok)throw Error(`Failed to fetch identity document`);return e.json()}_authHeaders(){let{token:e}=_e.getState();return e?{Authorization:`Bearer ${e}`}:{}}async _authorizedFetch(e,t={}){let n=n=>fetch(e,{...t,headers:{...t.headers,...n}}),r=await n(this._authHeaders());if(r.status!==401||w())return r;let i=await Wt();if(!i)throw new Mt;return n({Authorization:`Bearer ${i}`})}async getStrategyDirectory(){let e=await this._authorizedFetch(`${S()}/graphcore/api/get_strategy_directory/`);if(!e.ok)throw await Zt(e,`Failed to fetch strategy directory`);return e.json()}async getRoutes(){let e=await fetch(`${S()}/graphcore/api/routes/`);if(!e.ok)throw Error(`Failed to fetch routes`);return e.json()}async getEntityDirectory(){let e=await this._authorizedFetch(`${S()}/graphcore/api/get_entity_directory/`);if(!e.ok)throw await Zt(e,`Failed to fetch entity directory`);return e.json()}async createInvite(e,t,n={}){let r=await this._authorizedFetch(`${S()}/graphcore/api/invites/`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({resource_id:e,role_name:t,...n})});if(!r.ok)throw await Zt(r,`Failed to create invite`);return r.json()}async redeemInvite(e){let t=await this._authorizedFetch(`${S()}/graphcore/api/invites/redeem/`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:e})});if(!t.ok)throw await Zt(t,`Failed to redeem invite`);return t.json()}async getAccess(e){let t=await this._authorizedFetch(`${S()}/graphcore/api/access/${encodeURIComponent(e)}/`);if(!t.ok)throw await Zt(t,`Failed to fetch access`);return t.json()}async listEntities({type_ids:e,parent_id:t,where:n,granted_to_me:r,cursor:i,limit:a=25}){let o={type_ids:e,limit:a};t&&(o.parent_id=t),n&&(o.where=n),r&&(o.granted_to_me=!0),i&&(o.cursor=i);let s=await this._authorizedFetch(`${S()}/graphcore/api/list_entities/`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw await Zt(s,`Failed to list entities`);return s.json()}async getEntity(e,t){let n={"Content-Type":`application/json`};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${S()}/graphcore/api/get_entity/${encodeURIComponent(e)}/`,{method:`GET`,headers:n});if(!r.ok)throw await Zt(r,`Failed to fetch entity`);return r.json()}},Qt=(e,t)=>({equal:{field:e,value:t}}),$t=(e,t)=>({in_values:{field:e,values:t}}),en=(e,t)=>({contains_value:{field:e,value:t}}),tn=(e,t)=>({contains_any:{field:e,values:t}}),nn=(e,t)=>({range:{field:e,...t}}),rn=(...e)=>({all_of:e}),an=(...e)=>({any_of:e}),on={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},sn=l.default.createContext&&l.default.createContext(on),cn=[`attr`,`size`,`title`];function ln(e,t){if(e==null)return{};var n,r,i=un(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function un(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function dn(){return dn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},dn.apply(null,arguments)}function fn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function pn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?fn(Object(n),!0).forEach(function(t){mn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):fn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function mn(e,t,n){return(t=hn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hn(e){var t=gn(e,`string`);return typeof t==`symbol`?t:t+``}function gn(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function _n(e){return e&&e.map((e,t)=>l.default.createElement(e.tag,pn({key:t},e.attr),_n(e.child)))}function q(e){return t=>l.default.createElement(vn,dn({attr:pn({},e.attr)},t),_n(e.child))}function vn(e){var t=t=>{var n=e.attr,r=e.size,i=e.title,a=ln(e,cn),o=r||t.size||`1em`,s;return t.className&&(s=t.className),e.className&&(s=(s?s+` `:``)+e.className),l.default.createElement(`svg`,dn({stroke:`currentColor`,fill:`currentColor`,strokeWidth:`0`},t.attr,n,a,{className:s,style:pn(pn({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:`http://www.w3.org/2000/svg`}),i&&l.default.createElement(`title`,null,i),e.children)};return sn===void 0?t(on):l.default.createElement(sn.Consumer,null,e=>t(e))}function yn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M85.57 446.25h340.86a32 32 0 0 0 28.17-47.17L284.18 82.58c-12.09-22.44-44.27-22.44-56.36 0L57.4 399.08a32 32 0 0 0 28.17 47.17`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m250.26 195.39 5.74 122 5.73-121.95a5.74 5.74 0 0 0-5.79-6h0a5.74 5.74 0 0 0-5.68 5.95`},child:[]},{tag:`path`,attr:{d:`M256 397.25a20 20 0 1 1 20-20 20 20 0 0 1-20 20`},child:[]}]})(e)}function bn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m112 112 20 320c.95 18.49 14.4 32 32 32h184c17.67 0 30.87-13.51 32-32l20-320`},child:[]},{tag:`path`,attr:{strokeLinecap:`round`,strokeMiterlimit:`10`,strokeWidth:`32`,d:`M80 112h352`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M192 112V72h0a23.93 23.93 0 0 1 24-24h80a23.93 23.93 0 0 1 24 24h0v40m-64 64v224m-72-224 8 224m136-224-8 224`},child:[]}]})(e)}function xn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M434.67 285.59v-29.8c0-98.73-80.24-178.79-179.2-178.79a179 179 0 0 0-140.14 67.36m-38.53 82v29.8C76.8 355 157 435 256 435a180.45 180.45 0 0 0 140-66.92`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m32 256 44-44 46 44m358 0-44 44-46-44`},child:[]}]})(e)}function Sn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M262.29 192.31a64 64 0 1 0 57.4 57.4 64.13 64.13 0 0 0-57.4-57.4M416.39 256a154 154 0 0 1-1.53 20.79l45.21 35.46a10.81 10.81 0 0 1 2.45 13.75l-42.77 74a10.81 10.81 0 0 1-13.14 4.59l-44.9-18.08a16.11 16.11 0 0 0-15.17 1.75A164.5 164.5 0 0 1 325 400.8a15.94 15.94 0 0 0-8.82 12.14l-6.73 47.89a11.08 11.08 0 0 1-10.68 9.17h-85.54a11.11 11.11 0 0 1-10.69-8.87l-6.72-47.82a16.07 16.07 0 0 0-9-12.22 155 155 0 0 1-21.46-12.57 16 16 0 0 0-15.11-1.71l-44.89 18.07a10.81 10.81 0 0 1-13.14-4.58l-42.77-74a10.8 10.8 0 0 1 2.45-13.75l38.21-30a16.05 16.05 0 0 0 6-14.08c-.36-4.17-.58-8.33-.58-12.5s.21-8.27.58-12.35a16 16 0 0 0-6.07-13.94l-38.19-30A10.81 10.81 0 0 1 49.48 186l42.77-74a10.81 10.81 0 0 1 13.14-4.59l44.9 18.08a16.11 16.11 0 0 0 15.17-1.75A164.5 164.5 0 0 1 187 111.2a15.94 15.94 0 0 0 8.82-12.14l6.73-47.89A11.08 11.08 0 0 1 213.23 42h85.54a11.11 11.11 0 0 1 10.69 8.87l6.72 47.82a16.07 16.07 0 0 0 9 12.22 155 155 0 0 1 21.46 12.57 16 16 0 0 0 15.11 1.71l44.89-18.07a10.81 10.81 0 0 1 13.14 4.58l42.77 74a10.8 10.8 0 0 1-2.45 13.75l-38.21 30a16.05 16.05 0 0 0-6.05 14.08c.33 4.14.55 8.3.55 12.47`},child:[]}]})(e)}function Cn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M96 256h320M96 176h320M96 336h320`},child:[]}]})(e)}function wn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M332.64 64.58C313.18 43.57 286 32 256 32c-30.16 0-57.43 11.5-76.8 32.38-19.58 21.11-29.12 49.8-26.88 80.78C156.76 206.28 203.27 256 256 256s99.16-49.71 103.67-110.82c2.27-30.7-7.33-59.33-27.03-80.6M432 480H80a31 31 0 0 1-24.2-11.13c-6.5-7.77-9.12-18.38-7.18-29.11C57.06 392.94 83.4 353.61 124.8 326c36.78-24.51 83.37-38 131.2-38s94.42 13.5 131.2 38c41.4 27.6 67.74 66.93 76.18 113.75 1.94 10.73-.68 21.34-7.18 29.11A31 31 0 0 1 432 480`},child:[]}]})(e)}function Tn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M336 256c-20.56 0-40.44-9.18-56-25.84-15.13-16.25-24.37-37.92-26-61-1.74-24.62 5.77-47.26 21.14-63.76S312 80 336 80c23.83 0 45.38 9.06 60.7 25.52 15.47 16.62 23 39.22 21.26 63.63-1.67 23.11-10.9 44.77-26 61C376.44 246.82 356.57 256 336 256m131.83 176H204.18a27.71 27.71 0 0 1-22-10.67 30.22 30.22 0 0 1-5.26-25.79c8.42-33.81 29.28-61.85 60.32-81.08C264.79 297.4 299.86 288 336 288c36.85 0 71 9 98.71 26.05 31.11 19.13 52 47.33 60.38 81.55a30.27 30.27 0 0 1-5.32 25.78A27.68 27.68 0 0 1 467.83 432M147 260c-35.19 0-66.13-32.72-69-72.93-1.42-20.6 5-39.65 18-53.62 12.86-13.83 31-21.45 51-21.45s38 7.66 50.93 21.57c13.1 14.08 19.5 33.09 18 53.52-2.87 40.2-33.8 72.91-68.93 72.91m65.66 31.45c-17.59-8.6-40.42-12.9-65.65-12.9-29.46 0-58.07 7.68-80.57 21.62-25.51 15.83-42.67 38.88-49.6 66.71a27.39 27.39 0 0 0 4.79 23.36A25.32 25.32 0 0 0 41.72 400h111a8 8 0 0 0 7.87-6.57c.11-.63.25-1.26.41-1.88 8.48-34.06 28.35-62.84 57.71-83.82a8 8 0 0 0-.63-13.39c-1.57-.92-3.37-1.89-5.42-2.89`},child:[]}]})(e)}function En(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M384 224v184a40 40 0 0 1-40 40H104a40 40 0 0 1-40-40V168a40 40 0 0 1 40-40h167.48M336 64h112v112M224 288 440 72`},child:[]}]})(e)}function Dn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M448 96a64 64 0 1 0-96.31 55.21c-1.79 20.87-11.47 38.1-28.87 51.29C305.07 216 280.09 224 256 224s-49.07-8-66.82-21.5c-17.4-13.19-27.08-30.42-28.87-51.29a64 64 0 1 0-64.11.29c2.08 40.87 21.17 76.87 54.31 102C171.3 269.26 197 280.19 224 285.09v75.52a64 64 0 1 0 64 0v-75.52c27-4.9 52.7-15.83 73.49-31.59 33.14-25.13 52.23-61.13 54.31-102A64 64 0 0 0 448 96M128 64a32 32 0 1 1-32 32 32 32 0 0 1 32-32m128 384a32 32 0 1 1 32-32 32 32 0 0 1-32 32m128-320a32 32 0 1 1 32-32 32 32 0 0 1-32 32`},child:[]}]})(e)}function On(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M64 192v-72a40 40 0 0 1 40-40h75.89a40 40 0 0 1 22.19 6.72l27.84 18.56a40 40 0 0 0 22.19 6.72H408a40 40 0 0 1 40 40v40`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M479.9 226.55 463.68 392a40 40 0 0 1-39.93 40H88.25a40 40 0 0 1-39.93-40L32.1 226.55A32 32 0 0 1 64 192h384.1a32 32 0 0 1 31.8 34.55`},child:[]}]})(e)}function kn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`circle`,attr:{cx:`256`,cy:`256`,r:`64`},child:[]},{tag:`path`,attr:{d:`M490.84 238.6c-26.46-40.92-60.79-75.68-99.27-100.53C349 110.55 302 96 255.66 96c-42.52 0-84.33 12.15-124.27 36.11-40.73 24.43-77.63 60.12-109.68 106.07a31.92 31.92 0 0 0-.64 35.54c26.41 41.33 60.4 76.14 98.28 100.65C162 402 207.9 416 255.66 416c46.71 0 93.81-14.43 136.2-41.72 38.46-24.77 72.72-59.66 99.08-100.92a32.2 32.2 0 0 0-.1-34.76M256 352a96 96 0 1 1 96-96 96.11 96.11 0 0 1-96 96`},child:[]}]})(e)}function An(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`circle`,attr:{cx:`256`,cy:`256`,r:`48`},child:[]},{tag:`circle`,attr:{cx:`416`,cy:`256`,r:`48`},child:[]},{tag:`circle`,attr:{cx:`96`,cy:`256`,r:`48`},child:[]}]})(e)}function jn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M416 221.25V416a48 48 0 0 1-48 48H144a48 48 0 0 1-48-48V96a48 48 0 0 1 48-48h98.75a32 32 0 0 1 22.62 9.37l141.26 141.26a32 32 0 0 1 9.37 22.62z`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M256 56v120a32 32 0 0 0 32 32h120m-232 80h160m-160 80h160`},child:[]}]})(e)}function Mn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M440.9 136.3a4 4 0 0 0 0-6.91L288.16 40.65a64.14 64.14 0 0 0-64.33 0L71.12 129.39a4 4 0 0 0 0 6.91L254 243.88a4 4 0 0 0 4.06 0zM54 163.51a4 4 0 0 0-6 3.49v173.89a48 48 0 0 0 23.84 41.39L234 479.51a4 4 0 0 0 6-3.46V274.3a4 4 0 0 0-2-3.46zM272 275v201a4 4 0 0 0 6 3.46l162.15-97.23A48 48 0 0 0 464 340.89V167a4 4 0 0 0-6-3.45l-184 108a4 4 0 0 0-2 3.45`},child:[]}]})(e)}function Nn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`rect`,attr:{width:`336`,height:`336`,x:`128`,y:`128`,fill:`none`,strokeLinejoin:`round`,strokeWidth:`32`,rx:`57`,ry:`57`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`m383.5 128 .5-24a56.16 56.16 0 0 0-56-56H112a64.19 64.19 0 0 0-64 64v216a56.16 56.16 0 0 0 56 56h24`},child:[]}]})(e)}function Pn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M160 368 32 256l128-112m192 224 128-112-128-112m-48-48-96 320`},child:[]}]})(e)}function Fn(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M368 368 144 144m224 0L144 368`},child:[]}]})(e)}function In(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeMiterlimit:`10`,strokeWidth:`32`,d:`M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z`},child:[]},{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M250.26 166.05 256 288l5.73-121.95a5.74 5.74 0 0 0-5.79-6h0a5.74 5.74 0 0 0-5.68 6`},child:[]},{tag:`path`,attr:{d:`M256 367.91a20 20 0 1 1 20-20 20 20 0 0 1-20 20`},child:[]}]})(e)}function Ln(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`32`,d:`M256 112v288m144-144H112`},child:[]}]})(e)}var J=Object.freeze({ENTITY:`graphcore.Entity`,VIEW:`graphcore.View`,USER:`graphcore.User`,GROUP:`graphcore.Group`,GRANT:`graphcore.Grant`,DEPLOYMENT:`graphcore.Deployment`,STRATEGY_REQUEST:`graphcore.StrategyRequest`}),Rn={[J.ENTITY]:Mn,[J.VIEW]:kn,[J.USER]:wn,[J.GROUP]:Tn,[J.STRATEGY_REQUEST]:Dn},zn=Mn;function Bn(e){return Rn[e]||zn}var Vn=k(()=>null),Hn=e=>{Vn.setState(e)},Un=(e,t)=>{t instanceof Mt||Hn({message:`${e}: ${t instanceof Error?t.message:String(t)}`,type:`error`})},Wn=()=>R(Vn,e=>e),Gn=100,Kn=100,qn=k(()=>({loaded:{},views:{}})),Jn=new Map,Yn=new Set,Xn=!1,Zn=(e,t,n)=>JSON.stringify([`top`,e,t,n]),Qn=(e,t,n,r)=>JSON.stringify([e,t,n,r]);function $n(e){if(typeof e.slot!=`string`||typeof e.client!=`string`)return null;let t=typeof e.renders==`string`?e.renders:null;return typeof e.parent_id==`string`&&e.parent_id?Qn(e.parent_id,e.client,e.slot,t):typeof e.owner==`string`?Zn(e.owner,e.client,e.slot):null}function er(e,t){let{client:n,address:r,view:i}=e;return r===void 0?{key:JSON.stringify([`view`,n,i]),predicate:rn(en(`ancestor_ids`,i),Qt(`client`,n))}:{key:JSON.stringify([`page`,t,n,r]),predicate:rn(Qt(`owner`,t),Qt(`client`,n),Qt(`address`,r))}}function tr(e){let t={},n=new Set;e.forEach(e=>{if(e?.entity_type_id!==J.VIEW)return;let r=$n(e);r&&(e.deleted?n.add(e.entity_id):t[r]=e.entity_id)}),(Object.keys(t).length!==0||n.size!==0)&&qn.setState(e=>{let r={...e.views,...t};return n.size&&Object.keys(r).forEach(e=>n.has(r[e])&&delete r[e]),{views:r}})}async function nr(e){try{let t=[],n;do{let r=await K.listEntities({type_ids:[J.VIEW],where:e.length===1?e[0].predicate:an(...e.map(e=>e.predicate)),cursor:n,limit:Gn});t.push(...r?.entities??[]),n=r?.next_cursor??void 0}while(n);L.mergeEntities(t),tr(t),qn.setState(t=>({loaded:{...t.loaded,...Object.fromEntries(e.map(e=>[e.key,!0]))}}))}catch(e){console.error(`View lookup failed:`,e),Un(`Could not load views`,e)}finally{e.forEach(e=>Yn.delete(e.key))}}function rr(){Xn=!1;let e=[...Jn.values()];Jn=new Map,e.forEach(e=>Yn.add(e.key));for(let t=0;t<e.length;t+=Kn)nr(e.slice(t,t+Kn))}var ir=e=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,16)};function ar(e,t,n){let{client:r,address:i,view:a,placement:o}=t,s;if(i!==void 0){if(!e.loaded[er(t,n).key])return;s=e.views[Zn(n,r,i)]??null}else{if(o.length&&!e.loaded[er(t,n).key])return;s=a}for(let t of o){if(!s)return null;s=e.views[Qn(s,r,t.slot,t.renders)]??null}return s}var or={request(e,t){let n=er(e,t);qn.getState().loaded[n.key]||Yn.has(n.key)||(Jn.set(n.key,n),!Xn&&(Xn=!0,ir(rr)))},noteEntities(e){tr(e)},find(e,t){return ar(qn.getState(),e,t)},clear(){Jn=new Map,Yn.clear(),Xn=!1,qn.setState({loaded:{},views:{}})}};function sr(e){let{principalEntityId:t}=ve(),n=e&&t?er(e,t).key:null;(0,c.useEffect)(()=>{e&&t&&or.request(e,t)},[n]);let r=R(qn,n=>e&&t?ar(n,e,t):null),i=I(e=>r?e.entitiesById[r]??null:null);if(r!==void 0)return r?i:null}var cr=3e4,lr=1e4,ur=3e3,dr=100,fr=new Set([`succeeded`,`failed`]),pr=null,mr=e=>e?Array.isArray(e)?e.reduce((e,t)=>(t?.entity_id&&(e[t.entity_id]=t),e),{}):Object.entries(e).reduce((e,[t,n])=>((n?.entity_id||t)&&(e[n.entity_id||t]=n),e),{}):{},hr=()=>{let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();if(typeof e?.getRandomValues==`function`){let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join(`-`)}return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return(e===`x`?t:t&3|8).toString(16)})},gr=()=>{let e=C();if(/^wss?:\/\//.test(e)){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/,``)}/ws/entities/`,t.toString()}return`${window.location.protocol===`https:`?`wss:`:`ws:`}//${e}/ws/entities/`},_r=`graphcore.bearer`,vr=()=>{let e={current:null},t={current:{token:null,principalEntityId:null}},n={current:0},r={current:null},i={current:null},a={current:null},o={current:dr},s={current:{outstanding:new Set,since:0,nextId:0}},c={current:null},l={current:null},u=new Map,d={current:{}},f={current:0},p={current:null},m=`idle`,h=e=>{m=e,ce(e)},g=()=>{r.current&&=(clearTimeout(r.current),null)},_=()=>{i.current&&=(clearInterval(i.current),null)},v=()=>{a.current&&=(clearTimeout(a.current),null)},y=()=>{d.current={},f.current=0,p.current!==null&&(window.cancelAnimationFrame(p.current),p.current=null)},b=()=>{p.current=null;let e=d.current;Object.keys(e).length!==0&&(d.current={},f.current=0,L.mergeEntities(e),or.noteEntities(Object.values(e)))},x=e=>{let t=d.current;Object.entries(mr(e)).forEach(([e,n])=>{ne(n,t[e])||(t[e]=n)}),f.current+=1,p.current===null&&(p.current=window.requestAnimationFrame(b))},S=(e,t,n,r={})=>{let i=u.get(e);i&&(clearTimeout(i.timeout),u.delete(e),t?i.resolve(n):i.reject(new le(r.error||`Strategy execution failed`,{code:r.error_code,details:r.error_details,strategyRequestId:r.requestId??i.requestId})))},C=e=>{u.forEach((t,n)=>{let r=t.requestId?e[t.requestId]:void 0;r&&fr.has(r.status)&&S(n,r.status===`succeeded`,r.ret_val,{...r,requestId:r.entity_id})})},w=(e,t=!1)=>{u.forEach((n,r)=>{t&&n.requestId||(clearTimeout(n.timeout),n.reject(e),u.delete(r))})},T=e=>{b();let t={};L.getEntityIds().forEach(e=>{t[e]=L.readEntity(e)?.etag??``}),u.forEach(e=>{e.requestId&&(t[e.requestId]=``)});let n=s.current;n.outstanding=new Set,n.since=Date.now();let r=Object.keys(t);for(let i=0;i<r.length;i+=o.current){let a=r.slice(i,i+o.current);n.nextId+=1,n.outstanding.add(n.nextId),e.send(JSON.stringify({command:`resync`,resync_id:n.nextId,entities:Object.fromEntries(a.map(e=>[e,t[e]]))}))}n.outstanding.size===0&&he(n.since)},E=e=>{let t=s.current;!t.outstanding.delete(e)||t.outstanding.size>0||(b(),he(t.since))},D=(t=`Cleaning up connection`)=>{_(),v(),y();let n=e.current;if(n){if(n.readyState===WebSocket.CONNECTING)n.onopen=()=>n.close(1e3,t);else try{n.close(1e3,t)}catch(e){console.error(`Error closing GraphCore WebSocket:`,e)}}e.current=null},O=t=>{let n=e.current;t&&n&&n.readyState===WebSocket.OPEN&&(L.isRequested(t)||L.isNotFound(t)||(L.markRequested(t),n.send(JSON.stringify({command:`get_entity`,entity_id:t}))))},k=t=>{let n=e.current;t&&n&&n.readyState===WebSocket.OPEN&&(L.readIdForKey(t)||L.isKeyRequested(t)||L.isKeyNotFound(t)||(L.markKeyRequested(t),n.send(JSON.stringify({command:`get_entity`,key:t}))))},A=()=>{let r=t.current.token,a=t.current.principalEntityId;if(!r){h(`idle`);return}g(),D(`Reconnecting`),h(`connecting`);let s=new WebSocket(gr(),[_r,r]);e.current=s,s.onopen=()=>{n.current=0,h(`connected`),t.current.token&&t.current.token!==r&&s.send(JSON.stringify({command:`reauth`,token:t.current.token})),a&&s.send(JSON.stringify({command:`subscribe_entities`,entity_ids:[a]})),_(),i.current=setInterval(()=>M(s,lr),cr)},s.onmessage=e=>{try{let t=JSON.parse(e.data);if(t.type===`auth_error`){l.current?.(t.message||`Session expired. Please log in again.`);return}if(t.type===`connected`){typeof t.max_batch_size==`number`&&t.max_batch_size>0&&(o.current=t.max_batch_size),T(s);return}if(t.type===`resync`){T(s);return}if(t.type===`resync_done`){t.error&&console.error(`GraphCore resync failed:`,t.error),E(t.resync_id);return}if(t.type===`pong`){v();return}if(t.type===`entity_update`){let e=mr(t.entities);C(e),x(e),t.key&&(b(),L.resolveKey(t.key,Object.keys(e)[0]));return}if(t.type===`strategy_queued`){let e=u.get(t.client_request_id);e&&(e.requestId=t.request_id);return}if(t.type===`entity_not_found`){t.key?L.markKeyNotFound(t.key):L.markNotFound(t.entity_id);return}if(t.type===`access_revoked`){x({[t.resource_id]:{entity_id:t.resource_id,forbidden:!0}}),fe(t.resource_id);return}if(t.type===`access_granted`||t.type===`access_changed`){L.clearEntityFlags(t.resource_id),O(t.resource_id),fe(t.resource_id);return}if(t.type===`strategy_result`){S(t.client_request_id,t.success,t.ret_val,{...t,requestId:t.request_id});return}if(t.type===`error`){let e=typeof t.error==`object`?t.error.message||JSON.stringify(t.error):t.error||t.message||`Unknown server error`;console.error(`GraphCore server error:`,e)}}catch(e){console.error(`Error parsing GraphCore WebSocket message:`,e)}},s.onerror=e=>{console.error(`GraphCore WebSocket error:`,e)},s.onclose=e=>j(s,e.code)},j=(i,a,o=!1)=>{if(e.current===i){if(_(),v(),e.current=null,L.clearRequestedEntities(),b(),w(Error(`Connection lost before the request was queued`),!0),h(t.current.token?`disconnected`:`idle`),o&&t.current.token)A();else if(a!==1e3&&t.current.token){let e=Math.min(3e4,2**n.current*500);r.current=setTimeout(()=>{n.current+=1,A()},e)}else n.current=0}},M=(e,t)=>{e.readyState===WebSocket.OPEN&&(e.send(JSON.stringify({command:`ping`})),v(),a.current=setTimeout(()=>{a.current=null,e.onopen=null,e.onmessage=null,e.onclose=null;try{e.close()}catch{}j(e,4e3,!0)},t))},N=()=>{if(!t.current.token)return;let r=e.current;!r||r.readyState===WebSocket.CLOSING||r.readyState===WebSocket.CLOSED?(n.current=0,A()):r.readyState===WebSocket.OPEN&&M(r,ur)},ee=()=>{if(c.current||typeof window>`u`)return;let e=()=>{document.visibilityState===`visible`&&N()},t=e=>{e.persisted&&N()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`online`,N),window.addEventListener(`pageshow`,t),c.current=()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`online`,N),window.removeEventListener(`pageshow`,t)}};return pr=u,{pendingRequests:u,wsRef:e,connect(n){let r=n.token??null,i=n.principalEntityId??null,a=t.current.principalEntityId!==i,o=t.current.token;t.current={token:r,principalEntityId:i},r?(ee(),a||!e.current||e.current.readyState===WebSocket.CLOSED||e.current.readyState===WebSocket.CLOSING?A():e.current.readyState===WebSocket.OPEN&&r!==o&&e.current.send(JSON.stringify({command:`reauth`,token:r}))):this.disconnect(`Authentication ended`)},disconnect(e=`Cleaning up connection`){t.current={token:null,principalEntityId:null},g(),L.clearRequestedEntities(),y(),D(e),h(`idle`),w(Error(`Connection closed`))},dispose(){this.disconnect(`Disposing bridge`),g(),_(),c.current?.(),c.current=null,pr===u&&(pr=null)},fetchEntity:O,fetchEntityByKey:k,subscribe(t){let n=e.current;n&&n.readyState===WebSocket.OPEN&&t.length!==0&&n.send(JSON.stringify({command:`subscribe_entities`,entity_ids:t}))},executeStrategy(t,n={}){let r=e.current;if(!r||r.readyState!==WebSocket.OPEN){let e=Error(`No active WebSocket connection`);if(n.awaitResponse)return Promise.reject(e);throw e}let i=!!n.awaitResponse,a=n.timeout??6e4;if(i){let e=hr(),n={...t,client_request_id:e};return new Promise((t,i)=>{let o=setTimeout(()=>{u.delete(e),i(Error(`Request timeout after ${a}ms`))},a);u.set(e,{resolve:e=>{t(e)},reject:e=>{i(e)},timeout:o}),r.send(JSON.stringify({command:`execute_strategy`,strategy:[n],await_response:!0}))})}let o=Array.isArray(t)?t:t==null?[]:[t];r.send(JSON.stringify({command:`execute_strategy`,strategy:o}))},getStatus(){return m},setOnAuthError(e){l.current=e},ping(){e.current&&M(e.current,lr)}}},yr=e=>Symbol.iterator in e,br=e=>`entries`in e,xr=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},Sr=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function Cr(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:yr(e)&&yr(t)?br(e)&&br(t)?xr(e,t):Sr(e,t):xr({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}var wr=(e,t={})=>{let n=e?.entity_type_id,r=Array.isArray(t.types)?t.types.filter(Boolean):[],i=Array.isArray(t.excludeTypes)?t.excludeTypes.filter(Boolean):[];return!(r.length>0&&!r.includes(n)||i.length>0&&i.includes(n))},Tr=e=>L.readEntity(e),Er=e=>{let t=Tr(e);return Array.isArray(t?.children_ids)?t.children_ids.filter(Boolean):[]},Dr=(e,t={})=>!e||t.enabled===!1?[]:Er(e).map(e=>Tr(e)).filter(e=>!!e).filter(e=>wr(e,t)),Or=(e,t={})=>{if(!e||t.enabled===!1)return null;let n=(r,i=new Set)=>{if(i.has(r))return null;i.add(r);let a=Tr(r);if(!a)return null;let o=Er(r).reduce((e,t)=>{let r=n(t,new Set(i));return r&&(e[t]=r),e},{});return wr(a,t)||Object.keys(o).length>0||t.includeRoot&&r===e?{entity:a,children:o}:null};return n(e)},kr={readEntity(e){return Tr(e)},readEntities(e){return L.readEntities(e)},readChildren(e,t={}){return Dr(e,t)},readRecursiveChildren(e,t={}){return Or(e,t)}},Ar=()=>{let e=D();if(!e)throw Error(`useGraphCoreBridge must be used within GraphCoreProvider.`);return e},jr=()=>{let e=Ar();return(0,c.useMemo)(()=>e.executeStrategy.bind(e),[e])},Mr=(e,t)=>{t&&e.forEach(e=>{!e||L.readEntity(e)||L.isNotFound(e)||t(e)})},Y=e=>{let t=Ar(),n=z(),r=I((0,c.useMemo)(()=>t=>e?t.entitiesById[e]??null:null,[e]));return(0,c.useEffect)(()=>{Mr([e],t.fetchEntity)},[t,n,e,r]),r},Nr=e=>{let t=Ar(),n=z(),r=I(t=>e?t.idsByKey[e]??null:null),i=I(t=>e?t.notFoundKeys.has(e):!1);return(0,c.useEffect)(()=>{e&&!r&&!i&&t.fetchEntityByKey(e)},[t,n,r,e,i]),{entityId:r,notFound:i}},Pr=e=>{let t=Ar(),n=(0,c.useMemo)(()=>e.filter(Boolean),[e]),r=z(),i=I(e=>n.map(t=>e.entitiesById[t]??null).filter(e=>!!e),Cr);return(0,c.useEffect)(()=>{Mr(n,t.fetchEntity)},[t,r,i,n]),i},Fr=(e,t={})=>{let n=Ar(),r=Y(e),i=(0,c.useMemo)(()=>Array.isArray(r?.children_ids)?r.children_ids.filter(Boolean):[],[r?.children_ids]),a=z(),o=I(()=>kr.readChildren(e,t),Cr);return(0,c.useEffect)(()=>{Mr(i,n.fetchEntity)},[n,a,i]),o},Ir=(e,t={})=>{let n=Ar(),r=z(),i=I(e=>e.entityIds),a=(0,c.useMemo)(()=>kr.readRecursiveChildren(e,t),[i,t,e]);return(0,c.useEffect)(()=>{Mr([e],n.fetchEntity)},[n,r,e]),a},Lr=e=>e?.attributes??{},Rr=(e,t)=>Lr(e)[t],zr=e=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==`attributes`));function Br(e){return(typeof e==`string`?e:e?.entity_type_id)?.split(`.`).pop()??``}function X(e){return[e?.display_name,Br(e),e?.entity_id].find(e=>typeof e==`string`&&e.trim().length>0)??`Entity`}var Vr=()=>{let e=I(e=>e.entityIds,Cr),t=(0,c.useCallback)(e=>{L.mergeEntities(e)},[]);async function n(){try{let e=await K.getEntityDirectory();t(e.entities||e)}catch(e){console.error(`Failed to fetch entity types:`,e)}}return{entityIds:e,mergeEntities:t,fetchEntityTypes:n,clearEntities:(0,c.useCallback)(()=>{L.clearEntities()},[])}},Hr=()=>{let e=ve(),{mergeEntities:t,clearEntities:n}=Vr(),{isAuthenticated:r,isLoading:i,token:a,principalEntityId:o,username:s,error:c}=e;function l(e){B(t=>({...t,error:e}))}async function u(e){B(e=>({...e,isLoading:!0,error:null}));try{await Ht(e)}catch(e){console.error(`Sign-in error:`,e),B(t=>({...t,isLoading:!1,error:e.message||`Sign-in failed`}))}}let d=()=>u(),f=()=>u({createAccount:!0});async function p(){n(),or.clear(),B(ge());try{await Xt()}catch(e){console.error(`Sign-out error:`,e)}}async function m(e,n){let r=e||o,i=n||a;if(!r)console.warn(`Cannot load user entities: no principalEntityId provided`);else try{let e=await K.getEntity(r,i);e&&t([e])}catch(e){console.error(`Error loading user entities:`,e),l(`Failed to load user entities: ${e.message}`)}}async function h(){if(!a||!o)return!1;try{return await m(o),!0}catch(e){return console.error(`Token validation failed:`,e),p(),!1}}return{isAuthenticated:r,isLoading:i,token:a,principalEntityId:o,username:s,error:c,login:d,register:f,logout:p,loadUserEntities:m,validateToken:h,setAuthError:l}},Ur=k(()=>null),Wr=e=>{Ur.setState(e,!0)},Gr=()=>R(Ur,e=>e),Kr={error:`bg-red-50 border-red-200 text-red-700`,success:`bg-green-50 border-green-200 text-green-700`,info:`bg-blue-50 border-blue-200 text-blue-700`},qr=()=>{let e=Wn();if((0,c.useEffect)(()=>{if(!e)return;let t=setTimeout(()=>Hn(null),5e3);return()=>clearTimeout(t)},[e]),!e)return null;let t=typeof e.message==`string`?e.message:JSON.stringify(e.message);return(0,u.jsx)(`div`,{className:`pointer-events-none fixed inset-x-0 top-4 z-10000 flex justify-center px-4`,children:(0,u.jsxs)(`div`,{className:`pointer-events-auto flex max-w-md items-center gap-3 rounded-lg border px-4 py-3 text-sm shadow-lg ${Kr[e.type]||Kr.info}`,children:[(0,u.jsx)(`span`,{className:`flex-1`,children:t}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>Hn(null),className:`text-lg leading-none opacity-60 hover:opacity-100`,"aria-label":`Dismiss notification`,children:`×`})]})})},Jr=(0,c.createContext)(null),Yr=Jr.Provider;function Xr(){let e=(0,c.useContext)(Jr);if(!e)throw Error(`useViewRegistry() must be called within a <GraphCoreProvider registry={...}>.`);return e}function Zr(e){return q({tag:`svg`,attr:{viewBox:`0 0 640 512`},child:[{tag:`path`,attr:{d:`M622.3 271.1l-115.2-45c-4.1-1.6-12.6-3.7-22.2 0l-115.2 45c-10.7 4.2-17.7 14-17.7 24.9 0 111.6 68.7 188.8 132.9 213.9 9.6 3.7 18 1.6 22.2 0C558.4 489.9 640 420.5 640 296c0-10.9-7-20.7-17.7-24.9zM496 462.4V273.3l95.5 37.3c-5.6 87.1-60.9 135.4-95.5 151.8zM224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm96 40c0-2.5.8-4.8 1.1-7.2-2.5-.1-4.9-.8-7.5-.8h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c6.8 0 13.3-1.5 19.2-4-54-42.9-99.2-116.7-99.2-212z`},child:[]}]})(e)}function Qr(e){return q({tag:`svg`,attr:{viewBox:`0 0 352 512`},child:[{tag:`path`,attr:{d:`M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z`},child:[]}]})(e)}function $r(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M497 273L329 441c-15 15-41 4.5-41-17v-96H152c-13.3 0-24-10.7-24-24v-96c0-13.3 10.7-24 24-24h136V88c0-21.4 25.9-32 41-17l168 168c9.3 9.4 9.3 24.6 0 34zM192 436v-40c0-6.6-5.4-12-12-12H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h84c6.6 0 12-5.4 12-12V76c0-6.6-5.4-12-12-12H96c-53 0-96 43-96 96v192c0 53 43 96 96 96h84c6.6 0 12-5.4 12-12z`},child:[]}]})(e)}function ei(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z`},child:[]}]})(e)}function ti(e){return q({tag:`svg`,attr:{viewBox:`0 0 640 512`},child:[{tag:`path`,attr:{d:`M32,224H64V416H32A31.96166,31.96166,0,0,1,0,384V256A31.96166,31.96166,0,0,1,32,224Zm512-48V448a64.06328,64.06328,0,0,1-64,64H160a64.06328,64.06328,0,0,1-64-64V176a79.974,79.974,0,0,1,80-80H288V32a32,32,0,0,1,64,0V96H464A79.974,79.974,0,0,1,544,176ZM264,256a40,40,0,1,0-40,40A39.997,39.997,0,0,0,264,256Zm-8,128H192v32h64Zm96,0H288v32h64ZM456,256a40,40,0,1,0-40,40A39.997,39.997,0,0,0,456,256Zm-8,128H384v32h64ZM640,256V384a31.96166,31.96166,0,0,1-32,32H576V224h32A31.96166,31.96166,0,0,1,640,256Z`},child:[]}]})(e)}function ni(e){return q({tag:`svg`,attr:{viewBox:`0 0 448 512`},child:[{tag:`path`,attr:{d:`M320 448v40c0 13.255-10.745 24-24 24H24c-13.255 0-24-10.745-24-24V120c0-13.255 10.745-24 24-24h72v296c0 30.879 25.121 56 56 56h168zm0-344V0H152c-13.255 0-24 10.745-24 24v368c0 13.255 10.745 24 24 24h272c13.255 0 24-10.745 24-24V128H344c-13.2 0-24-10.8-24-24zm120.971-31.029L375.029 7.029A24 24 0 0 0 358.059 0H352v96h96v-6.059a24 24 0 0 0-7.029-16.97z`},child:[]}]})(e)}function ri(e){return q({tag:`svg`,attr:{viewBox:`0 0 448 512`},child:[{tag:`path`,attr:{d:`M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z`},child:[]}]})(e)}function ii(e){return q({tag:`svg`,attr:{viewBox:`0 0 512 512`},child:[{tag:`path`,attr:{d:`M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z`},child:[]}]})(e)}var ai=/version: (\S+)/,oi=0;async function si(e){let t=await fetch(`${S()}/mcp`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,Authorization:`Bearer ${_e.getState().token??``}`},body:JSON.stringify({jsonrpc:`2.0`,id:++oi,method:`tools/call`,params:{name:`open`,arguments:{at:e}}})});if(!t.ok)throw Error(`The agent frontend answered ${t.status}`);let n=await t.json();if(n.error)throw Error(n.error.message);let r=(n.result?.content??[]).map(e=>e.text??``).join(`
2
+ `);if(n.result?.isError)throw Error(r);return{text:r,version:ai.exec(r)?.[1]??null}}var ci=`e/:backend_id/:local_id`,li=`[0-9a-hjkmnp-tv-z]`,ui=RegExp(`gc:/+(${li}{10})/(${li}{12})(?![0-9A-Za-z])`);function di(e){return`/e/${e.replace(/^gc:\/\//,``)}`}function fi(e){let{backend_id:t,local_id:n}=e;return t&&n?`gc://${t}/${n}`:null}function pi(e){let t=e;try{t=decodeURIComponent(e)}catch{}let n=ui.exec(t);return n?`gc://${n[1]}/${n[2]}`:null}var mi=`graphcore.agent_mirror`,hi=2e3,gi=(0,c.createContext)(!1),_i=()=>{try{return localStorage.getItem(mi)===`1`}catch{return!1}},vi=k(()=>({open:_i()}));function yi(e){vi.setState({open:e});try{localStorage.setItem(mi,e?`1`:`0`)}catch{}}function bi(e){let[t,n]=(0,c.useState)({place:null,error:null,changed:!1});return(0,c.useEffect)(()=>{let t=!1,r=!1,i=!1,a=null,o,s;n({place:null,error:null,changed:!1});let c=async()=>{if(r)i=!0;else{r=!0;try{let r=await si(e);if(t)return;let i=a!==null&&r.version!==a;a=r.version,n({place:r,error:null,changed:i}),i&&(clearTimeout(s),s=setTimeout(()=>n(e=>({...e,changed:!1})),hi))}catch(e){if(t)return;n(t=>({...t,error:e instanceof Error?e.message:String(e),changed:!1}))}finally{r=!1}i&&!t&&(i=!1,c())}};c();let l=F.subscribe((e,t)=>{e.entitiesById!==t.entitiesById&&(clearTimeout(o),o=setTimeout(c,250))});return()=>{t=!0,clearTimeout(o),clearTimeout(s),l()}},[e]),t}var xi=`[0-9a-hjkmnp-tv-z]`,Si=RegExp(`(gc://${xi}{10}/${xi}{12}|/e/${xi}{10}/${xi}{12})`,`g`);function Ci({text:e}){let t=e.split(Si);return(0,u.jsx)(u.Fragment,{children:t.map((e,t)=>t%2?(0,u.jsx)(d.Link,{to:e.startsWith(`gc://`)?di(e):e,className:`text-blue-700 hover:underline`,children:e},t):e)})}function wi({text:e}){return(0,u.jsx)(`div`,{className:`space-y-0.5 font-mono text-xs text-gray-800`,children:e.split(`
3
+ `).map((e,t)=>e.startsWith(`# `)?(0,u.jsx)(`h2`,{className:`font-sans text-base font-semibold text-gray-900`,children:(0,u.jsx)(Ci,{text:e.slice(2)})},t):e.startsWith(`## `)?(0,u.jsx)(`h3`,{className:`pt-2 font-sans text-sm font-semibold text-gray-900`,children:(0,u.jsx)(Ci,{text:e.slice(3)})},t):e.startsWith(`- `)?(0,u.jsxs)(`div`,{className:`break-all pl-3 -indent-3`,children:[`• `,(0,u.jsx)(Ci,{text:e.slice(2)})]},t):e.trim()?(0,u.jsx)(`div`,{className:`break-all text-gray-600`,children:(0,u.jsx)(Ci,{text:e})},t):(0,u.jsx)(`div`,{className:`h-2`},t))})}function Ti({address:e}){let{place:t,error:n,changed:r}=bi(e),[i,a]=(0,c.useState)(!1);return(0,u.jsxs)(`aside`,{"aria-label":`Agent view`,className:`flex h-full w-2/5 min-w-80 flex-col border-l border-gray-200 bg-white`,children:[(0,u.jsxs)(`header`,{className:`flex items-center gap-2 border-b border-gray-200 px-3 py-2 text-xs text-gray-600 transition-colors ${r?`bg-amber-50`:``}`,children:[(0,u.jsx)(ti,{className:`h-3.5 w-3.5 shrink-0 text-gray-500`}),(0,u.jsx)(`code`,{className:`min-w-0 truncate text-gray-900`,children:e}),t?.version&&(0,u.jsxs)(`span`,{className:`shrink-0 font-mono text-gray-400`,children:[`v`,t.version.slice(0,8)]}),r&&(0,u.jsx)(`span`,{className:`shrink-0 rounded bg-amber-200 px-1.5 text-amber-900`,children:`changed`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>a(!i),className:`ml-auto shrink-0 rounded border border-gray-200 px-2 py-0.5 hover:bg-gray-50`,children:i?`Formatted`:`Raw`}),(0,u.jsx)(`button`,{type:`button`,"aria-label":`Close agent view`,onClick:()=>yi(!1),className:`shrink-0 rounded p-1 hover:bg-gray-100`,children:(0,u.jsx)(Qr,{className:`h-3 w-3`})})]}),(0,u.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:[n&&(0,u.jsx)(`div`,{role:`alert`,className:`mb-3 whitespace-pre-wrap rounded border border-red-200 bg-red-50 p-2 font-mono text-xs text-red-700`,children:n}),t?i?(0,u.jsx)(`pre`,{className:`whitespace-pre-wrap break-all font-mono text-xs text-gray-800`,children:t.text}):(0,u.jsx)(wi,{text:t.text}):!n&&(0,u.jsxs)(`div`,{className:`text-xs text-gray-400`,children:[`Opening `,e,`…`]})]})]})}function Ei({address:e,children:t}){let n=(0,c.useContext)(gi),r=R(vi,e=>e.open);return n?(0,u.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,u.jsxs)(`div`,{className:`relative h-full min-w-0 flex-1`,children:[t,!r&&(0,u.jsxs)(`button`,{type:`button`,onClick:()=>yi(!0),className:`absolute bottom-3 right-3 z-10 flex items-center gap-1.5 rounded-full border border-gray-200 bg-white px-3 py-1.5 text-xs text-gray-700 shadow-sm hover:bg-gray-50`,children:[(0,u.jsx)(ti,{className:`h-3.5 w-3.5`}),`Agent view`]})]}),r&&(0,u.jsx)(Ti,{address:e})]}):(0,u.jsx)(u.Fragment,{children:t})}function Di({getToken:e,principalEntityId:t}){return(0,c.useEffect)(()=>{let n=e();n&&B(e=>({...e,isAuthenticated:!0,isLoading:!1,token:n,principalEntityId:t??e.principalEntityId}))},[e,t]),null}function Oi(){let{mergeEntities:e,clearEntities:t}=Vr();return(0,c.useEffect)(()=>{let n=!1,r=()=>{},i=Yt(()=>window.location.reload()),a=e=>{B(t=>t.isAuthenticated?{...t,token:e.access_token}:t)},o=()=>{t(),or.clear(),B({...ge(),error:jt})},s=Kt(o);return(async()=>{try{let t=await Rt();t.events.addUserLoaded(a),t.events.addSilentRenewError(o),r=()=>{t.events.removeUserLoaded(a),t.events.removeSilentRenewError(o)};let i=await Jt();if(n)return;if(!i){B(e=>({...e,isLoading:!1}));return}let s=await K.me(i.access_token);if(n)return;B(e=>({...e,isAuthenticated:!0,isLoading:!1,error:null,token:i.access_token,principalEntityId:s.principal_entity_id,username:s.username}));let c=await K.getEntity(s.principal_entity_id,i.access_token);!n&&c&&e([c])}catch(e){if(n)return;console.error(`Sign-in error:`,e),B(t=>({...t,isLoading:!1,error:e instanceof Error?e.message:`Sign-in failed`}))}})(),()=>{n=!0,r(),i(),s()}},[e,t]),null}function ki({bridge:e}){let{isAuthenticated:t,token:n,principalEntityId:r}=Hr();return(0,c.useEffect)(()=>(e.setOnAuthError(async e=>{(w()||!await Gt())&&Hn({message:e,type:`error`})}),()=>e.setOnAuthError(null)),[e]),(0,c.useEffect)(()=>{t&&n?e.connect({token:n,principalEntityId:r}):e.disconnect(`Authentication ended`)},[e,t,n,r]),null}function Ai({apiUrl:e}){return(0,c.useEffect)(()=>{let e=!1;return K.getIdentity().then(t=>{e||Wr(t?.deployment_entity_id??null)}).catch(()=>{e||Wr(null)}),()=>{e=!0}},[e]),null}function ji({apiUrl:e,wsUrl:t,registry:n,getToken:r,principalEntityId:i,agentMirror:a=!1,basePath:o,children:s}){let l=(0,c.useMemo)(()=>vr(),[]);return _(e,t,r),y(o),(0,c.useEffect)(()=>()=>{l.dispose()},[l]),(0,u.jsx)(Yr,{value:n,children:(0,u.jsxs)(E,{value:l,children:[r?(0,u.jsx)(Di,{getToken:r,principalEntityId:i}):(0,u.jsx)(Oi,{}),(0,u.jsx)(ki,{bridge:l}),(0,u.jsx)(Ai,{apiUrl:e}),(0,u.jsx)(gi.Provider,{value:a,children:s}),(0,u.jsx)(qr,{})]})})}function Mi(){let[e,t]=(0,c.useState)(!1);return(0,c.useEffect)(()=>{let e=!0;return Bt().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}var Ni=`/invite`;function Pi(e){return`${window.location.origin}${x(Ni)}#${e}`}var Fi=e=>e.startsWith(`#`)?decodeURIComponent(e.slice(1)):``;function Ii(){let{pathname:e,hash:t}=(0,d.useLocation)();return e===`/invite`&&!!Fi(t)}function Li({onRedeemed:e}){let{hash:t}=(0,d.useLocation)(),n=(0,d.useNavigate)(),[r,i]=(0,c.useState)(null),a=(0,c.useRef)(null),o=Fi(t);(0,c.useEffect)(()=>{o&&a.current!==o&&(a.current=o,K.redeemInvite(o).then(t=>{e?e(t):n(di(t.resource_id),{replace:!0})}).catch(e=>i(e.message||`This invite is invalid or has expired`)))},[o,e,n]);let s=(0,u.jsx)(`p`,{className:`text-gray-600`,role:`status`,children:`Accepting invite…`});return o?r&&(s=(0,u.jsx)(`p`,{role:`alert`,className:`text-red-600`,children:r})):s=(0,u.jsx)(`p`,{className:`text-gray-600`,children:`This invite link is incomplete.`}),(0,u.jsx)(`div`,{className:`flex h-full items-center justify-center p-8 text-center`,children:s})}var Ri=({className:e,title:t=`graphcore`})=>{let{login:n,register:r,isLoading:i,error:a}=Hr(),o=Mi(),s=Ii();return(0,u.jsx)(`div`,{className:e??`min-h-screen flex items-center justify-center bg-linear-to-br from-blue-50 to-indigo-100 px-4`,children:(0,u.jsxs)(`div`,{className:`max-w-md w-full bg-white rounded-lg shadow-xl p-8`,children:[(0,u.jsxs)(`div`,{className:`text-center mb-8`,children:[(0,u.jsx)(`h1`,{className:`text-3xl font-bold text-gray-900 mb-2`,children:t}),(0,u.jsx)(`p`,{className:`text-gray-600`,role:i?`status`:void 0,children:i?`Please wait...`:s?`You've been invited. Sign in to accept.`:`Sign in to continue`})]}),a&&(0,u.jsx)(`div`,{className:`mb-6 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg text-sm`,children:a}),!i&&(0,u.jsxs)(`div`,{className:`space-y-3`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>n(),className:`w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2.5 px-4 rounded-lg transition focus:ring-4 focus:ring-blue-300`,children:`Sign in`}),o&&(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(),className:`w-full border border-gray-300 text-gray-700 hover:bg-gray-50 font-medium py-2.5 px-4 rounded-lg transition`,children:`Create account`})]})]})})},zi=null;function Bi(){let[e,t]=(0,c.useState)(null);return(0,c.useEffect)(()=>{let e=!1;return zi??=K.getRoutes().then(e=>e.routes),zi.then(n=>!e&&t(n)).catch(()=>{zi=null,e||t([])}),()=>{e=!0}},[]),e}function Z(){let e=Ar(),t=z();return{sendStrategyRequest:(0,c.useCallback)((t,n={})=>{try{let r=e.executeStrategy(t,n);return n.awaitResponse&&r?.catch?r.catch(e=>{throw console.error(`Awaited strategy request failed:`,e),Hn({message:e?.message||`Request failed. Please try again.`,type:`error`}),e}):r}catch(e){if(console.error(`Error sending strategy request:`,e),Hn({message:`Error sending request. Please try again.`,type:`error`}),n.awaitResponse)return Promise.reject(e)}},[e]),isConnected:t===`connected`,bridge:e}}var Vi=50,Hi=250,Ui=!1,Wi={key:``,ids:[],cursor:null};function Gi(e){let t=N(e);if(!t)return;let{entitiesById:n}=F.getState(),r=t.ids.filter(e=>n[e]&&!n[e].forbidden);return r.length===t.ids.length?t:{...t,ids:r}}function Ki({typeIds:e,parentId:t,where:n,grantedToMe:r=!1,limit:i=Vi,all:a=!1,enabled:o=!0}){let s=e.join(`,`),l=n?JSON.stringify(n):``,u=JSON.stringify([s,t??null,l,r,i,a]),d=o&&!!s,[f,p]=(0,c.useState)(()=>Gi(u)??Wi),[m,h]=(0,c.useState)(d),[g,_]=(0,c.useState)({queryKey:u,runs:d}),v=(0,c.useRef)(0),y=(0,c.useRef)(0),b=(0,c.useRef)({ids:new Set,bound:null});if((g.queryKey!==u||g.runs!==d)&&(_({queryKey:u,runs:d}),d&&h(!0),g.queryKey!==u)){let e=Gi(u);e&&p(e)}let x=f.key===u?f:Wi,{ids:S,cursor:C}=x,w=d&&x.key!==u,T=m&&x.key===u;(0,c.useEffect)(()=>{f.key&&!f.forget&&M({key:f.key,ids:f.ids,cursor:f.cursor})},[f]);let E=(0,c.useCallback)(async e=>{if(!s)return;let n=v.current;h(!0);try{let o=[],c=e;do{let e=await K.listEntities({type_ids:s.split(`,`),parent_id:t,where:l?JSON.parse(l):void 0,...r?{granted_to_me:!0}:{},cursor:c,limit:i});if(n!==v.current)return;let a=e?.entities??[];Ui=!0;try{L.mergeEntities(a)}finally{Ui=!1}o.push(...a.map(e=>e.entity_id)),c=e?.next_cursor??null}while(a&&c);p(t=>({key:u,ids:e&&t.key===u?[...t.ids,...o]:o,cursor:c}))}catch(e){if(console.error(`Failed to list entities:`,e),n!==v.current)return;Un(`Could not load entities`,e),p(e=>e.key===u?e:{key:u,ids:[],cursor:null,forget:!0})}finally{n===v.current&&h(!1)}},[s,t,l,r,i,a,u]),D=(0,c.useCallback)(()=>{v.current+=1,y.current=Date.now(),E(null)},[E]);(0,c.useEffect)(()=>{o&&D()},[o,D]),(0,c.useEffect)(()=>{b.current={ids:new Set(S),bound:C===null?null:S[S.length-1]??null}},[S,C]),(0,c.useEffect)(()=>{if(!o||!s)return;let e=new Set(s.split(`,`)),n,r=()=>{clearTimeout(n),n=setTimeout(D,Hi)},i=de(r),a=me(e=>{y.current<e&&r()}),c=F.subscribe((n,i)=>{if(Ui||n.entitiesById===i.entitiesById)return;let a=t=>e.has(t?.entity_type_id),o=Object.keys(n.entitiesById).filter(e=>n.entitiesById[e].forbidden&&a(i.entitiesById[e])),s=e=>{let r=n.entitiesById[e];if(!a(r))return!1;let{ids:i,bound:o}=b.current;if(!i.has(e)&&o!==null&&e>o)return!1;if(l)return!0;let s=typeof t!=`string`||r.parent_id===t;return i.has(e)?!s:s};(o.length>0||Object.keys(n.entitiesById).some(e=>n.entitiesById[e]!==i.entitiesById[e]&&s(e))||Object.keys(i.entitiesById).some(e=>!(e in n.entitiesById)&&b.current.ids.has(e)))&&(o.length>0&&p(e=>({...e,ids:e.ids.filter(e=>!o.includes(e))})),r())});return()=>{c(),i(),a(),clearTimeout(n)}},[o,s,t,l,D]);let O=(0,c.useCallback)(()=>{C&&!m&&E(C)},[C,E,m]);return{ids:S,hasMore:C!==null,loading:w,refreshing:T,loadMore:O,refresh:D}}var qi=k(()=>({contents:{},state:`loading`,error:null})),Ji=k(()=>({contents:{},state:`loading`,error:null})),Yi=k(()=>({contents:{},state:`loading`,error:null})),Xi=null,Zi=null,Qi=async()=>qi.getState().state===`hasValue`?qi.getState().contents:Xi||(qi.setState(e=>({...e,state:`loading`,error:null})),Xi=K.getStrategyDirectory().then(e=>{let t=e||{};return qi.setState({contents:t,state:`hasValue`,error:null}),t}).catch(e=>{throw qi.setState({contents:{},state:`hasError`,error:e}),e}).finally(()=>{Xi=null}),Xi),$i=async()=>Ji.getState().state===`hasValue`?Ji.getState().contents:Zi||(Ji.setState(e=>({...e,state:`loading`,error:null})),Zi=K.getEntityDirectory().then(e=>{let t=e?.entities||e||{};return Ji.setState({contents:t,state:`hasValue`,error:null}),Yi.setState({contents:e?.declared||{},state:`hasValue`,error:null}),t}).catch(e=>(console.error(`Failed to fetch available entities:`,e),Ji.setState({contents:{},state:`hasError`,error:e}),Yi.setState({contents:{},state:`hasError`,error:e}),{})).finally(()=>{Zi=null}),Zi),ea=()=>R(qi),ta=()=>R(Ji),na=()=>ta(),ra=()=>R(Yi),ia=e=>{(0,c.useEffect)(()=>{$i()},[]);let t=ra().contents;return e?t[e]:void 0},Q=class{constructor(){this.reset()}reset(){return this.request={strategy_name:``,target_entity_id:null,param_config:{}},this}withStrategyName(e){return this.request.strategy_name=e,this}withTargetEntity(e){return this.request.target_entity_id=e,this}withParams(e){return this.request.param_config={...this.request.param_config,...e},this}build(){return{...this.request}}},$={builder(){return new Q},createGrant(e,t,n){return new Q().withStrategyName(`CreateGrant`).withTargetEntity(e).withParams({subject_id:t,role_name:n}).build()},changeGrantRole(e,t){return new Q().withStrategyName(`ChangeGrantRole`).withTargetEntity(e).withParams({role_name:t}).build()},revokeGrant(e){return new Q().withStrategyName(`RevokeGrant`).withTargetEntity(e).build()},setAttributes(e,t){return new Q().withStrategyName(`SetAttributes`).withTargetEntity(e).withParams({attribute_map:t}).build()},removeAttribute(e,t){return new Q().withStrategyName(`RemoveAttribute`).withTargetEntity(e).withParams({attribute_name:t}).build()},createEntity(e,t,n={}){let r={entity_type_id:t,initial_attributes:n};return new Q().withStrategyName(`CreateEntity`).withTargetEntity(e).withParams(r).build()},createGroup(e,{parentId:t=null,key:n=null,adminManaged:r=!1}={}){return new Q().withStrategyName(`CreateGroup`).withTargetEntity(t).withParams({name:e,key:n,admin_managed:r}).build()},setNewUserDefaults(e,t,n){return new Q().withStrategyName(`SetNewUserDefaults`).withTargetEntity(e).withParams({group_ids:t,roles:n}).build()},hideEntity(e,t=!0){return $.setAttributes(e,{hidden:t})},deleteEntity(e){return new Q().withStrategyName(`DeleteEntity`).withTargetEntity(e).build()},setViewState(e,{position:t,state:n,component:r}={}){let i=e?{state:n||{}}:{...t,state:n||{}};return r!==void 0&&(i.component=r),new Q().withStrategyName(`SetViewState`).withTargetEntity(e||null).withParams(i).build()},createView(e,{renders:t=null,component:n=null,state:r={}}={}){return new Q().withStrategyName(`CreateView`).withTargetEntity(e||null).withParams({renders:t,component:n,state:r}).build()},reparentChild(e,t){return new Q().withStrategyName(`ReparentChild`).withTargetEntity(e).withParams({parent_id:t}).build()},detachChild(e){return $.reparentChild(e,null)},moveChildBefore(e,t){return new Q().withStrategyName(`ReorderChild`).withTargetEntity(e).withParams({before_child_id:t}).build()},moveChildAfter(e,t){return new Q().withStrategyName(`ReorderChild`).withTargetEntity(e).withParams({after_child_id:t}).build()}};function aa(e){return e.startsWith(`/`)?e.split(/[?#]/)[0].replace(/\/+$/,``)||`/`:null}function oa(e,t=`web`){let n=aa(e);return n?{client:t,address:n,placement:[]}:null}function sa(e,t=`web`){return{client:t,view:e,placement:[]}}function ca(e,t,n){if(!t)throw Error(`A view slot must be a non-empty string`);if(e.placement.length>=64)throw Error(`View placement is deeper than 64 steps`);return{...e,placement:[...e.placement,{slot:t,renders:n??null}]}}function la(e){let{client:t,address:n,view:r,placement:i}=e;return n===void 0?{client:t,view:r,placement:i}:{client:t,address:n,placement:i}}var ua=(0,c.createContext)(null);function da(){return(0,d.useInRouterContext)()?(0,d.useLocation)().pathname:null}function fa(e){let t=da(),n=(0,c.useMemo)(()=>e&&t?oa(t):null,[e,t]),r=sr(n);return(0,c.useMemo)(()=>n?{position:n,view:r}:null,[n,r])}function pa(){let e=(0,c.useContext)(ua),t=fa(!e);return e??t}var ma=e=>{let t=e.slice(e.lastIndexOf(`.`)+1).replace(/_/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)};function ha(e,t){let n=pa(),r=n?.position??null,i=!!n?.route;return(0,c.useMemo)(()=>r&&!i?ca(r,e,t):r,[r,i,e,t])}function ga({position:e,children:t}){let n=sr(e),r=(0,c.useMemo)(()=>({position:e,view:n}),[e,n]);return(0,u.jsx)(ua.Provider,{value:r,children:t})}function _a({address:e,children:t}){let n=(0,c.useMemo)(()=>oa(e),[e]),r=sr(n),i=(0,c.useMemo)(()=>({position:n,view:r,route:!0}),[n,r]);return(0,u.jsx)(ua.Provider,{value:i,children:t})}function va(e,t,n={}){if(!e)throw Error(`A view name must be a non-empty string`);let r=({slot:n,...r})=>{let i=ha(n??e,r.entityId);return(0,u.jsx)(ga,{position:i,children:(0,u.jsx)(t,{...r})})};return r.displayName=`View(${e})`,Object.assign(r,{viewName:e,defaultFor:Object.freeze([...n.defaultFor??[]]),entry:!!n.entry,label:n.label??ma(e),Component:t})}function ya(e){return typeof e==`function`&&typeof e.viewName==`string`&&`Component`in e}var ba=25;function xa({typeIds:e,onPick:t,exclude:n=[],labelFor:r=X,disabled:i=!1,placeholder:a=`Search…`,className:o=``,autoFocus:s=!1,listPlacement:l=`above`}){let{ids:d,hasMore:f,loading:p,loadMore:m}=Ki({typeIds:e,limit:ba}),h=Pr(d),[g,_]=(0,c.useState)(``),[v,y]=(0,c.useState)(!1),b=(0,c.useMemo)(()=>{let e=g.trim().toLowerCase();return h.filter(t=>!n.includes(t.entity_id)&&(!e||r(t).toLowerCase().includes(e)))},[h,n,g,r]);return(0,c.useEffect)(()=>{g&&b.length<ba&&f&&m()},[g,b.length,f,m]),(0,u.jsxs)(`div`,{className:`graphcore-entity-picker relative ${o}`,children:[(0,u.jsx)(`input`,{type:`search`,value:g,disabled:i,placeholder:a,autoFocus:s,onFocus:()=>y(!0),onBlur:()=>y(!1),onChange:e=>_(e.target.value),className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 outline-none focus:border-slate-500`}),v&&(0,u.jsxs)(`ul`,{className:`absolute z-10 max-h-56 ${l===`above`?`bottom-full mb-1`:`top-full mt-1`} w-full overflow-y-auto divide-y divide-slate-100 rounded-md border border-slate-200 bg-white shadow-lg`,onMouseDown:e=>e.preventDefault(),onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<40&&m()},children:[b.map(e=>(0,u.jsx)(`li`,{children:(0,u.jsx)(`button`,{type:`button`,disabled:i,onClick:()=>{t(e),y(!1)},className:`w-full px-3 py-2 text-left text-sm text-slate-800 hover:bg-slate-50 disabled:opacity-50`,children:r(e)})},e.entity_id)),(p||b.length===0&&!f)&&(0,u.jsx)(`li`,{className:`px-3 py-2 text-xs text-slate-500`,children:p?`Loading…`:`No matches`})]})]})}var Sa=(e,t,n)=>$.builder().withStrategyName(e).withTargetEntity(t).withParams(n).build();function Ca({entityId:e}){if(!e)throw Error(`This view needs an entity to show.`);let{sendStrategyRequest:t}=Z(),n=Y(e),r=n?.member_ids??[],i=Pr(r),[a,o]=(0,c.useState)(!1),s=async(n,r)=>{o(!0);try{await t(Sa(n,e,r),{awaitResponse:!0})}finally{o(!1)}};return n?(0,u.jsxs)(`section`,{className:`graphcore-group-view space-y-6 p-6`,children:[(0,u.jsxs)(`label`,{className:`block space-y-1`,children:[(0,u.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-slate-500`,children:`Group name`}),(0,u.jsx)(`input`,{type:`text`,defaultValue:n.name??``,disabled:a,onBlur:e=>{let t=e.target.value.trim();t&&t!==n.name&&s(`ModifyGroup`,{name:t})},onKeyDown:e=>e.key===`Enter`&&e.currentTarget.blur(),className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-lg font-semibold text-slate-900`},n.name??``)]}),(0,u.jsxs)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:[i.length===0&&(0,u.jsx)(`li`,{className:`px-4 py-3 text-sm text-slate-500`,children:`No members yet.`}),i.map(e=>(0,u.jsxs)(`li`,{className:`flex items-center justify-between px-4 py-3 text-sm`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:X(e)}),(0,u.jsx)(`button`,{type:`button`,disabled:a,onClick:()=>void s(`RemoveMember`,{principal_entity_id:e.entity_id}),className:`rounded-md px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-50`,children:`Remove`})]},e.entity_id))]}),(0,u.jsx)(xa,{typeIds:[J.USER],exclude:r,disabled:a,placeholder:`Add a person…`,onPick:e=>void s(`AddMember`,{principal_entity_id:e.entity_id})})]}):(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500`,children:`Loading group…`})}var wa=va(`group_view`,Ca,{defaultFor:[J.GROUP]}),Ta=new Map;function Ea(e,t){let n=Ta.get(e),[r,i]=(0,c.useState)(n||null),[a,o]=(0,c.useState)(!n),[s,l]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=(0,c.useCallback)(async()=>{Ta.has(e)||o(!0),d(null);try{let t=await K.getAccess(e);Ta.set(e,t),i(t)}catch(e){d(e?.message||`Unable to load access`)}finally{o(!1)}},[e]);(0,c.useEffect)(()=>{f()},[f]),(0,c.useEffect)(()=>de(t=>{t===e&&f()}),[e,f]),(0,c.useEffect)(()=>me(()=>{f()}),[f]);let p=!!r?.can_manage,m=(0,c.useMemo)(()=>p&&r?.grants||[],[p,r]);(0,c.useEffect)(()=>{$i()},[]);let h=Y(e),g=na().contents,_=h?.entity_type_id?g[h.entity_type_id]:void 0,v=!!_?.shareable,y=!!_?.invitable,b=_?.roles||[],x=_?.public_permissions||[],S=(0,c.useMemo)(()=>Object.entries(g).filter(([,e])=>e?.principal||e?.group).map(([e])=>e),[g]),C=(0,c.useCallback)(e=>`${X(e)} (${g[e.entity_type_id]?.group?`group`:`person`})`,[g]),w=Pr((0,c.useMemo)(()=>m.map(e=>e.subject_id).filter(e=>e!==`*`),[m])),T=(0,c.useMemo)(()=>{let e={"*":`Anyone signed in`};for(let t of w)e[t.entity_id]=X(t);return e},[w]),E=(0,c.useMemo)(()=>m.find(e=>e.subject_id===`*`&&e.provenance===`direct`),[m]),D=(0,c.useCallback)(async e=>{l(!0);try{await t(e,{awaitResponse:!0}),await f()}finally{l(!1)}},[f,t]);return{summary:r,canManage:p,grants:m,shareable:v,invitable:y,roles:b,publicPermissions:x,subjectTypeIds:S,subjectLabel:C,labelsById:T,publicGrant:E,loading:a,busy:s,error:u,refresh:f,grant:(t,n)=>D($.createGrant(e,t,n)),changeRole:(e,t)=>D($.changeGrantRole(e,t)),revoke:e=>D($.revokeGrant(e)),setPublicRead:()=>D($.createGrant(e,`*`,`viewer`)),revokePublicRead:()=>E?.grant_entity_id?D($.revokeGrant(E.grant_entity_id)):Promise.resolve()}}var Da=`/admin`,Oa=`graphcore.admins`,ka=`member`,Aa=[{id:`members`,label:`Members`},{id:`groups`,label:`Groups`},{id:`roles`,label:`Roles`},{id:`new-users`,label:`New users`}];function ja(e){let{ids:t,refresh:n}=Ki({typeIds:[e],limit:100,all:!0});return{entities:Pr(t),refresh:n}}function Ma({sendStrategyRequest:e,className:t=``}){let{sendStrategyRequest:n}=Z(),r=e??n,i=Gr();return i?(0,u.jsx)(Na,{deploymentId:i,send:r,className:t}):(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500 ${t}`,children:`Loading deployment…`})}function Na({deploymentId:e,send:t,className:n}){let r=Ea(e,t),[i,a]=(0,c.useState)(`members`),[o,s]=(0,c.useState)(null),l=ja(J.USER),d=ja(J.GROUP),f=na().contents[J.DEPLOYMENT]?.roles||[];if(r.loading)return(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500 ${n}`,children:`Loading…`});if(!r.summary?.can_manage)return(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-600 ${n}`,children:`Only deployment administrators can open this page.`});let p=async e=>{try{await t(e,{awaitResponse:!0}),s(null)}catch(e){s(e?.message||`The change was refused.`)}await Promise.all([r.refresh(),l.refresh(),d.refresh()])},m=r.summary.grants;return(0,u.jsxs)(`section`,{className:`graphcore-admin-panel space-y-6 p-6 ${n}`,children:[(0,u.jsxs)(`header`,{className:`space-y-1`,children:[(0,u.jsx)(`h1`,{className:`text-xl font-semibold text-slate-900`,children:`Deployment administration`}),(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Decide who can create things in this deployment, organise people into groups, and set what new users receive.`})]}),o&&(0,u.jsxs)(`div`,{role:`alert`,className:`flex items-start justify-between gap-3 rounded-lg border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-900`,children:[(0,u.jsx)(`span`,{children:o}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>s(null),className:`shrink-0 text-xs font-semibold`,children:`Dismiss`})]}),(0,u.jsx)(`nav`,{className:`flex gap-1 border-b border-slate-200`,role:`tablist`,children:Aa.map(({id:e,label:t})=>(0,u.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":i===e,onClick:()=>a(e),className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium ${i===e?`border-slate-900 text-slate-900`:`border-transparent text-slate-500 hover:text-slate-700`}`,children:t},e))}),i===`members`&&(0,u.jsx)(Fa,{users:l.entities,groups:d.entities,grants:m,run:p}),i===`groups`&&(0,u.jsx)(Ia,{groups:d.entities,grants:m,roles:f,send:t,run:p,deploymentId:e}),i===`roles`&&(0,u.jsx)(Ba,{roles:f}),i===`new-users`&&(0,u.jsx)(Va,{deploymentId:e,groups:d.entities,grants:m,roles:f,run:p})]})}var Pa=(e,t)=>e.filter(e=>e.subject_id===t&&e.provenance===`direct`).map(e=>e.role);function Fa({users:e,groups:t,grants:n,run:r}){let[i,a]=(0,c.useState)(!1),o=t.find(e=>e.key===Oa),s=Pa(n,`*`).includes(ka),l=new Set(t.filter(e=>Pa(n,e.entity_id).length>0).map(e=>e.entity_id)),d=e.map(e=>{let r=t.filter(t=>(t.member_ids||[]).includes(e.entity_id)),i=Pa(n,e.entity_id);return{user:e,memberOf:r,direct:i,hasAccess:s||i.length>0||r.some(e=>l.has(e.entity_id)),isAdmin:r.some(e=>e===o)}}),f=i?d.filter(e=>!e.hasAccess):d;return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:i,onChange:()=>a(!i)}),`Only people with no access yet`]}),s&&(0,u.jsx)(`p`,{className:`rounded-lg bg-blue-50 px-4 py-3 text-sm text-blue-800`,children:`Everyone signed in is a member, so everyone has access. Turn this off under New users to approve people individually.`}),(0,u.jsxs)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:[f.length===0&&(0,u.jsx)(`li`,{className:`px-4 py-3 text-sm text-slate-500`,children:`Nobody here.`}),f.map(({user:e,memberOf:t,direct:n,hasAccess:i,isAdmin:a})=>(0,u.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 px-4 py-3 text-sm`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:X(e)}),a&&(0,u.jsx)(`span`,{className:`rounded bg-slate-900 px-1.5 py-0.5 text-xs text-white`,children:`Admin`}),!i&&(0,u.jsx)(`span`,{className:`rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800`,children:`No access yet`}),(0,u.jsx)(`span`,{className:`text-xs text-slate-500`,children:[...t.map(e=>e.name||e.key),...n].join(` · `)}),o&&!a&&(0,u.jsx)(`button`,{type:`button`,onClick:()=>void r($.builder().withStrategyName(`AddMember`).withTargetEntity(o.entity_id).withParams({principal_entity_id:e.entity_id}).build()),className:`ml-auto rounded-md px-2 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-100`,children:`Make admin`})]},e.entity_id))]})]})}function Ia({groups:e,grants:t,roles:n,send:r,run:i,deploymentId:a}){let o=ra().contents,[s,l]=(0,c.useState)(``),[d,f]=(0,c.useState)(null);return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`A group gives many people the same access at once. Each group has at most one role on the deployment, and everyone in the group has it. Changing a group's role replaces its current role for everyone in it. To combine permissions, use a role that bundles them or add people to several groups.`}),(0,u.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),s.trim()&&i($.createGroup(s.trim(),{adminManaged:!0})).then(()=>l(``))},children:[(0,u.jsx)(`input`,{value:s,onChange:e=>l(e.target.value),placeholder:`New group name`,className:`flex-1 rounded-md border border-slate-300 px-3 py-2 text-sm`}),(0,u.jsx)(`button`,{type:`submit`,className:`rounded-md bg-slate-900 px-3 py-2 text-sm font-medium text-white`,children:`Create group`})]}),(0,u.jsx)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:e.map(e=>{let r=t.find(t=>t.subject_id===e.entity_id&&t.provenance===`direct`),s=d===e.entity_id,c=e.key?o[e.key]:void 0;return(0,u.jsxs)(`li`,{className:`px-4 py-3 text-sm`,children:[(0,u.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>f(s?null:e.entity_id),"aria-expanded":s,className:`font-medium text-slate-900 hover:underline`,children:e.name||e.key||e.entity_id}),c&&(0,u.jsxs)(`span`,{className:`rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600`,title:`Declared by manifest ${c.manifest}`,children:[`Declared · `,e.key]}),(0,u.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[(e.member_ids||[]).length,` members`]}),(0,u.jsxs)(`span`,{className:`ml-auto text-xs text-slate-500`,children:[`Role on the deployment: `,(0,u.jsx)(`span`,{className:`font-mono`,children:r?.role??`none`})]})]}),s&&(0,u.jsxs)(`div`,{className:`mt-3 space-y-3 rounded-lg bg-slate-50 p-3`,children:[(0,u.jsx)(Ra,{group:e,grant:r,roles:n,run:i,deploymentId:a}),(0,u.jsx)(wa,{entityId:e.entity_id}),!c&&(0,u.jsx)(za,{group:e,run:i})]})]},e.entity_id)})})]})}var La=``;function Ra({group:e,grant:t,roles:n,run:r,deploymentId:i}){let a=t?.role??La,[o,s]=(0,c.useState)(null),l=e.name||e.key||`this group`,d=e=>e===La?`no role`:e,f=async()=>{o!==null&&(o===La?t?.grant_entity_id&&await r($.revokeGrant(t.grant_entity_id)):await r($.createGrant(i,e.entity_id,o)),s(null))};return(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsxs)(`label`,{className:`flex flex-wrap items-center gap-2 text-xs text-slate-700`,children:[(0,u.jsx)(`span`,{className:`font-medium`,children:`Role on the deployment`}),(0,u.jsxs)(`select`,{value:o??a,onChange:e=>s(e.target.value===a?null:e.target.value),className:`rounded-md border border-slate-300 bg-white px-2 py-1 text-xs`,children:[(0,u.jsx)(`option`,{value:La,children:`No role`}),n.map(e=>(0,u.jsx)(`option`,{value:e.name,children:e.name},e.name))]})]}),o!==null&&(0,u.jsxs)(`div`,{role:`alertdialog`,"aria-label":`Confirm role change`,className:`space-y-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-900`,children:[(0,u.jsxs)(`p`,{children:[a===La?(0,u.jsxs)(u.Fragment,{children:[`Give `,(0,u.jsx)(`strong`,{children:l}),` the role `,(0,u.jsx)(`strong`,{children:d(o)}),`?`]}):(0,u.jsxs)(u.Fragment,{children:[`Replace `,(0,u.jsx)(`strong`,{children:l}),`'s role `,(0,u.jsx)(`strong`,{children:d(a)}),` with `,(0,u.jsx)(`strong`,{children:d(o)}),`?`]}),` `,`This changes access for everyone in the group.`]}),(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>void f(),className:`rounded-md bg-slate-900 px-2 py-1 font-medium text-white`,children:o===La?`Remove role`:a===La?`Give role`:`Replace role`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>s(null),className:`rounded-md border border-slate-300 bg-white px-2 py-1 font-medium text-slate-700`,children:`Cancel`})]})]})]})}function za({group:e,run:t}){let[n,r]=(0,c.useState)(!1),i=e.name||`this group`;return n?(0,u.jsxs)(`div`,{role:`alertdialog`,"aria-label":`Confirm group deletion`,className:`space-y-2 rounded-lg border border-red-300 bg-red-50 p-3 text-xs text-red-900`,children:[(0,u.jsxs)(`p`,{children:[`Delete `,(0,u.jsx)(`strong`,{children:i}),`? Everyone in it loses the access the group gave them, here and on anything shared with the group. This cannot be undone.`]}),(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>void t($.deleteEntity(e.entity_id)),className:`rounded-md bg-red-700 px-2 py-1 font-medium text-white`,children:`Delete group`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(!1),className:`rounded-md border border-slate-300 bg-white px-2 py-1 font-medium text-slate-700`,children:`Cancel`})]})]}):(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(!0),className:`rounded-md px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-50`,children:`Delete group`})}function Ba({roles:e}){return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Roles are defined by the installed apps. Grant them to people or groups from Members, Groups, or New users.`}),(0,u.jsx)(`ul`,{className:`space-y-3`,children:e.map(e=>(0,u.jsxs)(`li`,{className:`rounded-xl border border-slate-200 p-4`,children:[(0,u.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,u.jsx)(`span`,{className:`font-mono text-sm font-semibold text-slate-900`,children:e.name}),e.description&&(0,u.jsx)(`span`,{className:`text-sm text-slate-600`,children:e.description})]}),(0,u.jsx)(`ul`,{className:`mt-2 space-y-1 text-xs text-slate-600`,children:(e.permission_details??e.permissions.map(e=>({name:e,description:``}))).map(e=>(0,u.jsxs)(`li`,{children:[(0,u.jsx)(`span`,{className:`font-mono`,children:e.name}),e.description&&(0,u.jsxs)(`span`,{children:[` - `,e.description]})]},e.name))})]},e.name))})]})}function Va({deploymentId:e,groups:t,grants:n,roles:r,run:i}){let a=Y(e),[o,s]=(0,c.useState)([]),[l,d]=(0,c.useState)([]);(0,c.useEffect)(()=>{s(a?.new_user_group_ids??[]),d(a?.new_user_roles??[])},[a?.new_user_group_ids,a?.new_user_roles]);let f=(0,c.useMemo)(()=>n.find(e=>e.subject_id===`*`&&e.role===ka&&e.provenance===`direct`),[n]),p=(e,t)=>e.includes(t)?e.filter(e=>e!==t):[...e,t];return(0,u.jsxs)(`div`,{className:`space-y-6`,children:[(0,u.jsxs)(`label`,{className:`flex items-start gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:!!f,onChange:()=>void i(f?.grant_entity_id?$.revokeGrant(f.grant_entity_id):$.createGrant(e,`*`,ka)),className:`mt-0.5`}),(0,u.jsxs)(`span`,{children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-800`,children:`Everyone signed in is a member`}),(0,u.jsx)(`span`,{className:`block text-slate-500`,children:`Turn off to approve people yourself: new users can sign in but create nothing until they get a role, directly or through a group.`})]})]}),(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsx)(`h2`,{className:`text-sm font-semibold text-slate-800`,children:`Add new users to these groups`}),(0,u.jsx)(`p`,{className:`text-xs text-slate-500`,children:`Prefer a group when you may want to change what new users can do later, or give access to many people at once.`}),t.map(e=>(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:o.includes(e.entity_id),onChange:()=>s(p(o,e.entity_id))}),e.name||e.key]},e.entity_id))]}),(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsx)(`h2`,{className:`text-sm font-semibold text-slate-800`,children:`Give new users these roles directly`}),(0,u.jsx)(`p`,{className:`text-xs text-slate-500`,children:`Use a direct role for a one-off; it is granted to each person separately.`}),r.map(e=>(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:l.includes(e.name),onChange:()=>d(p(l,e.name))}),(0,u.jsx)(`span`,{className:`font-mono`,children:e.name}),e.description&&(0,u.jsx)(`span`,{className:`text-slate-500`,children:e.description})]},e.name))]}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>void i($.setNewUserDefaults(e,o,l)),className:`rounded-md bg-slate-900 px-3 py-2 text-sm font-medium text-white`,children:`Save new-user settings`})]})}function Ha(e=!0){let t=Gr(),[n,r]=(0,c.useState)(!1);return(0,c.useEffect)(()=>{if(!e||!t){r(!1);return}let n=!1;return K.getAccess(t).then(e=>{n||r(!!e?.can_manage)}).catch(()=>{n||r(!1)}),()=>{n=!0}},[t,e]),n}function Ua(e){return[{to:`/`,label:`home`},...e.map(e=>e.pattern).filter(e=>e!==`/`&&!e.includes(`{`)).map(e=>({to:e,label:e.slice(1)}))]}var Wa=({isActive:e})=>`rounded-md px-2.5 py-1 text-sm ${e?`bg-gray-900 text-white`:`text-gray-600 hover:bg-gray-100`}`,Ga=`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm hover:bg-gray-100`;function Ka({adminHref:e}){let{isAuthenticated:t,username:n,principalEntityId:r,logout:i}=Hr(),a=Ha(t),o=Y(r),[s,l]=(0,c.useState)(!1),[f,p]=(0,c.useState)(!1),m=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(!s)return;let e=e=>{m.current?.contains(e.target)||l(!1)},t=e=>e.key===`Escape`&&l(!1);return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[s]);let h=o?.username||n||`User`;return(0,u.jsxs)(`div`,{ref:m,className:`relative`,children:[(0,u.jsxs)(`button`,{type:`button`,"aria-haspopup":`menu`,"aria-expanded":s,onClick:()=>l(e=>!e),className:`flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100`,children:[h,(0,u.jsx)(ri,{className:`h-2.5 w-2.5 text-gray-400`})]}),s&&(0,u.jsxs)(`div`,{role:`menu`,className:`absolute right-0 z-50 mt-1 w-64 rounded-lg border border-gray-200 bg-white p-1 shadow-lg`,children:[r&&(0,u.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:async()=>{if(r)try{await navigator.clipboard.writeText(r),p(!0),setTimeout(()=>p(!1),2e3)}catch(e){console.error(`Failed to copy user entity ID:`,e)}},title:`Copy user entity ID`,className:Ga,children:[f?(0,u.jsx)(ii,{className:`h-3 w-3 shrink-0 text-green-600`}):(0,u.jsx)(ni,{className:`h-3 w-3 shrink-0 text-gray-500`}),(0,u.jsx)(`span`,{className:`truncate font-mono text-xs text-gray-600`,children:r})]}),a&&(0,u.jsxs)(d.Link,{to:e,role:`menuitem`,onClick:()=>l(!1),className:`${Ga} text-gray-700`,children:[(0,u.jsx)(Zr,{className:`h-3.5 w-3.5 text-gray-500`}),`Admin`]}),(0,u.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:i,className:`${Ga} text-red-600 hover:bg-red-50`,children:[(0,u.jsx)($r,{className:`h-3.5 w-3.5`}),`Logout`]})]})]})}var qa=({title:e=`graphcore`,places:t,className:n=``,adminHref:r=Da})=>{let{isAuthenticated:i}=Hr(),a=Bi();if(!i)return null;let o=Ua(a??[]),s=t===!1?[]:Array.isArray(t)?t:t?t(o):o;return(0,u.jsxs)(`div`,{className:`flex items-center gap-4 border-b border-gray-200 bg-white px-4 py-2 ${n}`,children:[(0,u.jsx)(`h1`,{className:`text-sm font-semibold tracking-tight text-gray-900`,children:e}),s.length>0&&(0,u.jsx)(`nav`,{"aria-label":`Places`,className:`flex items-center gap-1`,children:s.map(e=>(0,u.jsx)(d.NavLink,{to:e.to,end:e.to===`/`,className:Wa,children:e.label},e.to))}),(0,u.jsx)(`div`,{className:`ml-auto`,children:(0,u.jsx)(Ka,{adminHref:r})})]})},Ja=({entityTypeId:e,className:t=`w-4 h-4`,size:n})=>{let r=Bn(e);return c.default.createElement(r,{className:t,size:n})},Ya={light:{wrapper:`border border-gray-200 bg-white shadow-xs`,input:`border-gray-200 bg-white text-gray-900 placeholder:text-gray-400 focus:border-blue-400 focus:ring-blue-100`,icon:`text-gray-400`,list:`border border-gray-200 bg-gray-50/70`,option:`border-transparent text-gray-700 hover:border-blue-200 hover:bg-blue-50`,optionActive:`border-blue-200 bg-blue-50 text-blue-900 shadow-xs`,optionMeta:`text-gray-400`,optionMetaActive:`text-blue-500`,empty:`text-gray-500`},dark:{wrapper:`border border-gray-700 bg-gray-800 shadow-xs`,input:`border-gray-600 bg-gray-700 text-white placeholder:text-gray-400 focus:border-blue-500 focus:ring-blue-500/20`,icon:`text-gray-400`,list:`border border-gray-700 bg-gray-900/50`,option:`border-transparent text-gray-200 hover:border-blue-500/40 hover:bg-blue-500/10`,optionActive:`border-blue-500/40 bg-blue-500/15 text-white shadow-xs`,optionMeta:`text-gray-400`,optionMetaActive:`text-blue-300`,empty:`text-gray-400`}},Xa=({availableViewTypes:e,selectedValue:t,onSelect:n,theme:r=`light`,placeholder:i=`Search view types...`,autoFocus:a=!1})=>{let[o,s]=(0,c.useState)(``),l=Ya[r]||Ya.light,d=(0,c.useMemo)(()=>Object.entries(e||{}),[e]),f=(0,c.useMemo)(()=>{let e=o.trim().toLowerCase();return e?d.filter(([t,n])=>String(n).toLowerCase().includes(e)||t.toLowerCase().includes(e)):d},[o,d]);return(0,u.jsxs)(`div`,{className:`rounded-xl p-3 ${l.wrapper}`,children:[(0,u.jsxs)(`div`,{className:`relative`,children:[(0,u.jsx)(ei,{className:`absolute left-3 top-1/2 -translate-y-1/2 ${l.icon}`}),(0,u.jsx)(`input`,{type:`text`,value:o,onChange:e=>s(e.target.value),placeholder:i,className:`w-full rounded-lg border py-2.5 pl-10 pr-3 text-sm outline-hidden transition focus:ring-4 ${l.input}`,autoFocus:a})]}),(0,u.jsx)(`div`,{className:`mt-3 max-h-64 overflow-y-auto rounded-xl p-2 ${l.list}`,children:f.length>0?(0,u.jsx)(`div`,{className:`space-y-2`,children:f.map(([e,r])=>{let i=t===e;return(0,u.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:`flex w-full items-start justify-between rounded-lg border px-3 py-2.5 text-left transition ${i?l.optionActive:l.option}`,children:[(0,u.jsxs)(`span`,{className:`min-w-0`,children:[(0,u.jsx)(`span`,{className:`block truncate text-sm font-medium`,children:String(r)}),(0,u.jsx)(`span`,{className:`mt-0.5 block truncate text-xs ${i?l.optionMetaActive:l.optionMeta}`,children:e})]}),i&&(0,u.jsx)(ii,{className:`ml-3 mt-0.5 shrink-0 text-xs`})]},e)})}):(0,u.jsx)(`div`,{className:`px-3 py-6 text-center text-sm ${l.empty}`,children:`No view types match your search.`})})]})};function Za(e){let t=pa(),{sendStrategyRequest:n}=Z(),r=(0,c.useRef)(e);r.current=e;let i=t?.view?.state,a=(0,c.useMemo)(()=>({...r.current,...i&&typeof i==`object`&&!Array.isArray(i)?i:{}}),[i]),o=t?.view?.entity_id??null,s=t?.position??null;return[a,(0,c.useCallback)((e,t)=>{if(!o&&!s)return Promise.resolve(void 0);let r={position:s?la(s):void 0,state:e};t!==void 0&&(r.component=t);let i=Promise.resolve(n($.setViewState(o,r),{awaitResponse:!0}));return i.catch(()=>void 0),i},[s,n,o])]}function Qa(){let{sendStrategyRequest:e}=Z();return(0,c.useCallback)(async(t={})=>{try{return(await e($.createView(null,t),{awaitResponse:!0}))?.view_entity_id??null}catch{return null}},[e])}function $a(){(0,c.useEffect)(()=>{$i()},[]);let e=na().contents;return(0,c.useMemo)(()=>Object.keys(e).filter(e=>e!==J.VIEW).sort(),[e])}var eo=[{key:`entity_ide`,label:`Entity IDE`,icon:Pn,state:{sidebar_config:{allow_create:!0}}}],to=`flex min-w-0 flex-col items-center gap-2 rounded-xl border border-gray-200 bg-white p-5 text-center shadow-xs transition-colors`;function no({viewId:e,onRemove:t}){let n=(0,d.useNavigate)(),r=Xr(),i=Y(e),a=I(t=>t.notFoundEntityIds.has(e)),o=a||i?.forbidden,s=typeof i?.component==`string`?i.component:null,c=o?a?`View not found`:`No access`:i&&Rr(i,`name`)||s&&r.get(s)?.label||s||`View`;return(0,u.jsxs)(`div`,{className:`group relative`,children:[(0,u.jsxs)(`button`,{type:`button`,disabled:!!o,onClick:()=>n(di(e)),className:`${to} w-full hover:border-blue-300 hover:shadow-md disabled:cursor-default disabled:opacity-60`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 text-blue-600`,children:(0,u.jsx)(Ja,{entityTypeId:i?.entity_type_id,className:`h-5 w-5`})}),(0,u.jsx)(`span`,{className:`line-clamp-2 w-full break-words text-sm font-medium text-gray-900`,children:c})]}),(0,u.jsx)(`button`,{type:`button`,title:`Remove from gallery`,onClick:t,className:`absolute right-1 top-1 rounded-sm p-0.5 text-gray-400 opacity-0 hover:text-gray-700 group-hover:opacity-100`,children:(0,u.jsx)(Fn,{className:`h-4 w-4`})})]})}function ro(){let e=(0,d.useNavigate)(),t=Xr(),[{views:n},r]=Za({views:[]}),i=Qa(),a=Pr(n),o=(0,c.useRef)(n),s=(0,c.useRef)(n);(0,c.useEffect)(()=>{o.current=n,s.current=n},[n]);let l=$a(),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useMemo)(()=>{let e=new Set(a.filter(e=>eo.some(t=>t.key===e.component)).map(e=>e.entity_id));return n.filter(t=>!e.has(t))},[n,a]),S=(0,c.useMemo)(()=>Object.fromEntries(t.keys().map(e=>[e,t.get(e).label])),[t]),C=async e=>{s.current=e;try{await r({views:e})}catch(e){throw s.current=o.current,e}},w=async(e,t)=>{if(y)return null;b(e);try{let e=await i(t);return e&&await C([...s.current,e]),e}catch{return null}finally{b(null)}},T=e=>void C(s.current.filter(t=>t!==e)).catch(()=>void 0),E=async t=>{let n=a.find(e=>e.component===t);if(n){e(di(n.entity_id));return}let r=eo.find(e=>e.key===t),i=await w(t,{component:t,state:r?.state??{}});i&&e(di(i))},D=()=>{m(!1),g(``),v(null)};return(0,u.jsxs)(`div`,{className:`h-full overflow-y-auto bg-gray-50 p-6`,children:[(0,u.jsxs)(`div`,{className:`mb-6`,children:[(0,u.jsx)(`h1`,{className:`text-2xl font-bold text-gray-900`,children:`My Views`}),(0,u.jsx)(`p`,{className:`text-gray-600`,children:`Select a view to explore your data`})]}),(0,u.jsxs)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-4`,children:[eo.map(e=>{let t=e.icon,n=y===e.key;return(0,u.jsxs)(`button`,{type:`button`,onClick:()=>E(e.key),disabled:n,className:`flex flex-col items-center gap-2 rounded-xl border border-gray-200 bg-white p-5 text-center shadow-xs transition-colors hover:border-blue-300 hover:shadow-md disabled:cursor-wait`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100 text-blue-600`,children:n?(0,u.jsx)(xn,{className:`h-5 w-5 animate-spin`}):(0,u.jsx)(t,{className:`h-5 w-5`})}),(0,u.jsx)(`span`,{className:`truncate text-sm font-medium text-gray-900`,children:e.label}),(0,u.jsx)(`span`,{className:`text-xs text-gray-500`,children:n?`Creating…`:`Quick start view`})]},e.key)}),x.map(e=>(0,u.jsx)(no,{viewId:e,onRemove:()=>T(e)},e)),(0,u.jsxs)(`button`,{type:`button`,onClick:()=>m(!0),className:`flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-gray-300 p-5 text-center text-gray-500 transition-colors hover:border-blue-400 hover:text-blue-600`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-lg bg-gray-100`,children:(0,u.jsx)(Ln,{className:`h-5 w-5`})}),(0,u.jsx)(`span`,{className:`text-sm font-medium`,children:`New View`})]})]}),p&&(0,f.createPortal)((0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:D}),(0,u.jsxs)(`div`,{className:`relative w-full max-w-sm space-y-3 rounded-xl border border-gray-200 bg-white p-4 shadow-2xl`,onClick:e=>e.stopPropagation(),children:[(0,u.jsx)(`h3`,{className:`text-sm font-semibold text-gray-900`,children:`Create a new view`}),(0,u.jsx)(Xa,{availableViewTypes:S,selectedValue:h,onSelect:g,theme:`light`,autoFocus:!0}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{className:`mb-1 text-xs font-medium text-gray-500`,children:[`Shows `,_?X(_):`no entity`]}),l.length>0&&(0,u.jsx)(xa,{typeIds:l,onPick:v,placeholder:`Pick an entity (optional)…`},l.join(`,`))]}),(0,u.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:D,className:`rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50`,children:`Cancel`}),(0,u.jsx)(`button`,{type:`button`,onClick:async()=>{(h||_)&&(await w(`custom`,{component:h||null,renders:_?.entity_id??null}),D())},disabled:!h&&!_||y!==null,className:`rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400`,children:`Create`})]})]})]}),document.body)]})}var io=va(`view_gallery`,ro,{entry:!0}),ao=e=>e.replace(/(^|-)\w/g,e=>e.toUpperCase());function oo({entityId:e,sendStrategyRequest:t,className:n=``}){let r=Ea(e,t),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)({}),{summary:l}=r,d=i||r.roles[0]?.name;if(r.loading)return(0,u.jsx)(`div`,{className:`min-h-[28rem] p-6 text-sm text-slate-500 ${n}`,children:`Loading access…`});if(r.error)return(0,u.jsx)(`div`,{className:`min-h-[28rem] p-6 text-sm text-red-600 ${n}`,role:`alert`,children:r.error});if(!l||!r.shareable)return null;let f=r.publicPermissions.includes(`Read`),p=async()=>{s({busy:!0});try{let{token:t}=await K.createInvite(e,d);s({url:Pi(t)})}catch(e){s({error:e?.message||`Unable to create invite link`})}};return(0,u.jsxs)(`section`,{className:`graphcore-access-panel min-h-[28rem] space-y-6 p-6 ${n}`,children:[(0,u.jsxs)(`div`,{className:`flex min-h-5 items-center justify-between gap-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Choose who can view this and what they can do with it.`}),r.busy&&(0,u.jsx)(`span`,{className:`shrink-0 text-xs font-medium text-slate-400`,"aria-live":`polite`,children:`Saving…`})]}),f&&(0,u.jsx)(`p`,{className:`rounded-lg bg-blue-50 px-4 py-3 text-sm text-blue-800`,children:`Public read is enabled by application policy.`}),r.canManage?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`label`,{className:`flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm font-medium text-slate-800`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:!!r.publicGrant||f,disabled:r.busy||f,onChange:()=>void(r.publicGrant?r.revokePublicRead():r.setPublicRead()),className:`h-4 w-4 rounded border-slate-300 text-slate-900 focus:ring-slate-500`}),(0,u.jsx)(`span`,{children:`Anyone signed in can view`})]}),(0,u.jsx)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:r.grants.map(e=>(0,u.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 px-4 py-3 text-sm`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:r.labelsById[e.subject_id]??e.subject_id}),(0,u.jsx)(`span`,{className:`text-xs text-slate-500`,children:e.provenance}),e.provenance===`direct`&&e.grant_entity_id&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`select`,{value:e.role,disabled:r.busy,onChange:t=>void r.changeRole(e.grant_entity_id,t.target.value),className:`ml-auto rounded-md border border-slate-300 bg-white px-2 py-1 text-sm text-slate-700`,children:r.roles.map(e=>(0,u.jsx)(`option`,{value:e.name,children:ao(e.name)},e.name))}),(0,u.jsx)(`button`,{type:`button`,disabled:r.busy,onClick:()=>void r.revoke(e.grant_entity_id),className:`rounded-md px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-50`,children:`Revoke`})]})]},`${e.subject_id}-${e.provenance}`))}),(0,u.jsxs)(`div`,{className:`space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-4`,children:[(0,u.jsx)(`select`,{className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm`,value:d??``,disabled:r.busy,onChange:e=>a(e.target.value),children:r.roles.map(e=>(0,u.jsx)(`option`,{value:e.name,children:ao(e.name)},e.name))}),r.subjectTypeIds.length>0&&(0,u.jsx)(xa,{typeIds:r.subjectTypeIds,exclude:r.grants.map(e=>e.subject_id),labelFor:r.subjectLabel,disabled:r.busy||!d,placeholder:`Share with a person or group…`,onPick:e=>void r.grant(e.entity_id,d)}),r.invitable&&(0,u.jsx)(`button`,{type:`button`,disabled:r.busy||o.busy||!d,onClick:()=>void p(),className:`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100`,children:`Create invite link`}),o.url&&(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`input`,{readOnly:!0,"aria-label":`Invite link`,value:o.url,onFocus:e=>e.target.select(),className:`min-w-0 flex-1 rounded-md border border-slate-300 bg-white px-3 py-2 text-xs text-slate-700`}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>void navigator.clipboard?.writeText(o.url),className:`rounded-md bg-slate-900 px-3 py-2 text-xs font-semibold text-white`,children:`Copy`})]}),o.url&&(0,u.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[`Single use, expires in 7 days. Shown once; anyone with it can join as `,ao(d),`.`]}),o.error&&(0,u.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:o.error})]})]}):(0,u.jsx)(`p`,{className:`rounded-lg bg-slate-50 px-4 py-3 text-sm text-slate-600`,children:`Only people who can manage access can see who has access.`})]})}function so({path:e,component:t}){if(typeof e!=`string`||!e.startsWith(`/`))throw Error(`definePage: path must start with "/", got ${JSON.stringify(e)}`);if(!t)throw Error(`definePage: ${e} has no component`);return Object.freeze({kind:`graphcore.page`,path:lo(e),component:t})}function co(e){return typeof e==`object`&&!!e&&e.kind===`graphcore.page`}function lo(e){return e.length>1?e.replace(/\/+$/,``):e}function uo(e){let t=new Map;for(let{app:n,exports:r}of e)for(let e of Object.values(r))for(let r of(Array.isArray(e)?e:[e]).filter(co)){let e=t.get(r.path);if(e)throw Error(`Pages from "${e.app}" and "${n}" both claim the path "${r.path}"`);t.set(r.path,{page:r,app:n})}return[...t.values()].map(({page:e})=>e)}function fo(e){return e==null||e===``?`Empty`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e,null,2)}function po(e){if(typeof e!=`string`)return null;try{let t=new URL(e);if(t.protocol===`http:`||t.protocol===`https:`)return e}catch{return null}return null}function mo(e){let t=po(e);return t?(0,u.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,className:`text-blue-600 underline break-all hover:text-blue-700`,children:t}):fo(e)}function ho({entityId:e}){let t=Y(e),n=X(t),r=Br(t),i=Object.entries(Lr(t));return(0,u.jsxs)(`div`,{className:`bg-white text-gray-900 border border-gray-200 rounded-xl shadow-xs overflow-hidden`,children:[(0,u.jsxs)(`div`,{className:`px-5 py-4 border-b border-gray-200`,children:[(0,u.jsx)(`div`,{className:`text-xs font-medium uppercase tracking-wide text-gray-500`,children:r}),(0,u.jsx)(`h2`,{className:`mt-1 text-xl font-semibold text-gray-900`,children:n})]}),(0,u.jsx)(`div`,{className:`p-5`,children:i.length===0?(0,u.jsx)(`div`,{className:`text-sm text-gray-500`,children:`No additional attributes.`}):(0,u.jsx)(`dl`,{className:`space-y-3`,children:i.map(([e,t])=>(0,u.jsxs)(`div`,{className:`rounded-lg border border-gray-200 bg-gray-50 p-3`,children:[(0,u.jsx)(`dt`,{className:`text-xs font-medium uppercase tracking-wide text-gray-500`,children:e}),(0,u.jsx)(`dd`,{className:`mt-1 whitespace-pre-wrap wrap-break-word text-sm text-gray-900`,children:mo(t)})]},e))})})]})}var go=(0,c.createContext)([]);function _o(){return(0,c.useContext)(go)}function vo({token:e,children:t}){let n=_o(),r=(0,c.useMemo)(()=>e?[...n,e]:n,[n,e]);return(0,u.jsx)(go.Provider,{value:r,children:t})}var yo=class extends c.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`Visualization error:`,e,t)}render(){return this.state.hasError?typeof this.props.fallback==`function`?this.props.fallback(this.state.error):this.props.fallback||(0,u.jsx)(`div`,{className:`p-4 text-red-500 border border-red-300 rounded-sm bg-red-50`,children:`Something went wrong with this visualization.`}):this.props.children}};function bo({className:e=``}){return(0,u.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#16161e] select-none ${e}`,children:(0,u.jsxs)(`div`,{className:`flex flex-col items-center gap-2 px-6 py-5 rounded-xl bg-[#1e1e26] border border-white/10`,children:[(0,u.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`text-gray-500`,children:[(0,u.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`,ry:`2`}),(0,u.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),(0,u.jsx)(`span`,{className:`text-xs font-medium text-gray-500`,children:`No permission`})]})})}var xo=[],So=(0,c.createContext)(xo),Co=()=>(0,c.useContext)(So);function wo(e,t,n){return t&&e.get(t)?t:n?e.defaultViewFor(n):null}function To({label:e}){return(0,u.jsxs)(`div`,{className:`flex items-center justify-center p-4 text-gray-400`,children:[(0,u.jsx)(`div`,{className:`mr-2 h-5 w-5 animate-spin rounded-full border-b-2 border-gray-400`}),(0,u.jsx)(`span`,{children:e})]})}function Eo({cause:e,className:t=``}){return e===`forbidden`?(0,u.jsx)(bo,{className:t}):(0,u.jsx)(`div`,{className:`flex h-full w-full items-center justify-center p-4 text-xs font-medium text-gray-500 ${t}`,children:`Entity not found`})}function Do(){let e=Xr();return(0,c.useMemo)(()=>Object.fromEntries(e.keys().map(t=>[t,e.get(t).label])),[e])}function Oo({current:e}){let[,t]=Za({}),n=Do(),[r,i]=(0,c.useState)(!1);return(0,u.jsxs)(`div`,{className:`pointer-events-none absolute bottom-1 right-1 z-10`,children:[(0,u.jsx)(`button`,{type:`button`,title:`Change view`,onClick:()=>i(e=>!e),className:`rounded-sm border border-gray-200 bg-white/90 px-1.5 text-xs text-gray-500 shadow-xs transition-opacity hover:text-gray-900 group-hover:pointer-events-auto group-hover:opacity-100 ${r?`pointer-events-auto opacity-100`:`opacity-0`}`,children:`⋯`}),r&&(0,u.jsx)(`div`,{className:`pointer-events-auto absolute bottom-full right-0 mb-1 w-64 nodrag`,children:(0,u.jsx)(Xa,{availableViewTypes:n,selectedValue:e??``,onSelect:e=>{i(!1),t({},e)},theme:`light`,placeholder:`Search views...`,autoFocus:!0})})]})}function ko(){let[,e]=Za({}),t=Do();return(0,u.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,u.jsx)(`h3`,{className:`text-sm font-semibold text-gray-900`,children:`Choose a view`}),(0,u.jsx)(Xa,{availableViewTypes:t,selectedValue:``,onSelect:t=>void e({},t),theme:`light`,placeholder:`Search views...`})]})}function Ao({name:e,entityId:t,className:n}){let r=Xr(),i=_o(),a=`${t??``}:${e??``}`;if(i.includes(a))return(0,u.jsx)(`div`,{className:`rounded-sm border border-amber-200 bg-amber-50 p-4 text-amber-700`,children:`Recursive view render blocked to prevent infinite loop.`});let o=e&&r.get(e)?.Component||ho;return(0,u.jsx)(vo,{token:a,children:(0,u.jsxs)(`div`,{className:`group relative h-full min-h-0 ${n??``}`,children:[(0,u.jsx)(Oo,{current:e}),(0,u.jsx)(yo,{fallback:e=>(0,u.jsxs)(`div`,{className:`rounded-sm border border-red-200 bg-red-50 p-4 text-red-600`,children:[(0,u.jsx)(`div`,{className:`font-semibold`,children:`Error rendering view`}),(0,u.jsx)(`div`,{className:`mt-1 text-sm`,children:e?.message||`Unknown error`})]}),children:(0,u.jsx)(o,{entityId:t})})]})})}function jo({entity:e,slot:t,className:n}){let r=ha(t??`entity`,e.entity_id);return(0,u.jsx)(ga,{position:r,children:(0,u.jsx)(Mo,{entity:e,className:n})})}function Mo({entity:e,className:t}){let n=Xr(),r=pa()?.view;if(r===void 0)return(0,u.jsx)(To,{label:`Loading view…`});let i=wo(n,typeof r?.component==`string`?r.component:null,e.entity_type_id);return(0,u.jsx)(Ao,{name:i,entityId:e.entity_id,className:t})}function No({view:e,className:t}){let n=Xr(),r=(0,c.useMemo)(()=>sa(e.entity_id),[e.entity_id]),i=sr(r)??e,a=typeof i.renders==`string`?i.renders:null,o=Y(a),s=I(e=>a?e.notFoundEntityIds.has(a):!1),l=(0,c.useMemo)(()=>({position:r,view:i}),[r,i]),d;if(o?.forbidden)d=(0,u.jsx)(Eo,{cause:`forbidden`,className:t});else if(s)d=(0,u.jsx)(Eo,{cause:`not_found`,className:t});else if(a&&!o)d=(0,u.jsx)(To,{label:`Loading entity…`});else{let e=wo(n,typeof i.component==`string`?i.component:null,o?.entity_type_id);d=!e&&!a?(0,u.jsx)(ko,{}):(0,u.jsx)(Ao,{name:e,entityId:a,className:t})}return(0,u.jsx)(vo,{token:`view:${i.entity_id}`,children:(0,u.jsx)(ua.Provider,{value:l,children:d})})}function Po({entityKey:e,slot:t,className:n}){let{entityId:r,notFound:i}=Nr(e);return i?(0,u.jsx)(Eo,{cause:`not_found`,className:n}):r?(0,u.jsx)(Fo,{entityId:r,slot:t,className:n}):(0,u.jsx)(To,{label:`Loading entity…`})}function Fo({entityId:e,slot:t,className:n}){let r=Y(e),i=I(t=>e?t.notFoundEntityIds.has(e):!1),a=_o();return e?r?.forbidden?(0,u.jsx)(Eo,{cause:`forbidden`,className:n}):i?(0,u.jsx)(Eo,{cause:`not_found`,className:n}):r?r.entity_type_id===J.VIEW?a.includes(`view:${r.entity_id}`)?(0,u.jsx)(`div`,{className:`rounded-sm border border-amber-200 bg-amber-50 p-4 text-amber-700`,children:`Recursive view render blocked to prevent infinite loop.`}):(0,u.jsx)(No,{view:r,className:n}):(0,u.jsx)(jo,{entity:r,slot:t,className:n}):(0,u.jsx)(To,{label:`Loading entity…`}):null}function Io({entityId:e,entityKey:t,context:n,slot:r,className:i}){return(0,u.jsx)(So.Provider,{value:n??xo,children:t?(0,u.jsx)(Po,{entityKey:t,slot:r,className:i}):(0,u.jsx)(Fo,{entityId:e,slot:r,className:i})})}var Lo=()=>{let e=fi((0,d.useParams)()),t=(0,d.useNavigate)(),{pathname:n}=(0,d.useLocation)(),{isAuthenticated:r}=Hr(),{isConnected:i}=Z();return r?i?(0,u.jsx)(`div`,{className:`h-full min-h-0`,children:(0,u.jsx)(Ei,{address:n,children:(0,u.jsx)(_a,{address:n,children:(0,u.jsx)(Io,{entityId:e,className:`h-full`})})})}):(0,u.jsx)(`div`,{className:`h-full flex items-center justify-center bg-gray-50 text-gray-500`,children:(0,u.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,u.jsx)(`div`,{className:`animate-spin rounded-full h-6 w-6 border-b-2 border-gray-400`}),(0,u.jsx)(`span`,{children:`Connecting to server…`})]})}):(0,u.jsx)(`div`,{className:`h-full flex items-center justify-center bg-gray-50`,children:(0,u.jsxs)(`div`,{className:`max-w-lg p-8 bg-white rounded-lg border border-gray-200 text-center`,children:[(0,u.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900 mb-2`,children:`Authentication Required`}),(0,u.jsx)(`p`,{className:`text-gray-600 mb-6`,children:`You need to be logged in to view this entity.`}),(0,u.jsx)(`button`,{onClick:()=>t(`/`),className:`px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors`,children:`Go to Home`})]})})},Ro=()=>{let{pathname:e}=(0,d.useLocation)(),t=pi(e);return(0,u.jsx)(d.Navigate,{to:t?di(t):`/`,replace:!0})},zo=new Set([`/`,`/e/{entity}`]),Bo=e=>e.replace(`{entity}`,`:entityBackend/:entityLocal`);function Vo({viewName:e}){let{pathname:t}=(0,d.useLocation)(),{entityBackend:n,entityLocal:r}=(0,d.useParams)(),i=Xr(),a=n&&r?`gc://${n}/${r}`:null,o=i.get(e)??(e===`home`?i.get(io.viewName):void 0),s;return s=o?(0,u.jsx)(o,{entityId:a}):a?(0,u.jsx)(Io,{entityId:a,className:`h-full`}):(0,u.jsxs)(`div`,{className:`p-6 text-sm text-gray-500`,children:[`No view "`,e,`" is available for `,t]}),(0,u.jsx)(Ei,{address:t,children:(0,u.jsx)(_a,{address:t,children:(0,u.jsx)(`div`,{className:`h-full min-h-0`,children:s})})})}function Ho({fallback:e=null}){let t=Bi();return(0,u.jsxs)(d.Routes,{children:[(0,u.jsx)(d.Route,{index:!0,element:(0,u.jsx)(Vo,{viewName:`home`})}),(t??[]).filter(e=>!zo.has(e.pattern)).map(e=>(0,u.jsx)(d.Route,{path:Bo(e.pattern),element:(0,u.jsx)(Vo,{viewName:e.view_name})},e.pattern)),(0,u.jsx)(d.Route,{path:`*`,element:t?e:null})]})}function Uo({topBar:e=(0,u.jsx)(qa,{})}){let{isAuthenticated:t,principalEntityId:n}=Hr();return!t||!n?(0,u.jsx)(Ri,{}):(0,u.jsxs)(d.Routes,{children:[(0,u.jsx)(d.Route,{path:ci,element:(0,u.jsx)(`div`,{className:`h-screen w-screen overflow-hidden bg-gray-50`,children:(0,u.jsx)(Lo,{})})}),(0,u.jsxs)(d.Route,{path:`/*`,element:(0,u.jsxs)(`div`,{className:`h-screen w-screen overflow-hidden bg-gray-50 flex flex-col`,children:[e,(0,u.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,u.jsx)(d.Outlet,{})})]}),children:[(0,u.jsx)(d.Route,{path:Da.slice(1),element:(0,u.jsx)(`div`,{className:`h-full overflow-auto`,children:(0,u.jsx)(Ma,{})})}),(0,u.jsx)(d.Route,{path:Ni.slice(1),element:(0,u.jsx)(Li,{})}),(0,u.jsx)(d.Route,{path:`*`,element:(0,u.jsx)(Ho,{fallback:(0,u.jsx)(Ro,{})})})]})]})}var Wo=[`/admin`,`/auth/callback`];function Go(e){return e.split(`/`).filter(Boolean).flatMap(e=>e===`{entity}`?[null,null]:e===`*`?[`*`]:e.startsWith(`:`)?[null]:[e])}function Ko(e,t){for(let n=0;;n+=1){if(e[n]===`*`||t[n]===`*`)return!0;if(n>=e.length||n>=t.length)return e.length===t.length;if(e[n]!==null&&t[n]!==null&&e[n]!==t[n])return!1}}function qo(e,t,n){if(n)return[];let r=[...t,...Wo,`/e/{entity}`],i=[];for(let t of e)for(let e of r)Ko(Go(t.path),Go(e))&&i.push({page:t.path,route:e});return i}function Jo(){let[e,t]=(0,c.useState)(()=>window.location.pathname);return(0,c.useEffect)(()=>{let e=()=>t(window.location.pathname);return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[]),e}function Yo(e,t){return e===t||e.startsWith(`${t}/`)}function Xo({pages:e,basePath:t}){let n=Bi();return(0,c.useEffect)(()=>{if(!n)return;let r=qo(e,n.map(e=>e.pattern),t);if(!r.length)return;let i=r.map(({page:e,route:t})=>`page ${e} hides ${t}`).join(`; `);console.error(`GraphCore: pages collide with app routes: ${i}. Mount the app under a basePath.`),Hn({message:`Pages collide with app routes: ${i}`,type:`error`})},[n,e,t]),null}function Zo(){return(0,u.jsx)(`div`,{className:`p-8 text-sm text-gray-500`,children:`Page not found.`})}function Qo({registry:e,pages:t=[],config:n,basePath:r,app:i=(0,u.jsx)(Uo,{}),notFound:a=(0,u.jsx)(Zo,{})}){let o=v(r);y(o);let s=Jo(),c=(0,u.jsxs)(ji,{...n,registry:e,basePath:o,children:[(0,u.jsx)(Xo,{pages:t,basePath:o}),i]});return o&&Yo(s,o)?(0,u.jsx)(d.BrowserRouter,{basename:o,children:c}):(0,u.jsx)(d.BrowserRouter,{children:(0,u.jsxs)(d.Routes,{children:[t.map(e=>(0,u.jsx)(d.Route,{path:e.path,element:(0,u.jsx)(e.component,{})},e.path)),(0,u.jsx)(d.Route,{path:`*`,element:o?a:c})]})})}var $o=({attributeName:e,onConfirm:t,onCancel:n})=>(0,u.jsx)(`div`,{className:`fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50`,children:(0,u.jsxs)(`div`,{className:`bg-white border border-gray-200 rounded-xl p-6 shadow-2xl max-w-md w-full mx-4`,children:[(0,u.jsx)(`h3`,{className:`text-lg font-semibold text-gray-900 mb-4`,children:`Delete Attribute`}),(0,u.jsxs)(`p`,{className:`text-gray-600 mb-6`,children:[`Are you sure you want to delete the attribute `,(0,u.jsxs)(`span`,{className:`font-mono text-blue-600`,children:[`"`,e,`"`]}),`?`]}),(0,u.jsxs)(`div`,{className:`flex justify-end gap-3`,children:[(0,u.jsx)(`button`,{onClick:n,className:`px-4 py-2 bg-white border border-gray-200 hover:bg-gray-50 hover:border-gray-300 text-gray-700 rounded-lg transition-colors`,children:`Cancel`}),(0,u.jsx)(`button`,{onClick:t,className:`px-4 py-2 bg-red-50 border border-red-200 hover:bg-red-100 text-red-600 rounded-lg transition-colors font-medium`,children:`Delete`})]})]})}),es=({label:e,value:t,onUpdate:n,onDebounced:r})=>{let[i,a]=(0,c.useState)(()=>JSON.stringify(t,null,2)),[o,s]=(0,c.useState)(null);return(0,c.useEffect)(()=>{a(JSON.stringify(t,null,2))},[t]),(0,u.jsxs)(`div`,{className:`w-full`,children:[(0,u.jsx)(`textarea`,{"aria-label":e,value:i,onChange:e=>{a(e.target.value);try{let t=JSON.parse(e.target.value);s(null),r(t)}catch{s(`Invalid JSON`)}},onBlur:()=>{try{let e=JSON.parse(i);s(null),n(e)}catch{s(`Invalid JSON - not saved`)}},className:`w-full bg-white border ${o?`border-red-300`:`border-gray-300`} rounded-lg px-3 py-2 text-sm text-gray-900 font-mono focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-y min-h-[60px]`}),o&&(0,u.jsx)(`p`,{className:`text-xs text-red-600 mt-1`,children:o})]})},ts=({label:e,value:t,onUpdate:n,onDebounced:r})=>{let[i,a]=(0,c.useState)(t??``);return(0,c.useEffect)(()=>{a(t??``)},[t]),(0,u.jsx)(`input`,{type:`text`,"aria-label":e,value:i,onChange:e=>{a(e.target.value),r(e.target.value)},onBlur:e=>n(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),n(i))},className:`w-full bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`})},ns=({manifest:e})=>(0,u.jsx)(`span`,{className:`ml-2 rounded bg-slate-100 px-1.5 py-0.5 font-sans text-xs text-slate-600`,title:`Declared by manifest ${e}; only the apply on migrate writes it`,children:`declared`});function rs({entityId:e}){let{sendStrategyRequest:t}=Z();if(!e)throw Error(`This view needs an entity to show.`);let n=e,r=Y(n),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(``),[l,d]=(0,c.useState)(null),f=(0,c.useRef)(new Map);(0,c.useEffect)(()=>()=>{f.current.forEach(clearTimeout),f.current.clear()},[n]);let p=(0,c.useMemo)(()=>Object.entries(Lr(r)).map(([e,t])=>({key:e,value:t})).sort((e,t)=>e.key.localeCompare(t.key)),[r]),m=zr(r),h=ia(r?.key),g=e=>Object.prototype.hasOwnProperty.call(Lr(r),e),_=(0,c.useCallback)(e=>{let t=e.trim();if(t===``)return``;try{return JSON.parse(t)}catch{return e}},[]),v=(0,c.useCallback)((e,r)=>{if(!n)return;clearTimeout(f.current.get(e)),f.current.delete(e);let i=$.setAttributes(n,{[e]:r});t(i)},[n,t]),y=(0,c.useCallback)((e,t,n=300)=>{clearTimeout(f.current.get(e)),f.current.set(e,setTimeout(()=>v(e,t),n))},[v]),b=(0,c.useCallback)(e=>{n&&(clearTimeout(f.current.get(e)),f.current.delete(e),t($.removeAttribute(n,e)),d(null))},[n,t]),x=(0,c.useCallback)(()=>{let e=i.trim();if(!n||!e||Object.prototype.hasOwnProperty.call(Lr(r),e))return;let c=_(o),l=$.setAttributes(n,{[e]:c});t(l),a(``),s(``)},[n,i,o,_,t,r]),S=(0,c.useCallback)((e,t)=>{let n=typeof t;return n===`boolean`?(0,u.jsx)(`input`,{"aria-label":e,type:`checkbox`,checked:t,onChange:t=>v(e,t.target.checked),className:`w-5 h-5 bg-white border border-gray-300 rounded-sm focus:ring-2 focus:ring-blue-500`}):n===`number`?(0,u.jsx)(`input`,{"aria-label":e,type:`number`,defaultValue:t,onChange:t=>{let n=t.target.value===``?0:parseFloat(t.target.value);y(e,n)},onBlur:t=>{let n=t.target.value===``?0:parseFloat(t.target.value);v(e,n)},className:`w-full bg-white border border-gray-300 rounded-lg px-3 py-1.5 text-sm text-gray-900 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`}):n===`object`?(0,u.jsx)(es,{label:e,value:t,onUpdate:t=>v(e,t),onDebounced:t=>y(e,t,500)}):(0,u.jsx)(ts,{label:e,value:t,onUpdate:t=>v(e,t),onDebounced:t=>y(e,t)})},[v,y]);return r?(0,u.jsxs)(`div`,{className:`h-full flex flex-col bg-gray-50 text-gray-900 p-4`,children:[(0,u.jsxs)(`div`,{className:`mb-4`,children:[(0,u.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900`,children:`Entity Attributes`}),(0,u.jsxs)(`p`,{className:`text-sm text-gray-500 mt-1`,children:[`Entity ID: `,(0,u.jsx)(`span`,{className:`font-mono text-gray-700`,children:n})]})]}),(0,u.jsxs)(`section`,{"aria-label":`Fields`,className:`mb-4 overflow-auto rounded-lg border border-gray-200 bg-white p-4`,children:[(0,u.jsx)(`h3`,{className:`mb-3 font-semibold`,children:`Fields`}),(0,u.jsx)(`dl`,{className:`space-y-2`,children:Object.entries(m).map(([e,t])=>(0,u.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,u.jsxs)(`dt`,{className:`font-mono text-gray-600`,children:[e,h?.fields.includes(e)&&(0,u.jsx)(ns,{manifest:h.manifest})]}),(0,u.jsx)(`dd`,{className:`whitespace-pre-wrap break-all`,children:typeof t==`object`?JSON.stringify(t,null,2):String(t??``)})]},e))})]}),(0,u.jsxs)(`h3`,{className:`mb-2 font-semibold`,children:[`Attributes`,h?.fields.includes(`attributes`)&&(0,u.jsx)(ns,{manifest:h.manifest})]}),(0,u.jsx)(`div`,{role:`region`,"aria-label":`Attributes`,className:`flex-1 overflow-auto bg-white border border-gray-200 rounded-lg shadow-xs`,children:(0,u.jsxs)(`table`,{className:`w-full border-collapse`,children:[(0,u.jsx)(`thead`,{className:`sticky top-0 bg-white border-b border-gray-200`,children:(0,u.jsxs)(`tr`,{children:[(0,u.jsx)(`th`,{className:`text-left px-4 py-3 text-xs font-medium uppercase tracking-wide text-gray-500 w-1/3`,children:`Attribute Name`}),(0,u.jsx)(`th`,{className:`text-left px-4 py-3 text-xs font-medium uppercase tracking-wide text-gray-500`,children:`Value`}),(0,u.jsx)(`th`,{className:`text-center px-4 py-3 text-xs font-medium uppercase tracking-wide text-gray-500 w-20`,children:`Actions`})]})}),(0,u.jsx)(`tbody`,{children:p.length===0?(0,u.jsx)(`tr`,{children:(0,u.jsx)(`td`,{colSpan:3,className:`px-4 py-8 text-center text-gray-500`,children:`No attributes found`})}):p.map(({key:e,value:t})=>(0,u.jsxs)(`tr`,{className:`border-b border-gray-100 hover:bg-gray-50`,children:[(0,u.jsx)(`td`,{className:`px-4 py-3`,children:(0,u.jsx)(`code`,{className:`text-sm text-blue-600 font-mono`,children:e})}),(0,u.jsx)(`td`,{className:`px-4 py-3`,children:S(e,t)}),(0,u.jsx)(`td`,{className:`px-4 py-3 text-center`,children:(0,u.jsx)(`button`,{"aria-label":`Delete ${e}`,onMouseDown:e=>e.preventDefault(),onClick:()=>{clearTimeout(f.current.get(e)),f.current.delete(e),d(e)},className:`text-red-500 hover:text-red-600 transition-colors p-1 rounded-sm`,title:`Delete attribute`,children:(0,u.jsx)(`svg`,{className:`w-5 h-5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,u.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16`})})})})]},`${n}:${e}`))})]})}),(0,u.jsxs)(`div`,{className:`mt-4 pt-4 border-t border-gray-200`,children:[(0,u.jsx)(`h3`,{className:`text-sm font-medium text-gray-700 mb-3`,children:`Add New Attribute`}),(0,u.jsxs)(`div`,{className:`flex gap-3`,children:[(0,u.jsx)(`input`,{type:`text`,placeholder:`Attribute name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),x())},className:`flex-1 bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`}),(0,u.jsx)(`input`,{type:`text`,placeholder:`Value (JSON or string)`,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),x())},className:`flex-1 bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500`}),(0,u.jsx)(`button`,{onClick:x,disabled:!i.trim()||g(i.trim()),className:`px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-200 disabled:cursor-not-allowed text-white border border-blue-600 rounded-lg transition-colors font-medium`,children:`Add`})]}),(0,u.jsxs)(`p`,{className:`text-xs text-gray-500 mt-2`,children:[`Tip: Use JSON format for objects, arrays, booleans, or numbers (e.g., `,(0,u.jsx)(`code`,{className:`text-gray-600`,children:`true`}),`, `,(0,u.jsx)(`code`,{className:`text-gray-600`,children:`42`}),`, `,(0,u.jsx)(`code`,{className:`text-gray-600`,children:`{"key": "value"}`}),`)`]})]}),l&&(0,u.jsx)($o,{attributeName:l,onConfirm:()=>b(l),onCancel:()=>d(null)})]}):(0,u.jsx)(`div`,{className:`flex items-center justify-center h-full bg-gray-50 text-gray-600 p-4`,children:(0,u.jsxs)(`div`,{className:`text-center`,children:[(0,u.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-4`}),(0,u.jsx)(`div`,{children:`Loading entity...`})]})})}var is=va(`entity_attributes`,e=>(0,u.jsx)(rs,{...e},e.entityId)),as=e=>`${e.slot??``}@${e.entityId}`;function os(e,t){let n=new Set(e.filter(e=>e.entityId===t).map(e=>e.slot));if(!n.has(void 0))return;let r=2;for(;n.has(`panel${r}`);)r+=1;return`panel${r}`}function ss(e){let[t,n]=Za(e),r=t.panels;return{state:t,update:n,panels:r,addPanel:(0,c.useCallback)(e=>{let t={entityId:e},i=os(r,e);return i&&(t.slot=i),n({panels:[...r,t]})},[r,n]),removePanel:(0,c.useCallback)(e=>{let i={...t.sizes};return delete i[e],n({panels:r.filter(t=>as(t)!==e),sizes:i})},[r,t.sizes,n])}}function cs({onPick:e}){let t=$a(),[n,r]=(0,c.useState)(!1);return(0,u.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,u.jsx)(`button`,{type:`button`,title:`Add panel`,onClick:()=>r(e=>!e),className:`flex h-7 w-7 items-center justify-center rounded-sm text-gray-500 hover:bg-gray-200 hover:text-gray-900`,children:(0,u.jsx)(Ln,{className:`h-4 w-4`})}),n&&t.length>0&&(0,u.jsx)(`div`,{className:`absolute right-0 z-20 mt-1 w-72 rounded-lg border border-gray-200 bg-white p-2 shadow-lg nodrag`,children:(0,u.jsx)(xa,{typeIds:t,onPick:t=>{r(!1),e(t.entity_id)},placeholder:`Add an entity…`,autoFocus:!0,listPlacement:`below`},t.join(`,`))})]})}function ls({onClick:e}){return(0,u.jsx)(`span`,{role:`button`,title:`Remove panel`,className:`shrink-0 rounded-sm p-0.5 opacity-60 hover:bg-gray-200 hover:opacity-100`,onClick:e,children:(0,u.jsx)(Fn,{className:`h-3.5 w-3.5`})})}var us={panels:[],sizes:{}};function ds({direction:e}){let{state:t,panels:n,addPanel:r,removePanel:i}=ss(us),a=e===`row`;return(0,u.jsxs)(`div`,{className:`flex h-full w-full flex-col`,children:[(0,u.jsx)(`div`,{className:`flex shrink-0 items-center justify-end gap-1 border-b border-gray-200 bg-gray-50/70 px-1`,children:(0,u.jsx)(cs,{onPick:e=>void r(e)})}),n.length===0?(0,u.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-sm text-gray-500`,children:`Empty layout - add a panel to populate`}):(0,u.jsx)(`div`,{className:`flex min-h-0 flex-1 gap-1 bg-gray-200 ${a?`flex-row`:`flex-col`}`,children:n.map(e=>{let n=as(e);return(0,u.jsxs)(`div`,{style:{flex:`${t.sizes[n]??1} 1 0`},className:`relative min-h-0 min-w-0 overflow-hidden bg-white`,children:[(0,u.jsx)(`div`,{className:`absolute left-1 top-1 z-10`,children:(0,u.jsx)(ls,{onClick:()=>void i(n)})}),(0,u.jsx)(Io,{entityId:e.entityId,slot:e.slot,className:`h-full`})]},n)})})]})}var fs=va(`composite_hbox`,()=>(0,u.jsx)(ds,{direction:`row`})),ps=va(`composite_vbox`,()=>(0,u.jsx)(ds,{direction:`column`})),ms={panels:[],sizes:{},active:null};function hs(){let{state:e,update:t,panels:n,addPanel:r,removePanel:i}=ss(ms),a=Pr((0,c.useMemo)(()=>n.map(e=>e.entityId),[n])),o=(0,c.useMemo)(()=>Object.fromEntries(a.map(e=>[e.entity_id,X(e)])),[a]),s=n.find(t=>as(t)===e.active)??n[0],l=s?as(s):null;return(0,u.jsxs)(`div`,{className:`flex h-full w-full flex-col`,children:[(0,u.jsxs)(`div`,{className:`flex shrink-0 items-center overflow-x-auto border-b border-gray-200 bg-gray-50/70`,children:[n.map(e=>{let n=as(e),r=o[e.entityId]??e.entityId;return(0,u.jsxs)(`button`,{type:`button`,onClick:()=>void t({active:n}),title:r,className:`flex max-w-48 shrink-0 items-center gap-2 border-r border-gray-200 px-3 py-2 text-sm ${l===n?`bg-white text-gray-900`:`bg-gray-50 text-gray-600 hover:bg-gray-100`}`,children:[(0,u.jsx)(`span`,{className:`truncate`,children:r}),(0,u.jsx)(ls,{onClick:e=>{e.stopPropagation(),i(n)}})]},n)}),(0,u.jsx)(`div`,{className:`ml-auto px-1`,children:(0,u.jsx)(cs,{onPick:e=>void r(e)})})]}),(0,u.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:s?(0,u.jsx)(Io,{entityId:s.entityId,slot:s.slot,className:`h-full`},l):(0,u.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-gray-500`,children:`Empty tabbed layout - add a panel to populate`})})]})}var gs=va(`composite_tabs`,hs);function _s({entityId:e}){if(!e)throw Error(`This view needs an entity to show.`);let{sendStrategyRequest:t}=Z(),[n,r]=(0,c.useState)(null),[i,a]=(0,c.useState)(null),[o,s]=(0,c.useState)(null),[l,d]=(0,c.useState)(null),[p,m]=(0,c.useState)(``),[h,g]=(0,c.useState)(!1),_=Y(e),v=Fr(e,{}),y=(0,c.useMemo)(()=>(v||[]).filter(e=>e.entity_type_id!==J.VIEW),[v]);(0,c.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&r(null)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[n]);let b=_||{},x=X(b),S=Rr(b,`list_purpose`),C=typeof S==`string`?S:``,w=Rr(b,`description`),T=typeof w==`string`?w:``,E=(0,c.useMemo)(()=>y.find(e=>e.entity_id===n),[y,n]),D=(0,c.useMemo)(()=>y.find(e=>e.entity_id===i)||null,[y,i]),O=()=>{s(null),d(null)},k=(e,t)=>{e.stopPropagation(),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),s(t)},A=(e,t)=>{if(!o||o===t)return;e.preventDefault();let n=e.currentTarget.getBoundingClientRect(),r=n.top+n.height/2,i=e.clientY<r?`before`:`after`;d(e=>e?.entityId===t&&e.position===i?e:{entityId:t,position:i})},j=(e,n,r)=>{e&&n&&e!==n&&t(r===`before`?$.moveChildBefore(e,n):$.moveChildAfter(e,n))},M=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=o||e.dataTransfer.getData(`text/plain`),r=l?.entityId===t?l.position:`after`;j(n,t,r),O()},N=e=>{n===e&&r(null),t($.detachChild(e))},ee=e=>{n===e&&r(null),a(e)},te=()=>{i&&(t($.deleteEntity(i)),a(null))},P=async()=>{let n=p.trim();if(n&&!h){g(!0);try{await t($.createEntity(e,J.ENTITY,{name:n}),{awaitResponse:!0}),m(``)}finally{g(!1)}}};return _?(0,u.jsxs)(`div`,{className:`flex h-full flex-col bg-gray-50 text-gray-900`,children:[(0,u.jsxs)(`div`,{className:`shrink-0 border-b border-gray-200 bg-white px-6 py-4`,children:[(0,u.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight text-gray-900`,children:x}),T&&(0,u.jsx)(`p`,{className:`mt-1 text-sm text-gray-600`,children:T})]}),C&&(0,u.jsx)(`span`,{className:`rounded-full border border-gray-200 bg-gray-50 px-3 py-1 text-xs font-medium text-gray-600`,children:C})]}),(0,u.jsxs)(`div`,{className:`mt-3 flex items-center gap-2`,children:[(0,u.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P())},placeholder:`New entity name…`,disabled:h,className:`flex-1 max-w-xs rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-900 placeholder-gray-400 focus:outline-hidden focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50`}),(0,u.jsx)(`button`,{type:`button`,onClick:P,disabled:!p.trim()||h,className:`rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400`,children:h?`Creating…`:`+ New Entity`}),(0,u.jsxs)(`span`,{className:`ml-auto text-xs font-medium text-gray-500`,children:[y.length,` `,y.length===1?`item`:`items`]})]})]}),(0,u.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1.5`,children:y.length===0?(0,u.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center text-center text-gray-500`,children:[(0,u.jsx)(`h3`,{className:`text-lg font-medium text-gray-900`,children:`No items yet`}),(0,u.jsx)(`p`,{className:`mt-1 max-w-sm text-sm text-gray-600`,children:`Add child entities to this list to build a durable artifact.`})]}):(0,u.jsx)(`div`,{className:`overflow-hidden rounded-md border border-gray-200 bg-white`,children:y.map(e=>{let t=e||{},n=e.entity_id,i=o===n,a=l?.entityId===n&&l.position===`before`,s=l?.entityId===n&&l.position===`after`;return(0,u.jsxs)(`div`,{onDragOver:e=>A(e,n),onDrop:e=>M(e,n),onDragEnd:O,className:`group flex items-center gap-1 border-b border-gray-200 px-2 py-1 last:border-b-0 hover:bg-gray-50 ${i?`opacity-50`:``} ${a?`border-t-2 border-t-blue-500`:``} ${s?`border-b-2 border-b-blue-500`:``}`,children:[(0,u.jsx)(`div`,{draggable:!0,onDragStart:e=>k(e,n),onDragEnd:O,className:`flex h-5 w-5 shrink-0 cursor-grab items-center justify-center rounded-sm text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 active:cursor-grabbing`,title:`Drag to reorder`,"aria-label":`Drag ${X(t)} to reorder`,children:(0,u.jsx)(Cn,{className:`h-4 w-4`})}),(0,u.jsxs)(`button`,{type:`button`,onClick:()=>r(n),className:`flex min-w-0 flex-1 items-center gap-2 text-left focus:outline-hidden focus:ring-2 focus:ring-inset focus:ring-blue-500`,children:[(0,u.jsx)(`div`,{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-xs bg-gray-100 text-gray-500`,children:(0,u.jsx)(Ja,{entityTypeId:t.entity_type_id,className:`h-3 w-3`})}),(0,u.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,u.jsx)(`div`,{className:`truncate text-sm font-medium leading-5 text-gray-900`,children:X(t)})})]}),(0,u.jsxs)(`div`,{className:`flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),N(n)},"aria-label":`Remove ${X(t)} from list`,title:`Remove from list`,className:`rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700`,children:(0,u.jsx)(Fn,{className:`h-3.5 w-3.5`})}),(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ee(n)},"aria-label":`Delete ${X(t)}`,title:`Delete entity`,className:`rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-600`,children:(0,u.jsx)(bn,{className:`h-3.5 w-3.5`})})]})]},n)})})}),i&&(0,f.createPortal)((0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/50`,onClick:()=>a(null)}),(0,u.jsxs)(`div`,{className:`relative mx-4 w-full max-w-md rounded-lg border border-gray-200 bg-white p-6 shadow-xl`,onClick:e=>e.stopPropagation(),children:[(0,u.jsxs)(`div`,{className:`mb-4 flex items-center gap-3`,children:[(0,u.jsx)(`div`,{className:`flex h-10 w-10 items-center justify-center rounded-full border border-amber-200 bg-amber-50`,children:(0,u.jsx)(yn,{className:`h-5 w-5 text-amber-600`})}),(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h3`,{className:`text-lg font-semibold text-gray-900`,children:`Confirm Delete`}),(0,u.jsx)(`p`,{className:`text-sm text-gray-600`,children:`This action cannot be undone`})]})]}),(0,u.jsxs)(`p`,{className:`mb-6 text-gray-700`,children:[`Are you sure you want to delete`,` `,(0,u.jsxs)(`span`,{className:`font-medium text-gray-900`,children:[`"`,X(D),`"`]}),`? This will permanently delete the entity and all its data.`]}),(0,u.jsxs)(`div`,{className:`flex justify-end gap-3`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>a(null),className:`rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm text-gray-600 transition-colors hover:bg-gray-50`,children:`Cancel`}),(0,u.jsx)(`button`,{type:`button`,onClick:te,className:`rounded-lg bg-red-600 px-4 py-2 text-sm text-white transition-colors hover:bg-red-700`,children:`Delete Entity`})]})]})]}),document.body),n&&(0,f.createPortal)((0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/40 backdrop-blur-xs`,onClick:()=>r(null)}),(0,u.jsxs)(`div`,{className:`relative flex h-[90%] w-[92%] max-w-5xl flex-col rounded-xl border border-gray-200 bg-white shadow-2xl`,onClick:e=>e.stopPropagation(),children:[(0,u.jsxs)(`div`,{className:`flex items-center justify-between border-b border-gray-200 px-4 py-3`,children:[(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h3`,{className:`text-sm font-semibold text-gray-900`,children:X(E)}),(0,u.jsx)(`div`,{className:`text-xs text-gray-500`,children:Br(E)})]}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>r(null),className:`text-2xl leading-none text-gray-400 transition-colors hover:text-gray-600`,title:`Close (Esc)`,children:`×`})]}),(0,u.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-4`,children:(0,u.jsx)(Io,{entityId:n})})]})]}),document.body)]}):(0,u.jsx)(`div`,{className:`flex h-full items-center justify-center bg-gray-50 text-gray-500`,children:`Loading list...`})}var vs=va(`list_view`,_s),ys={ENTITY_ID:`application/x-entity-id`,ENTITY_DATA:`application/x-entity-data`,SOURCE_CONTEXT:`application/x-source-context`},bs=class{static startDrag(e,t,n={}){let{dragEffect:r=`move`,dragImage:i,dragImageText:a}=n;if(e.dataTransfer.setData(ys.ENTITY_ID,t.entityId),e.dataTransfer.setData(ys.ENTITY_DATA,JSON.stringify(t)),t.sourceContext&&e.dataTransfer.setData(ys.SOURCE_CONTEXT,t.sourceContext),e.dataTransfer.effectAllowed=r,a&&!i){let t=this.createDragImage(a);e.dataTransfer.setDragImage(t,0,0),setTimeout(()=>document.body.removeChild(t),0)}else i&&e.dataTransfer.setDragImage(i,0,0);console.log(`🎯 Entity drag started:`,t)}static handleDrop(e,t){e.preventDefault(),e.stopPropagation();let n=e.dataTransfer.getData(ys.ENTITY_ID);if(!n)return console.warn(`🚫 No entity ID found in drag data`),!1;let r={entityId:n};try{let t=e.dataTransfer.getData(ys.ENTITY_DATA);t&&(r=JSON.parse(t))}catch(e){console.warn(`⚠️ Could not parse full drag data, using entity ID only:`,e)}return console.log(`🎯 Entity drop handled:`,r),t(r),!0}static handleDragOver(e,t={}){let{dropEffect:n=`move`,acceptedTypes:r}=t;return!e.dataTransfer.getData(ys.ENTITY_ID)&&r?!1:(e.preventDefault(),e.dataTransfer.dropEffect=n,!0)}static createDragImage(e){let t=document.createElement(`div`);return t.style.position=`absolute`,t.style.top=`-1000px`,t.style.backgroundColor=`rgba(55, 65, 81, 0.9)`,t.style.color=`white`,t.style.padding=`8px 12px`,t.style.borderRadius=`6px`,t.style.fontSize=`0.875rem`,t.style.fontWeight=`500`,t.style.border=`1px solid rgba(75, 85, 99, 0.5)`,t.style.boxShadow=`0 4px 6px -1px rgba(0, 0, 0, 0.1)`,t.textContent=e,document.body.appendChild(t),t}static hasValidEntityData(e){return!!e.dataTransfer.getData(ys.ENTITY_ID)}static getEntityId(e){return e.dataTransfer.getData(ys.ENTITY_ID)||null}};function xs(e){return{onDragOver:t=>{bs.handleDragOver(t,{dropEffect:e.dropEffect,acceptedTypes:e.acceptedTypes})&&e.onDragOver&&e.onDragOver(t.nativeEvent)},onDrop:t=>{bs.handleDrop(t,e.onDrop)},onDragEnter:t=>{bs.hasValidEntityData(t)&&e.onDragEnter&&e.onDragEnter(t.nativeEvent)},onDragLeave:t=>{e.onDragLeave&&e.onDragLeave(t.nativeEvent)}}}var Ss=Object.values(J),Cs=Qt(`parent_id`,null);function ws(e){if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=Ss.find(e=>e===t);if(n)return n;let r=new Set;t.endsWith(`Entity`)?r.add(t):(r.add(`${t}Entity`),r.add(`${t.charAt(0).toUpperCase()}${t.slice(1)}Entity`));for(let e of r){let t=Ss.find(t=>t.endsWith(`.${e}`));if(t)return t}return t.includes(`.`)?t:null}function Ts(e){let t=new Set,n=[];return e.forEach(e=>{let r=ws(e);r&&!t.has(r)&&(t.add(r),n.push(r))}),n}var Es=new Set([J.VIEW,J.GRANT,J.DEPLOYMENT,J.STRATEGY_REQUEST]);function Ds(e){return Object.entries(e).filter(([e,t])=>!Es.has(e)&&!t?.principal).map(([e])=>e).sort()}var Os=c.default.forwardRef(({position:e,options:t,onSelect:n},r)=>{let[i,a]=(0,c.useState)(``),o=(0,c.useMemo)(()=>{let e=i.trim().toLowerCase();return Object.entries(t).filter(([t,n])=>!e||String(n?.name||t).toLowerCase().includes(e)||t.toLowerCase().includes(e))},[t,i]);return(0,f.createPortal)((0,u.jsxs)(`div`,{ref:r,className:`fixed w-64 bg-white border border-gray-200 rounded-lg shadow-xl z-9999 flex flex-col max-h-96`,style:{top:e.top,left:e.left},children:[(0,u.jsx)(`div`,{className:`p-2 border-b border-gray-200`,children:(0,u.jsx)(`input`,{type:`text`,value:i,onChange:e=>a(e.target.value),placeholder:`Search entity types...`,autoFocus:!0,className:`w-full px-2 py-1 text-xs bg-white text-gray-900 border border-gray-300 rounded-sm focus:outline-hidden focus:ring-1 focus:ring-blue-500 placeholder-gray-500`})}),(0,u.jsx)(`div`,{className:`overflow-y-auto p-2`,children:o.length>0?o.map(([e,t])=>(0,u.jsxs)(`button`,{onClick:()=>n(e),className:`w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-sm transition-colors flex items-center gap-2`,title:e,children:[(0,u.jsx)(Ja,{entityTypeId:e,className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`span`,{className:`truncate`,children:t?.name||e})]},e)):(0,u.jsx)(`div`,{className:`px-3 py-2 text-xs text-gray-500`,children:i?`No matching entity types`:`Loading entity types...`})})]}),document.body)}),ks=({typeId:e,typeName:t,count:n,isExpanded:r,onToggle:i,depth:a})=>(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5 py-0.5 px-2 text-xs text-gray-500 cursor-pointer hover:bg-gray-50 rounded-sm select-none`,style:{paddingLeft:`${a*16+8}px`},onClick:i,children:[(0,u.jsx)(`span`,{className:`text-xs`,children:r?`▼`:`▶`}),(0,u.jsx)(Ja,{entityTypeId:e,className:`w-3.5 h-3.5 shrink-0`}),(0,u.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:t}),(0,u.jsxs)(`span`,{className:`text-gray-400`,children:[`(`,n,`)`]})]}),As=({entityId:e,parentId:t,selectedEntityId:n=null,onSelect:r,onDoubleClick:i,onPin:a,onDelete:o,onCreateChild:s,expandedEntities:l,onToggleExpanded:d,depth:f=0,onEntityMove:p,onEntityAdd:m,onRemoveChild:h,availableEntities:g={},allowCreate:_=!0,filterTypeIds:v=[],showDeleteAction:y=!0,showCreateChildAction:b=!0,ancestors:S=new Set,groupByEntityType:C=!0,revealEntityId:w,revealAncestors:T})=>{let E=S.has(e),D=(0,c.useMemo)(()=>new Set([...S,e]),[S,e]),O=Y(e),[k,A]=(0,c.useState)(!1),[j,M]=(0,c.useState)(!1),[N,ee]=(0,c.useState)(null),[te,P]=(0,c.useState)(!1),[ne,re]=(0,c.useState)(new Set),[ie,ae]=(0,c.useState)(void 0),F=(0,c.useRef)(null),I=(0,c.useRef)(null),L=(0,c.useRef)(null),oe=(0,c.useRef)(null),R=l.has(e),se=Fr(e,{types:v,enabled:!!O?.children_ids?.length}),ce=se.length>0,z=R?se:[];if(w!==ie){ae(w);let e=new Set;w&&C&&se.forEach(t=>{(t.entity_id===w||T?.has(t.entity_id))&&e.add(t.entity_type_id||`unknown`)}),re(e)}let le=(0,c.useCallback)(()=>{r?.(e)},[e,r]),ue=(0,c.useCallback)(()=>{i(e)},[e,i]),de=(0,c.useCallback)(t=>{t.preventDefault(),t.stopPropagation(),ce&&d(e)},[e,ce,d]);(0,c.useCallback)(()=>{a&&a(e)},[e,a]);let fe=(0,c.useMemo)(()=>{let e=v.length>0?new Set(v):null;return Object.entries(g).filter(([t])=>!e||e.has(t))},[g,v]),pe=(0,c.useMemo)(()=>Object.fromEntries(fe),[fe]),me=(0,c.useCallback)(t=>{if(t.stopPropagation(),R||d(e),fe.length===1){let[t]=fe[0];s&&s(e,t),M(!1);return}let n=!j;if(n&&I.current){let e=I.current.getBoundingClientRect();ee({top:e.bottom+4,left:Math.max(8,Math.min(e.right-256,window.innerWidth-256-8))})}M(n)},[fe,e,R,s,d,j]),he=(0,c.useCallback)(t=>{R||d(e),s&&s(e,t),M(!1)},[e,R,s,d]);(0,c.useEffect)(()=>{let e=e=>{let t=e.target;F.current&&!F.current.contains(t)&&L.current&&!L.current.contains(t)&&M(!1)};if(j)return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[j]);let ge=(0,c.useCallback)(t=>{t.stopPropagation(),navigator.clipboard?.writeText(e),P(!1)},[e]),_e=(0,c.useCallback)(t=>{t.stopPropagation(),window.open(`${window.location.origin}${x(di(e))}`,`_blank`,`noopener,noreferrer`),P(!1)},[e]),B=(0,c.useCallback)(n=>{n.stopPropagation(),t&&h&&h(e,t),P(!1)},[e,h,t]);(0,c.useEffect)(()=>{let e=e=>{oe.current&&!oe.current.contains(e.target)&&P(!1)};if(te)return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[te]);let ve=(0,c.useCallback)(n=>{if(!O)return;let r=O.entity_type_id,i=X(O);bs.startDrag(n,{entityId:e,entityType:r,sourceContext:`entity-explorer`,sourceParentId:t},{dragEffect:`move`,dragImageText:i})},[O,e,t]),V=xs({dropEffect:`move`,onDrop:t=>{console.log(`Entity dropped on EntityItem:`,t,`target:`,e),A(!1),t.entityId!==e&&(t.sourceContext===`entity-explorer`&&t.sourceParentId?p?.(t.entityId,e,t.sourceParentId):m?.(t.entityId,e))},onDragEnter:()=>{A(!0)},onDragLeave:()=>{A(!1)}});if(!O){let n={paddingLeft:`${f*16+8}px`};return(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5 py-1 px-2 text-xs text-gray-600`,style:n,children:[(0,u.jsx)(`div`,{className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`span`,{className:`flex-1`,children:`(missing)`}),t&&h&&(0,u.jsx)(`button`,{onClick:()=>h(e,t),className:`shrink-0 w-4 h-4 flex items-center justify-center text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-sm transition-all`,title:`Remove missing entity from parent`,children:(0,u.jsx)(Fn,{className:`w-3.5 h-3.5`})})]})}if(E){let n={paddingLeft:`${f*16+8}px`},r=X(O);return(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5 py-1 px-2 text-xs text-gray-400 italic`,style:n,title:`Circular reference — this entity already appears above in the tree`,children:[(0,u.jsx)(In,{className:`w-3.5 h-3.5 shrink-0`}),(0,u.jsxs)(`span`,{className:`truncate flex-1`,children:[r,` (circular ref)`]}),t&&h&&(0,u.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),h(e,t)},className:`shrink-0 w-4 h-4 flex items-center justify-center text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-sm transition-all`,title:`Remove circular reference from parent`,children:(0,u.jsx)(Fn,{className:`w-3.5 h-3.5`})})]})}let ye=O?.entity_type_id||``,be=n===e,xe=Rr(O,`name`),Se=ye===J.VIEW?typeof xe==`string`&&xe?xe:O?.component||X(O):X(O),H={paddingLeft:`${f*16+8}px`};return(0,u.jsxs)(`div`,{className:`relative`,children:[(0,u.jsxs)(`div`,{draggable:!0,className:`flex items-center gap-1.5 py-1 px-2 rounded text-sm transition-all cursor-grab select-none hover:bg-gray-100 text-gray-700 w-full ${be?`bg-blue-50 border border-blue-200 text-blue-700`:``} ${k?`ring-2 ring-blue-500 ring-inset bg-blue-50`:``}`,style:H,onClick:le,onDoubleClick:ue,onDragStart:ve,...V,title:`${ye} • ${Se} • Double-click to open • Click pin to dock • Drag to move • Drop entities to add as children • ${e}`,children:[ce&&(0,u.jsx)(`div`,{className:`shrink-0 w-4 h-4 flex items-center justify-center text-xs text-gray-500 hover:text-gray-300 cursor-pointer`,onClick:de,title:`Click to expand/collapse`,children:R?`▼`:`▶`}),!ce&&(0,u.jsx)(`div`,{className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`div`,{className:`shrink-0`,children:(0,u.jsx)(Ja,{entityTypeId:ye,className:`w-4 h-4`})}),(0,u.jsx)(`div`,{className:`truncate min-w-0 font-medium flex-1`,children:Se}),_&&b&&(0,u.jsxs)(`div`,{className:`relative shrink-0`,ref:F,children:[(0,u.jsx)(`button`,{ref:I,onClick:me,className:`w-6 h-6 flex items-center justify-center text-xs text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-sm transition-all`,title:`Add child entity`,children:`+`}),j&&N&&(0,u.jsx)(Os,{ref:L,position:N,options:pe,onSelect:he})]}),y&&(0,u.jsx)(`button`,{onClick:t=>{t.stopPropagation(),console.log(`Delete button clicked for entity:`,e),o&&o(e)},type:`button`,className:`shrink-0 w-6 h-6 flex items-center justify-center text-xs text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-sm transition-all`,title:`Delete entity`,children:(0,u.jsx)(bn,{className:`w-3.5 h-3.5`})}),(0,u.jsxs)(`div`,{className:`relative shrink-0`,ref:oe,children:[(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),P(e=>!e)},className:`w-6 h-6 flex items-center justify-center text-xs text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-sm transition-all`,title:`More actions`,children:(0,u.jsx)(An,{className:`w-3.5 h-3.5`})}),te&&(0,u.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded-lg shadow-xl z-9999 p-1`,children:[(0,u.jsxs)(`button`,{type:`button`,onClick:ge,className:`w-full px-2 py-1.5 text-xs text-gray-700 hover:bg-gray-50 rounded-sm flex items-center gap-2`,children:[(0,u.jsx)(Nn,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Copy entity ID`})]}),(0,u.jsxs)(`button`,{type:`button`,onClick:_e,className:`w-full px-2 py-1.5 text-xs text-gray-700 hover:bg-gray-50 rounded-sm flex items-center gap-2`,children:[(0,u.jsx)(En,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Open in new tab`})]}),t&&h&&(0,u.jsxs)(`button`,{type:`button`,onClick:B,className:`w-full px-2 py-1.5 text-xs text-gray-700 hover:bg-red-50 hover:text-red-600 rounded-sm flex items-center gap-2`,children:[(0,u.jsx)(Fn,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Remove link from parent`})]})]})]})]}),R&&z.length>0&&(0,u.jsx)(`div`,{className:`mt-0.5 space-y-0.5`,children:C?(()=>{let t=new Map;return z.forEach(e=>{let n=e.entity_type_id||`unknown`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),Array.from(t.entries()).map(([t,c])=>{let x=ne.has(t),S=g[t]?.name||t.split(`.`).pop()||t;return(0,u.jsxs)(`div`,{children:[(0,u.jsx)(ks,{typeId:t,typeName:S,count:c.length,isExpanded:x,onToggle:()=>re(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),depth:f+1}),x&&c.map(t=>(0,u.jsx)(As,{entityId:t.entity_id,parentId:e,onDoubleClick:i,onPin:a,onDelete:o,onCreateChild:s,expandedEntities:l,onToggleExpanded:d,onEntityMove:p,onEntityAdd:m,onRemoveChild:h,availableEntities:g,allowCreate:_,filterTypeIds:v,showDeleteAction:y,showCreateChildAction:b,selectedEntityId:n,onSelect:r,depth:f+2,ancestors:D,groupByEntityType:C,revealEntityId:w,revealAncestors:T},t.entity_id))]},t)})})():z.map(t=>(0,u.jsx)(As,{entityId:t.entity_id,parentId:e,onDoubleClick:i,onPin:a,onDelete:o,onCreateChild:s,expandedEntities:l,onToggleExpanded:d,onEntityMove:p,onEntityAdd:m,onRemoveChild:h,availableEntities:g,allowCreate:_,filterTypeIds:v,showDeleteAction:y,showCreateChildAction:b,selectedEntityId:n,onSelect:r,depth:f+1,ancestors:D,groupByEntityType:C,revealEntityId:w,revealAncestors:T},t.entity_id))})]})},js=va(`entity_explorer`,({entityId:e,uiHooks:t,onEntityDelete:n,onEntityOpen:r,onEntitySelect:i,onEntityPin:a,explorerConfig:o})=>{let{sendStrategyRequest:s}=Z(),l=e||``,[d,p]=Za({}),m=na(),h=m.state===`hasValue`?m.contents:{};(0,c.useEffect)(()=>{$i()},[]);let{onEntityOpen:g,onEntityPin:_,onEntitySelect:v}=t||{},y=r??g,b=a??_,x=i??v,S=o?.allow_create??!0,C=o?.title||`Explorer`,w=o?.show_delete_action??!0,T=o?.show_create_child_action??!0,E=o?.group_by_entity_type??!0,D=o?.reveal_entity_id??null,O=(0,c.useMemo)(()=>{let e=Ts(Array.isArray(o?.filter_entity_types)?o.filter_entity_types:[]);return e.length>0?e:Ds(h)},[o?.filter_entity_types,h]),k=(0,c.useMemo)(()=>Ts(Array.isArray(d.explorer_active_filter_entity_types)?d.explorer_active_filter_entity_types:[]),[d.explorer_active_filter_entity_types]),A=Array.isArray(d.explorer_active_filter_entity_types)?k:O,j=!e,M=Ki({typeIds:(0,c.useMemo)(()=>A.length>0?A:Object.keys(h).sort(),[A,h]),where:Cs,enabled:j}),[N,ee]=(0,c.useState)(null),te=(0,c.useRef)(null),P=(0,c.useRef)(null),ne=(0,c.useCallback)(()=>{ee(e=>{let t=te.current?.getBoundingClientRect();return e||!t?null:{top:t.bottom+4,left:Math.max(8,Math.min(t.left,window.innerWidth-256-8))}})},[]);(0,c.useEffect)(()=>{if(!N)return;let e=e=>{let t=e.target;!P.current?.contains(t)&&!te.current?.contains(t)&&ee(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[N]);let re=(0,c.useMemo)(()=>Object.fromEntries(Object.entries(h).filter(([e])=>A.length===0||A.includes(e))),[h,A]),[ie,ae]=(0,c.useState)(!1),[F,I]=(0,c.useState)(``),[oe,R]=(0,c.useState)(null),se=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(!ie)return;let e=e=>{se.current&&!se.current.contains(e.target)&&ae(!1)};return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[ie]);let ce=(0,c.useMemo)(()=>{let e=F.trim().toLowerCase();return e?Object.entries(h).filter(([t,n])=>String(n?.name||t).toLowerCase().includes(e)||String(t).toLowerCase().includes(e)):Object.entries(h)},[h,F]),z=(0,c.useCallback)(e=>{p({explorer_active_filter_entity_types:e})},[p]),le=(0,c.useCallback)(e=>{y?.(e,l)},[y,l]),ue=(0,c.useCallback)(e=>{R(e),x?.(e,l)},[x,l]),de=(0,c.useCallback)(e=>{b?.(e,l)},[b,l]),fe=(0,c.useCallback)(e=>{V(e)},[]),pe=(0,c.useCallback)((e,t,n)=>{if(console.log(`Moving entity:`,e,`from:`,n,`to:`,t),e===t||n===t)return;let r=$.reparentChild(e,t);s(r)},[s]),me=(0,c.useCallback)((e,t)=>{if(console.log(`Adding entity:`,e,`to:`,t),e===t)return;let n=$.reparentChild(e,t);s(n)},[s]),he=(0,c.useCallback)(async(e,t)=>{try{let n=(await Promise.resolve(s($.createEntity(e,t),{awaitResponse:!0})))?.child_entity;n&&(e&&B(t=>new Set(t).add(e)),R(n),x?.(n,e??``))}catch(e){console.error(`Failed to create entity:`,e)}},[x,s]),ge=(0,c.useCallback)((e,t)=>{console.log(`Removing child:`,e,`from parent:`,t);let n=$.detachChild(e);s(n)},[s]),[_e,B]=(0,c.useState)(new Set([l])),[ve,V]=(0,c.useState)(null),ye=Y(l),be=Y(ve||l),xe=(0,c.useMemo)(()=>!ve||!be?`this entity`:X(be),[ve,be]),Se=(0,c.useMemo)(()=>{if(!D)return new Set;let e=new Set,t=new Set,n=[D];for(;n.length>0;){let r=n.shift();if(t.has(r))continue;if(t.add(r),r===l)break;let i=L.readEntity(r);for(let r of i?.parent_ids??[])r&&!t.has(r)&&(e.add(r),n.push(r))}return e},[D,l]);(0,c.useEffect)(()=>{D&&(B(e=>new Set([...e,...Se])),R(D))},[D,Se]);let H=(0,c.useCallback)(e=>{B(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),U=(0,c.useMemo)(()=>ve?(0,u.jsxs)(`div`,{className:`fixed inset-0 z-9999 flex items-center justify-center`,children:[(0,u.jsx)(`div`,{className:`absolute inset-0 bg-black/50`,onClick:()=>V(null)}),(0,u.jsxs)(`div`,{className:`relative bg-white border border-gray-200 rounded-lg shadow-xl p-6 max-w-md w-full mx-4`,onClick:e=>e.stopPropagation(),children:[(0,u.jsxs)(`div`,{className:`flex items-center gap-3 mb-4`,children:[(0,u.jsx)(`div`,{className:`w-10 h-10 rounded-full bg-amber-50 border border-amber-200 flex items-center justify-center`,children:(0,u.jsx)(yn,{className:`w-5 h-5 text-amber-600`})}),(0,u.jsxs)(`div`,{children:[(0,u.jsx)(`h3`,{className:`text-lg font-semibold text-gray-900`,children:`Confirm Delete`}),(0,u.jsx)(`p`,{className:`text-sm text-gray-600`,children:`This action cannot be undone`})]})]}),(0,u.jsxs)(`p`,{className:`text-gray-700 mb-6`,children:[`Are you sure you want to delete `,(0,u.jsxs)(`span`,{className:`font-medium text-gray-900`,children:[`"`,xe,`"`]}),`? This will permanently delete the entity and all its data.`]}),(0,u.jsxs)(`div`,{className:`flex gap-3 justify-end`,children:[(0,u.jsx)(`button`,{type:`button`,onClick:()=>V(null),className:`px-4 py-2 text-sm bg-white hover:bg-gray-50 text-gray-600 border border-gray-200 rounded-lg transition-colors`,children:`Cancel`}),(0,u.jsx)(`button`,{type:`button`,onClick:async()=>{let e=ve;V(null);try{await s($.deleteEntity(e),{awaitResponse:!0}),n?.(e)}catch{}},className:`px-4 py-2 text-sm bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors`,children:`Delete Entity`})]})]})]}):null,[ve,xe,n,s]);return!j&&!ye?(0,u.jsxs)(`div`,{className:`p-4 text-center text-gray-500 text-sm`,children:[(0,u.jsx)(In,{className:`w-6 h-6 mb-2 mx-auto text-red-500`}),(0,u.jsx)(`div`,{children:`No root entity found`}),(0,u.jsxs)(`div`,{className:`text-xs text-gray-600 mt-1`,children:[`Entity ID: `,l]})]}):(0,u.jsxs)(`div`,{className:`h-full flex flex-col bg-white text-gray-900`,children:[(0,u.jsxs)(`div`,{className:`flex-1 overflow-y-auto overflow-x-visible p-2`,children:[(0,u.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,u.jsxs)(`div`,{className:`text-xs text-gray-500 flex items-center gap-1.5`,children:[(0,u.jsx)(On,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:C})]}),(0,u.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[j&&S&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`button`,{ref:te,type:`button`,onClick:ne,className:`px-2 py-1 text-xs bg-white hover:bg-gray-50 text-gray-700 border border-gray-200 rounded-lg transition-colors`,title:`Create a top-level entity`,children:`+ New`}),N&&(0,u.jsx)(Os,{ref:P,position:N,options:re,onSelect:e=>{ee(null),he(null,e)}})]}),(0,u.jsxs)(`div`,{className:`relative`,ref:se,children:[(0,u.jsxs)(`button`,{onClick:()=>{ae(e=>!e),I(``)},className:`px-2 py-1 text-xs bg-white hover:bg-gray-50 text-gray-700 border border-gray-200 rounded-lg transition-colors flex items-center gap-1`,title:`Explorer filter settings`,children:[(0,u.jsx)(Sn,{className:`w-3 h-3`}),(0,u.jsx)(`span`,{children:`Settings`})]}),ie&&(0,u.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 w-56 max-w-[calc(100vw-1rem)] bg-white border border-gray-200 rounded-lg shadow-xl z-9999`,children:[(0,u.jsx)(`div`,{className:`p-2 border-b border-gray-200 text-xs font-medium text-gray-700`,children:`Filter entity types`}),(0,u.jsx)(`div`,{className:`p-2 border-b border-gray-200`,children:(0,u.jsx)(`input`,{type:`text`,value:F,onChange:e=>I(e.target.value),placeholder:`Search types...`,className:`w-full px-2 py-1 text-xs bg-white text-gray-900 border border-gray-300 rounded-sm focus:outline-hidden focus:ring-1 focus:ring-blue-500 placeholder-gray-500`})}),(0,u.jsxs)(`div`,{className:`p-2 border-b border-gray-200 flex gap-2`,children:[(0,u.jsx)(`button`,{type:`button`,className:`px-2 py-1 text-xs border border-gray-200 rounded-sm hover:bg-gray-50`,onClick:()=>z([]),children:`Show all`}),(0,u.jsx)(`button`,{type:`button`,className:`px-2 py-1 text-xs border border-gray-200 rounded-sm hover:bg-gray-50`,onClick:()=>z(O),children:`Reset default`})]}),(0,u.jsxs)(`div`,{className:`max-h-64 overflow-auto p-2 space-y-1`,children:[ce.map(([e,t])=>{let n=A.includes(e);return(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-gray-700 cursor-pointer`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>{let t=A.includes(e)?A.filter(t=>t!==e):[...A,e];z(t)}}),(0,u.jsx)(Ja,{entityTypeId:e,className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{className:`truncate`,children:t?.name||e})]},e)}),ce.length===0&&(0,u.jsx)(`div`,{className:`text-xs text-gray-500 px-1 py-1`,children:`No matching entity types`})]})]})]})]})]}),j?(0,u.jsxs)(u.Fragment,{children:[M.ids.map(e=>(0,u.jsx)(As,{entityId:e,parentId:void 0,selectedEntityId:oe,onSelect:ue,onDoubleClick:le,onPin:de,onDelete:fe,onCreateChild:he,expandedEntities:_e,onToggleExpanded:H,onEntityMove:pe,onEntityAdd:me,onRemoveChild:ge,availableEntities:h,allowCreate:S,filterTypeIds:A,showDeleteAction:w,showCreateChildAction:T,groupByEntityType:E,revealEntityId:D||void 0,revealAncestors:Se,depth:0},e)),M.ids.length===0&&!M.loading&&(0,u.jsx)(`div`,{className:`px-2 py-1 text-xs text-gray-500`,children:`No top-level entities`}),M.hasMore&&(0,u.jsx)(`button`,{type:`button`,onClick:M.loadMore,disabled:M.loading,className:`mt-1 w-full px-2 py-1 text-xs text-gray-500 hover:text-gray-900 hover:bg-gray-50 rounded-sm`,children:M.loading?`Loading…`:`Load more`})]}):(0,u.jsx)(As,{entityId:l,parentId:void 0,selectedEntityId:oe,onSelect:ue,onDoubleClick:le,onPin:de,onDelete:fe,onCreateChild:he,expandedEntities:_e,onToggleExpanded:H,onEntityMove:pe,onEntityAdd:me,onRemoveChild:ge,availableEntities:h,allowCreate:S,filterTypeIds:A,showDeleteAction:w,showCreateChildAction:T,groupByEntityType:E,revealEntityId:D||void 0,revealAncestors:Se,depth:0})]}),U&&(0,f.createPortal)(U,document.body)]})}),Ms={open_tab_entity_ids:[],active_tab_entity_id:null,root_entity_id:null,sidebar_config:{}},Ns=Object.values(J);function Ps(e){let t=Rr(e,`docName`);if(typeof t==`string`&&t.trim())return t;if(e?.entity_type_id===J.VIEW){let t=Rr(e,`name`);if(typeof t==`string`&&t.trim())return t;if(typeof e.component==`string`&&e.component)return e.component}return X(e)}function Fs(e){if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=Ns.find(e=>e===t);if(n)return n;let r=new Set;t.endsWith(`Entity`)?r.add(t):(r.add(`${t}Entity`),r.add(`${t.charAt(0).toUpperCase()}${t.slice(1)}Entity`));for(let e of r){let t=Ns.find(t=>t.endsWith(`.${e}`));if(t)return t}return t.includes(`.`)?t:null}function Is(e){let t=new Set,n=[];return e.forEach(e=>{let r=Fs(e);r&&!t.has(r)&&(t.add(r),n.push(r))}),n}function Ls({entityId:e,sidebarConfig:t,rootEntityId:n,explorerTitle:r,uiHooks:i}){let[a,o]=Za(Ms),s={...a.sidebar_config||{},...t||{}},l=n||a.root_entity_id||e||null,d=!!s.allow_create,f=(0,c.useMemo)(()=>Is(Array.isArray(s.filter_entity_types)?s.filter_entity_types:[]),[s.filter_entity_types]),p=(0,c.useMemo)(()=>Array.isArray(a.open_tab_entity_ids)?a.open_tab_entity_ids.filter(e=>typeof e==`string`):[],[a.open_tab_entity_ids]),m=typeof a.active_tab_entity_id==`string`?a.active_tab_entity_id:null,h=(0,c.useCallback)((e,t)=>{o({open_tab_entity_ids:e,active_tab_entity_id:t})},[o]),g=(0,c.useCallback)(e=>{let t=p.includes(e)?p:[...p,e];h(t,e)},[p,h]),_=(0,c.useCallback)(e=>{let t=p.indexOf(e),n=p.filter(t=>t!==e),r=m;m===e&&(r=n.length===0?null:n[Math.min(t,n.length-1)]),h(n,r)},[m,p,h]),v=(0,c.useCallback)(e=>{p.includes(e)&&_(e)},[_,p]);return(0,u.jsxs)(`div`,{className:`h-full w-full flex bg-gray-50 text-gray-900`,children:[(0,u.jsx)(`div`,{className:`w-80 min-w-[260px] max-w-[520px] border-r border-gray-200 bg-white flex flex-col`,children:(0,u.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto`,children:(0,u.jsx)(js,{entityId:l,onEntityDelete:v,uiHooks:{...i,onEntitySelect:g,onEntityOpen:g},explorerConfig:{title:r||`Explorer`,allow_create:d,filter_entity_types:f,show_delete_action:s.show_delete_action,show_create_child_action:s.show_create_child_action,reveal_entity_id:m||void 0},className:`h-full w-full`})})}),(0,u.jsxs)(`div`,{className:`flex-1 min-w-0 flex flex-col bg-white`,children:[(0,u.jsx)(`div`,{className:`shrink-0 border-b border-gray-200 bg-gray-50/70`,children:p.length===0?(0,u.jsx)(`div`,{className:`px-4 py-2 text-sm text-gray-500`,children:`Select an entity from the explorer to open a tab.`}):(0,u.jsx)(`div`,{className:`flex overflow-x-auto`,children:p.map(e=>(0,u.jsx)(Rs,{entityId:e,isActive:e===m,onSelect:()=>{h(p,e)},onClose:()=>_(e)},e))})}),(0,u.jsx)(`div`,{className:`flex-1 min-h-0`,children:m?(0,u.jsx)(Io,{entityId:m,className:`h-full w-full`},m):(0,u.jsx)(`div`,{className:`h-full flex items-center justify-center text-gray-500`,children:(0,u.jsxs)(`div`,{className:`text-center`,children:[(0,u.jsx)(jn,{className:`w-10 h-10 mx-auto mb-3 text-gray-300`}),(0,u.jsx)(`div`,{className:`text-sm`,children:`No entity open`})]})})})]})]})}var Rs=({entityId:e,isActive:t,onSelect:n,onClose:r})=>{let i=Y(e),a=Ps(i||{});return(0,u.jsxs)(`button`,{type:`button`,onClick:n,className:`group flex items-center gap-2 px-3 py-2 border-r border-gray-200 text-sm max-w-72 ${t?`bg-white text-gray-900`:`bg-gray-50 text-gray-600 hover:bg-gray-100`}`,title:a,children:[(0,u.jsx)(Ja,{entityTypeId:i?.entity_type_id,className:`w-3.5 h-3.5 shrink-0`}),(0,u.jsx)(`span`,{className:`truncate`,children:a}),(0,u.jsx)(`span`,{role:`button`,className:`opacity-60 hover:opacity-100 p-0.5 rounded-sm hover:bg-gray-200`,onClick:e=>{e.stopPropagation(),r()},children:(0,u.jsx)(Fn,{className:`w-3.5 h-3.5`})})]})},zs=va(`entity_ide`,Ls);function Bs(){let e=new Map,t=new Map,n=[],r={register(n){if(!ya(n))throw Error(`ViewRegistry.register takes a component declared with defineView`);let r=n.viewName;if(e.has(r))throw Error(`ViewRegistry: a view named "${r}" is already registered`);for(let e of n.defaultFor){let n=t.get(e);if(n)throw Error(`ViewRegistry: "${r}" and "${n}" both claim defaultFor ${e}`)}e.set(r,n);for(let e of n.defaultFor)t.set(e,r)},use(e){for(let t of Object.values(e.exports))ya(t)&&(r.register(t),t.entry&&n.push({app:e.app,viewKey:t.viewName}))},get(t){return e.get(t)??null},defaultViewFor(e){return t.get(e)??null},entryPoints(){return[...n]},keys(){return Array.from(e.keys())}};return r}var Vs={app:`graphcore`,exports:{EntityAttributesView:is,CompositeHBox:fs,CompositeVBox:ps,CompositeTabs:gs,ListView:vs,EntityExplorer:js,EntityIDE:zs,GroupView:wa,ViewGallery:io}};function Hs(){let{sendStrategyRequest:e}=Z(),t=(0,c.useRef)(0),[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(null);return{run:(0,c.useCallback)(async n=>{t.current+=1,r(!0),a(null);try{return await e(n,{awaitResponse:!0})??{}}catch(e){return a(e instanceof Error?e:Error(String(e))),null}finally{--t.current,t.current===0&&r(!1)}},[e]),busy:n,error:i,clearError:(0,c.useCallback)(()=>a(null),[])}}function Us(e,t){let[n,r]=(0,c.useState)(null),i=(0,c.useRef)({entity:e,read:t});i.current={entity:e,read:t};let a=n&&e&&n.entityId===e.entity_id?n:null,o=e?.version??0,s=(0,c.useCallback)(e=>{let t=i.current.entity;t&&r(n=>{let r=n&&n.entityId===t.entity_id?n:null;return{entityId:t.entity_id,value:{...r?.value??i.current.read(t),...e},base:r?.base??t.version??0}})},[]),l=(0,c.useCallback)(()=>r(null),[]);return{value:a?.value??(e?t(e):null),edit:s,reset:l,editing:a!==null,base:a?.base??o,stale:a!==null&&o!==a.base}}var Ws=`w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 focus:border-slate-500 focus:outline-none`,Gs=`rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100 disabled:opacity-50`;function Ks(e,t){for(let n of Object.values(e)){let e=n.find(e=>e?.name===t);if(e)return e.schema??{type:`object`,properties:{}}}return null}function qs(e){return e.enum?!0:e.type===`array`?e.items?.type===`string`&&!e.items.enum:[`string`,`number`,`integer`,`boolean`].includes(e.type??``)}function Js(e,t,n){if(n?.[e])return n[e];if(t.title)return t.title;let r=e.replace(/_/g,` `);return r.charAt(0).toUpperCase()+r.slice(1)}function Ys(e){return e==null||e===``||Array.isArray(e)&&e.every(e=>e===``)}function Xs(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=t[i];a.type===`array`&&Array.isArray(e)&&(e=e.filter(e=>e!==``)),(!Ys(e)||n.has(i))&&(r[i]=e)}return r}function Zs({name:e,schema:t,value:n,required:r,text:i,onChange:a}){let o=`strategy-form-${e}`,s=t.description?(0,u.jsx)(`p`,{className:`mt-1 text-xs text-slate-500`,children:t.description}):null;if(t.type===`boolean`)return(0,u.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-slate-800`,children:[(0,u.jsx)(`input`,{id:o,type:`checkbox`,checked:!!n,onChange:e=>a(e.target.checked),className:`h-4 w-4 rounded border-slate-300`}),i]});let c;if(t.enum)c=(0,u.jsxs)(`select`,{id:o,className:Ws,value:n==null?``:String(n),required:r,onChange:e=>a(t.enum.find(t=>String(t)===e.target.value)??``),children:[!r&&(0,u.jsx)(`option`,{value:``}),t.enum.map(e=>(0,u.jsx)(`option`,{value:String(e),children:String(e)},String(e)))]});else if(t.type===`array`){let e=Array.isArray(n)&&n.length>0?n.map(String):[``];c=(0,u.jsxs)(`div`,{className:`space-y-2`,children:[e.map((t,n)=>(0,u.jsxs)(`div`,{className:`flex gap-2`,children:[(0,u.jsx)(`input`,{"aria-label":`${i} ${n+1}`,className:Ws,value:t,onChange:t=>a(e.map((e,r)=>r===n?t.target.value:e))}),e.length>1&&(0,u.jsx)(`button`,{type:`button`,className:Gs,"aria-label":`Remove ${i} ${n+1}`,onClick:()=>a(e.filter((e,t)=>t!==n)),children:`Remove`})]},n)),(0,u.jsx)(`button`,{type:`button`,className:Gs,onClick:()=>a([...e,``]),children:`Add`})]})}else c=t.type===`number`||t.type===`integer`?(0,u.jsx)(`input`,{id:o,type:`number`,className:Ws,required:r,step:t.type===`integer`?1:`any`,value:n==null?``:String(n),onChange:e=>a(e.target.value===``?``:Number(e.target.value))}):(t.maxLength??0)>200?(0,u.jsx)(`textarea`,{id:o,rows:4,className:Ws,required:r,maxLength:t.maxLength,value:typeof n==`string`?n:``,onChange:e=>a(e.target.value)}):(0,u.jsx)(`input`,{id:o,className:Ws,required:r,maxLength:t.maxLength,value:typeof n==`string`?n:``,onChange:e=>a(e.target.value)});return(0,u.jsxs)(`div`,{children:[t.type===`array`?(0,u.jsx)(`span`,{className:`mb-1 block text-sm font-medium text-slate-800`,children:i}):(0,u.jsx)(`label`,{htmlFor:o,className:`mb-1 block text-sm font-medium text-slate-800`,children:i}),c,s]})}function Qs({strategy:e,target:t,initial:n={},value:r,onChange:i,fields:a,hidden:o={},labels:s,submitLabel:l=`Save`,onDone:d}){let f=ea(),{run:p,busy:m,error:h}=Hs(),[g,_]=(0,c.useState)(null);if((0,c.useEffect)(()=>{Qi().catch(()=>void 0)},[]),f.state===`hasError`)return(0,u.jsx)(`p`,{className:`text-sm text-red-600`,children:`Could not load the strategy directory.`});if(f.state!==`hasValue`)return(0,u.jsx)(`p`,{className:`text-sm text-slate-500`,children:`Loading…`});let v=Ks(f.contents,e);if(!v)return(0,u.jsxs)(`p`,{className:`text-sm text-red-600`,children:[`No strategy named `,e,`.`]});let y=v.properties??{},b=new Set(v.required??[]),x=(a??Object.keys(y)).filter(e=>y[e]&&qs(y[e])),S=r??g??n,C=(e,t)=>{i?i({[e]:t}):_({...S,[e]:t})},w=async n=>{n.preventDefault();let r=await p({strategy_name:e,target_entity_id:t,param_config:{...Xs(y,S,b),...o}});r!==null&&(_(null),d?.(r))};return(0,u.jsxs)(`form`,{className:`space-y-4`,onSubmit:e=>void w(e),children:[x.map(e=>(0,u.jsx)(Zs,{name:e,schema:y[e],value:S[e],required:b.has(e),text:Js(e,y[e],s),onChange:t=>C(e,t)},e)),h&&(0,u.jsx)(`p`,{role:`alert`,className:`text-sm text-red-600`,children:h.message}),(0,u.jsx)(`button`,{type:`submit`,disabled:m,className:Gs,children:l})]})}exports.ADMIN_ROUTE=Da,exports.AccessPanel=oo,exports.AdminPanel=Ma,exports.AgentMirror=Ei,exports.AppRoutes=Ho,exports.AuthPage=Ri,exports.BaseEntity=ho,exports.CompositeHBox=fs,exports.CompositeTabs=gs,exports.CompositeVBox=ps,exports.ENTITY_ROUTE=ci,exports.EntityAttributesView=is,exports.EntityExplorer=js,exports.EntityIDE=zs,exports.EntityLinkRedirect=Ro,exports.EntityPicker=xa,exports.EntityRoute=Lo,exports.EntityView=Io,exports.GraphCoreApp=Uo,exports.GraphCoreProvider=ji,exports.GraphCoreRouter=Qo,exports.GroupView=wa,exports.INVITE_ROUTE=Ni,exports.InviteRoute=Li,exports.ListView=vs,exports.StrategyError=le,exports.StrategyForm=Qs,exports.StrategyRequests=$,exports.TopBar=qa,exports.ViewGallery=io,exports.allOf=rn,exports.anyOf=an,exports.baseViews=Vs,exports.collectPages=uo,exports.containsAny=tn,exports.containsValue=en,exports.createViewRegistry=Bs,exports.definePage=so,exports.defineView=va,exports.entityGraph=kr,exports.entityIdFromParams=fi,exports.entityPath=di,exports.equal=Qt,exports.findEntityId=pi,exports.getAttr=Rr,exports.getAttributes=Lr,exports.getBasePath=b,exports.getDisplayName=X,exports.getFields=zr,exports.inValues=$t,exports.inviteUrl=Pi,exports.onResync=me,exports.pageCollisions=qo,exports.range=nn,exports.typeShortName=Br,exports.useAccess=Ea,exports.useAuth=Hr,exports.useBridgeStatus=z,exports.useChildren=Fr,exports.useCreateView=Qa,exports.useDeploymentEntityId=Gr,exports.useEditable=Us,exports.useEntities=Pr,exports.useEntity=Y,exports.useEntityIdByKey=Nr,exports.useEntityQuery=Ki,exports.useGraphCoreBridge=Ar,exports.useIsDeploymentAdmin=Ha,exports.useOffersRegistration=Mi,exports.usePendingInvite=Ii,exports.usePlacementContext=Co,exports.useRecursiveChildren=Ir,exports.useStrategy=Hs,exports.useStrategyRequest=jr,exports.useViewRegistry=Xr,exports.useViewState=Za,exports.useWebSocketConsumer=Z,exports.webPath=x;