@graphcore/react-kernel 0.2.5 → 0.4.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.
- package/dist/api/entityApi.d.ts +7 -1
- package/dist/auth/offlineAccess.d.ts +10 -0
- package/dist/components/Admin/AdminPanel.d.ts +4 -3
- package/dist/graphcore-react-kernel.cjs.js +3 -3
- package/dist/graphcore-react-kernel.es.js +1947 -1656
- package/dist/hooks/useCatalog.d.ts +28 -0
- package/dist/hooks/useServerRoutes.d.ts +5 -0
- package/dist/host/HostedSession.d.ts +28 -0
- package/dist/host/channel.d.ts +43 -0
- package/dist/host/connect.d.ts +26 -0
- package/dist/host/testing.d.ts +25 -0
- package/dist/lib/GraphCoreProvider.d.ts +4 -0
- package/dist/lib/index.d.ts +4 -0
- package/dist/lib/runtimeConfig.d.ts +3 -0
- package/dist/state/registryDirectoryStore.d.ts +1 -0
- package/dist/utils/StrategyRequestBuilder.d.ts +2 -2
- package/dist/views/EntityView.d.ts +3 -1
- package/package.json +1 -1
|
@@ -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),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:
|
|
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;
|
|
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}var w=null;function T(e){w=e}function E(){return w}function D(){return h!==null}var O=(0,c.createContext)(null),ee=O.Provider,k=()=>(0,c.useContext)(O),A=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},j=(e=>e?A(e):A),M=100,N=new Map;function te(e){N.delete(e.key),N.set(e.key,e),N.size>M&&N.delete(N.keys().next().value)}function P(e){return N.get(e)}function ne(){N.clear()}function re(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 ie=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),{}):{},ae=(e,t)=>!e?.deleted&&!e?.forbidden&&!t?.forbidden&&typeof e?.version==`number`&&typeof t?.version==`number`&&e.version<t.version,oe=(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))},se=(e,t)=>{if(!t)return[];let n=e.entitiesById[t];return Array.isArray(n?.children_ids)?n.children_ids.filter(Boolean):[]},ce=(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=se(e,i).reduce((e,t)=>{let n=r(t,new Set(a));return n&&(e[t]=n),e},{});return oe(o,n)||Object.keys(s).length>0||n.includeRoot&&i===t?{entity:o,children:s}:null};return r(t)},F=j(()=>({entitiesById:{},entityIds:[],requestedEntityIds:new Set,notFoundEntityIds:new Set,idsByKey:{},requestedKeys:new Set,notFoundKeys:new Set})),I=(e,t)=>re(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 se(n,e).map(e=>n.entitiesById[e]??null).filter(e=>!!e&&!e.forbidden).filter(e=>oe(e,t))},readRecursiveChildren(e,t={}){return ce(F.getState(),e,t)},mergeEntities(e){let t=ie(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),!ae(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(){ne(),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)}},le=e=>e;function R(e,t=le){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 ue=j(()=>`idle`),de=e=>{ue.setState(e)},fe=()=>R(ue,e=>e),pe=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}},me=new Set;function he(e){return me.add(e),()=>{me.delete(e)}}function ge(e){me.forEach(t=>t(e))}var _e=new Set;function ve(e){return _e.add(e),()=>{_e.delete(e)}}function ye(e){_e.forEach(t=>t(e))}var z=()=>({isAuthenticated:!1,token:null,principalEntityId:null,username:null,isLoading:!1,error:null}),be=j(()=>({...z(),isLoading:!0})),B=e=>{be.setState(e)},xe=()=>R(be),V=class extends Error{};V.prototype.name=`InvalidTokenError`;function Se(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 Ce(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 Se(t)}catch{return atob(t)}}function we(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=Ce(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 Te={debug:()=>void 0,info:()=>void 0,warn:()=>void 0,error:()=>void 0},H,U,Ee=(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))(Ee||{});(e=>{function t(){H=3,U=Te}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})(Ee||={});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)}};Ee.reset();var De=class{static decode(e){try{return we(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))}`}},Oe=`10000000-1000-4000-8000-100000000000`,ke=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join(``)),Ae=class e{static _randomWord(){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return Oe.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 ke(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 ke(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 De.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 De.generateSignedJwtWithHmac(o,s,u)}};Ae.encodeBase64Url=e=>ke(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`);var G=Ae,je=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)}},Me=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(`,`)}},Ne=class e extends je{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)}},Pe=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))}},Fe=`;`,Ie=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}},Le=class extends Error{constructor(e){super(e),this.name=`ErrorTimeout`}},Re=class{constructor(e){this._logger=new W(`AccessTokenEvents`),this._expiringTimer=new Ne(`Access token expiring`),this._expiredTimer=new Ne(`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)}},ze=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)}},Be=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]}},Ve=class extends Error{constructor(e,t){super(t),this.name=`ErrorDPoPNonce`,this.nonce=e}},He=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 Le(`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 Ie(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 Ve(c.headers.get(`dpop-nonce`),`${JSON.stringify(d)}`):d.error?new Ie(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)})}},Ue=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 He([`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}},We=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}},Ge=`code`,Ke=`openid`,qe=`client_secret_post`,Je=900,Ye=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:i,client_id:a,client_secret:o,response_type:s=Ge,scope:c=Ke,redirect_uri:l,post_logout_redirect_uri:u,client_authentication:d=qe,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=Je,mergeClaimsStrategy:w={array:`replace`},disablePKCE:T=!1,stateStore:E,revokeTokenAdditionalContentTypes:D,fetchRequestCredentials:O,refreshTokenAllowedScope:ee,extraQueryParams:k={},extraTokenParams:A={},extraHeaders:j={},dpop:M,omitScopeWhenRequesting:N=!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=N,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 Be;this.stateStore=new We({store:e})}if(this.refreshTokenAllowedScope=ee,this.extraQueryParams=k,this.extraTokenParams=A,this.extraHeaders=j,this.dpop=M,this.dpop&&!this.dpop?.store)throw Error(`A DPoPStore is required when dpop is enabled`)}},Xe=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=De.decode(e);return t.debug(`JWT decoding successful`),n}catch(e){throw t.error(`Error parsing JWT response`),e}},this._jsonService=new He(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}},Ze=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new W(`TokenClient`),this._jsonService=new He(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`)}},Qe=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new W(`ResponseValidator`),this._userInfoService=new Xe(this._settings,this._metadataService),this._tokenClient=new Ze(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 Ie(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 Ie(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=De.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=De.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}},$e=class e{constructor(e){this.id=e.id||G.generateUUIDv4(),this.data=e.data,this.created=e.created&&e.created>0?e.created:Ne.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=Ne.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))}}},et=class e extends $e{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)}},tt=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 et.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}${Fe}${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})}};tt._logger=new W(`SigninRequest`);var nt=tt,rt=`openid`,it=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(Fe);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Fe))}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-Ne.getEpochTime()}set expires_in(e){typeof e==`string`&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+Ne.getEpochTime())}get isOpenId(){return this.scope?.split(` `).includes(rt)||!!this.id_token}},at=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 $e({data:t,request_type:a,url_state:s});let e=this.state.id;s&&(e=`${e}${Fe}${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}},ot=class{constructor(e){if(this.state=e.get(`state`),this.state){let e=decodeURIComponent(this.state).split(Fe);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Fe))}this.error=e.get(`error`),this.error_description=e.get(`error_description`),this.error_uri=e.get(`error_uri`)}},st=[`nbf`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`at_hash`],ct=[`sub`,`iss`,`aud`,`exp`,`iat`],lt=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:st;for(let n of e)ct.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}},ut=class{constructor(e,t){this.keys=e,this.nonce=t}},dt=class{constructor(e,t){this._logger=new W(`OidcClient`),this.settings=e instanceof Ye?e:new Ye(e),this.metadataService=t??new Ue(this.settings),this._claimsService=new lt(this.settings),this._validator=new Qe(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Ze(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 nt.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 it(Pe.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 et.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 Ve&&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 ut(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 it(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 Ve&&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 it(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 at({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 ot(Pe.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 Ie(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 $e.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`),$e.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})}},ft=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 ze(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)}}}},pt=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-Ne.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+Ne.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))}},mt=`oidc-client`,ht=class{constructor(){this._abort=new je(`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===mt){try{let n=Pe.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:mt,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()}}},gt={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},_t=`_blank`,vt=60,yt=2,bt=10,xt=class extends Ye{constructor(e){let{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=gt,popupWindowTarget:i=_t,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:_=yt,query_status_response_type:v=`code`,stopCheckSessionOnError:y=!0,revokeTokenTypes:b=[`access_token`,`refresh_token`],revokeTokensOnSignout:x=!1,includeIdTokenInSilentSignout:S=!1,accessTokenExpiringNotificationTimeInSeconds:C=vt,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||bt,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 Be;this.userStore=new We({store:e})}}},St=class e extends ht{constructor({silentRequestTimeoutInSeconds:t=bt}){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 Le(`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)}},Ct=class{constructor(e){this._settings=e,this._logger=new W(`IFrameNavigator`)}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new St({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create(`callback`),St.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},wt=500,Tt=1e3,Et=class extends ht{constructor({popupWindowTarget:e=_t,popupWindowFeatures:t={},popupSignal:n,popupAbortOnClose:r}){super(),this._logger=new W(`PopupWindow`);let i=Me.center({...gt,...t});this._window=window.open(void 0,e,Me.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*Tt)}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`)))},wt),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()}},Dt=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 Et({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n,popupAbortOnClose:r})}async callback(e,{keepOpen:t=!1}){this._logger.create(`callback`),Et.notifyOpener(e,t)}},Ot=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(){}},kt=class extends Re{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new W(`UserManagerEvents`),this._userLoaded=new je(`User loaded`),this._userUnloaded=new je(`User unloaded`),this._silentRenewError=new je(`Silent renew error`),this._userSignedIn=new je(`User signed in`),this._userSignedOut=new je(`User signed out`),this._userSessionChanged=new je(`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()}},At=class{constructor(e){this._userManager=e,this._logger=new W(`SilentRenewService`),this._isStarted=!1,this._retryTimer=new Ne(`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 Le){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)}},jt=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}},Mt=class{constructor(e,t,n,r){this._logger=new W(`UserManager`),this.settings=new xt(e),this._client=new dt(e),this._redirectNavigator=t??new Ot(this.settings),this._popupNavigator=n??new Dt(this.settings),this._iframeNavigator=r??new Ct(this.settings),this._events=new kt(this.settings),this._silentRenewService=new At(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new ft(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 jt(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 pt({...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 Ie)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 pt(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 Ie({...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`),pt.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 ut(await G.generateDPoPKeys()),await e.store.set(this.settings.client_id,t)),await G.generateDPoPJkt(t.keys)}},Nt=`/auth/callback`,Pt=`Your session ended. Sign in again.`,Ft=class extends Error{constructor(){super(Pt),this.name=`SessionEndedError`}},It=null,Lt=null,Rt=null,zt=new Set;async function Bt(){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,scopes:r}=await e.json();if(!t||!n)throw Error(`The backend named no issuer or client to sign in with`);let i=Array.isArray(r)?r.filter(e=>typeof e==`string`&&e):[];return{authority:t,clientId:n,scope:[...new Set([`openid`,...i])].join(` `)}}function Vt(){return It||(It=Bt().then(({authority:e,clientId:t,scope:n})=>new Mt({authority:e,client_id:t,redirect_uri:`${window.location.origin}${x(Nt)}`,post_logout_redirect_uri:`${window.location.origin}${x(`/`)}`,response_type:`code`,scope:n,automaticSilentRenew:!0})),It.catch(()=>{It=null})),It}function Ht(){let{pathname:e,search:t}=window.location;return e===x(`/auth/callback`)&&new URLSearchParams(t).has(`state`)}async function Ut(){try{return!!(await(await Vt()).metadataService.getMetadata()).prompt_values_supported?.includes(`create`)}catch{return!1}}async function Wt(){let e=await(await Vt()).signinRedirectCallback(),t=e.state?.returnTo??`/`;return window.history.replaceState(null,``,t),window.dispatchEvent(new PopStateEvent(`popstate`)),e}async function Gt(e={}){let{pathname:t,search:n,hash:r}=window.location;await(await Vt()).signinRedirect({state:{returnTo:`${t}${n}${r}`},...e.createAccount?{prompt:`create`}:{}})}async function Kt(){let e=await Vt(),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 qt(){return Rt||=(async()=>{let e=await Vt();try{let t=await e.signinSilent();if(t)return t.access_token}catch(e){console.warn(`Session renewal failed:`,e)}return await e.removeUser(),zt.forEach(e=>e()),null})().finally(()=>{Rt=null}),Rt}async function Jt(){return(await(await Vt()).getUser())?.expired?(await qt(),!0):!1}function Yt(e){return zt.add(e),()=>zt.delete(e)}async function Xt(){try{return await Wt()}catch(e){return console.warn(`Ignoring a sign-in callback that cannot be completed:`,e),window.history.replaceState(null,``,x(`/`)),Kt()}}function Zt(){return Lt||=Ht()?Xt():Kt(),Lt}function Qt(e){let t=t=>{t.persisted&&e()};return window.addEventListener(`pageshow`,t),()=>window.removeEventListener(`pageshow`,t)}async function $t(){let e=await Vt(),t=await e.getUser();await e.removeUser(),t&&await e.signoutRedirect({id_token_hint:t.id_token})}async function en(e,t){if(e.status===401)return new Ft;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}=be.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()),i=E();if(r.status!==401||D()&&!i)return r;let a=await(i?i():qt());if(!a)throw new Ft;return n({Authorization:`Bearer ${a}`})}async getStrategyDirectory(){let e=await this._authorizedFetch(`${S()}/graphcore/api/get_strategy_directory/`);if(!e.ok)throw await en(e,`Failed to fetch strategy directory`);return e.json()}async getCatalog(){let e=await this._authorizedFetch(`${S()}/graphcore/api/catalog/`);if(!e.ok)throw await en(e,`Failed to fetch the catalog`);return e.json()}async getConnectionToken(e){let t=await this._authorizedFetch(`${S()}/graphcore/api/connections/${encodeURIComponent(e)}/token/`,{method:`POST`});if(!t.ok)throw await en(t,`Failed to get a token for the connection`);return t.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 en(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 en(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 en(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 en(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 en(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 en(r,`Failed to fetch entity`);return r.json()}},tn=(e,t)=>({equal:{field:e,value:t}}),nn=(e,t)=>({in_values:{field:e,values:t}}),rn=(e,t)=>({contains_value:{field:e,value:t}}),an=(e,t)=>({contains_any:{field:e,values:t}}),on=(e,t)=>({range:{field:e,...t}}),sn=(...e)=>({all_of:e}),cn=(...e)=>({any_of:e}),ln={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},un=l.default.createContext&&l.default.createContext(ln),dn=[`attr`,`size`,`title`];function fn(e,t){if(e==null)return{};var n,r,i=pn(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 pn(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 mn(){return mn=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},mn.apply(null,arguments)}function hn(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 gn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?hn(Object(n),!0).forEach(function(t){_n(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):hn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function _n(e,t,n){return(t=vn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vn(e){var t=yn(e,`string`);return typeof t==`symbol`?t:t+``}function yn(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 bn(e){return e&&e.map((e,t)=>l.default.createElement(e.tag,gn({key:t},e.attr),bn(e.child)))}function q(e){return t=>l.default.createElement(xn,mn({attr:gn({},e.attr)},t),bn(e.child))}function xn(e){var t=t=>{var n=e.attr,r=e.size,i=e.title,a=fn(e,dn),o=r||t.size||`1em`,s;return t.className&&(s=t.className),e.className&&(s=(s?s+` `:``)+e.className),l.default.createElement(`svg`,mn({stroke:`currentColor`,fill:`currentColor`,strokeWidth:`0`},t.attr,n,a,{className:s,style:gn(gn({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 un===void 0?t(ln):l.default.createElement(un.Consumer,null,e=>t(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:`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 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:`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 wn(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 Tn(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 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:`M96 256h320M96 176h320M96 336h320`},child:[]}]})(e)}function Dn(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 On(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 kn(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 An(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 jn(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 Mn(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 Nn(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 Pn(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 Fn(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 In(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 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:`M160 368 32 256l128-112m192 224 128-112-128-112m-48-48-96 320`},child:[]}]})(e)}function Rn(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 zn(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 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:`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`}),Vn={[J.ENTITY]:Fn,[J.VIEW]:Mn,[J.USER]:Dn,[J.GROUP]:On,[J.STRATEGY_REQUEST]:An},Hn=Fn;function Un(e){return Vn[e]||Hn}var Wn=j(()=>null),Gn=e=>{Wn.setState(e)},Kn=(e,t)=>{t instanceof Ft||Gn({message:`${e}: ${t instanceof Error?t.message:String(t)}`,type:`error`})},qn=()=>R(Wn,e=>e),Jn=100,Yn=100,Xn=j(()=>({loaded:{},views:{}})),Zn=new Map,Qn=new Set,$n=!1,er=(e,t,n)=>JSON.stringify([`top`,e,t,n]),tr=(e,t,n,r)=>JSON.stringify([e,t,n,r]);function nr(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?tr(e.parent_id,e.client,e.slot,t):typeof e.owner==`string`?er(e.owner,e.client,e.slot):null}function rr(e,t){let{client:n,address:r,view:i}=e;return r===void 0?{key:JSON.stringify([`view`,n,i]),predicate:sn(rn(`ancestor_ids`,i),tn(`client`,n))}:{key:JSON.stringify([`page`,t,n,r]),predicate:sn(tn(`owner`,t),tn(`client`,n),tn(`address`,r))}}function ir(e){let t={},n=new Set;e.forEach(e=>{if(e?.entity_type_id!==J.VIEW)return;let r=nr(e);r&&(e.deleted?n.add(e.entity_id):t[r]=e.entity_id)}),(Object.keys(t).length!==0||n.size!==0)&&Xn.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 ar(e){try{let t=[],n;do{let r=await K.listEntities({type_ids:[J.VIEW],where:e.length===1?e[0].predicate:cn(...e.map(e=>e.predicate)),cursor:n,limit:Jn});t.push(...r?.entities??[]),n=r?.next_cursor??void 0}while(n);L.mergeEntities(t),ir(t),Xn.setState(t=>({loaded:{...t.loaded,...Object.fromEntries(e.map(e=>[e.key,!0]))}}))}catch(e){console.error(`View lookup failed:`,e),Kn(`Could not load views`,e)}finally{e.forEach(e=>Qn.delete(e.key))}}function or(){$n=!1;let e=[...Zn.values()];Zn=new Map,e.forEach(e=>Qn.add(e.key));for(let t=0;t<e.length;t+=Yn)ar(e.slice(t,t+Yn))}var sr=e=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,16)};function cr(e,t,n){let{client:r,address:i,view:a,placement:o}=t,s;if(i!==void 0){if(!e.loaded[rr(t,n).key])return;s=e.views[er(n,r,i)]??null}else{if(o.length&&!e.loaded[rr(t,n).key])return;s=a}for(let t of o){if(!s)return null;s=e.views[tr(s,r,t.slot,t.renders)]??null}return s}var lr={request(e,t){let n=rr(e,t);Xn.getState().loaded[n.key]||Qn.has(n.key)||(Zn.set(n.key,n),!$n&&($n=!0,sr(or)))},noteEntities(e){ir(e)},find(e,t){return cr(Xn.getState(),e,t)},clear(){Zn=new Map,Qn.clear(),$n=!1,Xn.setState({loaded:{},views:{}})}};function ur(e){let{principalEntityId:t}=xe(),n=e&&t?rr(e,t).key:null;(0,c.useEffect)(()=>{e&&t&&lr.request(e,t)},[n]);let r=R(Xn,n=>e&&t?cr(n,e,t):null),i=I(e=>r?e.entitiesById[r]??null:null);if(r!==void 0)return r?i:null}var dr=3e4,fr=1e4,pr=3e3,mr=100,hr=new Set([`succeeded`,`failed`]),gr=null,_r=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),{}):{},vr=()=>{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)})},yr=()=>{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/`},br=`graphcore.bearer`,xr=()=>{let e={current:null},t={current:{token:null,principalEntityId:null}},n={current:0},r={current:null},i={current:null},a={current:null},o={current:mr},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,de(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),lr.noteEntities(Object.values(e)))},x=e=>{let t=d.current;Object.entries(_r(e)).forEach(([e,n])=>{ae(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 pe(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&&hr.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&&ye(n.since)},E=e=>{let t=s.current;!t.outstanding.delete(e)||t.outstanding.size>0||(b(),ye(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}))))},ee=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}))))},k=()=>{let r=t.current.token,a=t.current.principalEntityId;if(!r){h(`idle`);return}g(),D(`Reconnecting`),h(`connecting`);let s=new WebSocket(yr(),[br,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,fr),dr)},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=_r(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}}),ge(t.resource_id);return}if(t.type===`access_granted`||t.type===`access_changed`){L.clearEntityFlags(t.resource_id),O(t.resource_id),ge(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,L.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))},M=()=>{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,pr)},N=()=>{if(c.current||typeof window>`u`)return;let e=()=>{document.visibilityState===`visible`&&M()},t=e=>{e.persisted&&M()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`online`,M),window.addEventListener(`pageshow`,t),c.current=()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`online`,M),window.removeEventListener(`pageshow`,t)}};return gr=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?(N(),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(),L.clearRequestedEntities(),y(),D(e),h(`idle`),w(Error(`Connection closed`))},dispose(){this.disconnect(`Disposing bridge`),g(),_(),c.current?.(),c.current=null,gr===u&&(gr=null)},fetchEntity:O,fetchEntityByKey:ee,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=vr(),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,fr)}}},Sr=e=>Symbol.iterator in e,Cr=e=>`entries`in e,wr=(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},Tr=(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 Er(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Sr(e)&&Sr(t)?Cr(e)&&Cr(t)?wr(e,t):Tr(e,t):wr({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}var Dr=(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))},Or=e=>L.readEntity(e),kr=e=>{let t=Or(e);return Array.isArray(t?.children_ids)?t.children_ids.filter(Boolean):[]},Ar=(e,t={})=>!e||t.enabled===!1?[]:kr(e).map(e=>Or(e)).filter(e=>!!e).filter(e=>Dr(e,t)),jr=(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=Or(r);if(!a)return null;let o=kr(r).reduce((e,t)=>{let r=n(t,new Set(i));return r&&(e[t]=r),e},{});return Dr(a,t)||Object.keys(o).length>0||t.includeRoot&&r===e?{entity:a,children:o}:null};return n(e)},Mr={readEntity(e){return Or(e)},readEntities(e){return L.readEntities(e)},readChildren(e,t={}){return Ar(e,t)},readRecursiveChildren(e,t={}){return jr(e,t)}},Nr=()=>{let e=k();if(!e)throw Error(`useGraphCoreBridge must be used within GraphCoreProvider.`);return e},Pr=()=>{let e=Nr();return(0,c.useMemo)(()=>e.executeStrategy.bind(e),[e])},Fr=(e,t)=>{t&&e.forEach(e=>{!e||L.readEntity(e)||L.isNotFound(e)||t(e)})},Y=e=>{let t=Nr(),n=fe(),r=I((0,c.useMemo)(()=>t=>e?t.entitiesById[e]??null:null,[e]));return(0,c.useEffect)(()=>{Fr([e],t.fetchEntity)},[t,n,e,r]),r},Ir=e=>{let t=Nr(),n=fe(),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}},Lr=e=>{let t=Nr(),n=(0,c.useMemo)(()=>e.filter(Boolean),[e]),r=fe(),i=I(e=>n.map(t=>e.entitiesById[t]??null).filter(e=>!!e),Er);return(0,c.useEffect)(()=>{Fr(n,t.fetchEntity)},[t,r,i,n]),i},Rr=(e,t={})=>{let n=Nr(),r=Y(e),i=(0,c.useMemo)(()=>Array.isArray(r?.children_ids)?r.children_ids.filter(Boolean):[],[r?.children_ids]),a=fe(),o=I(()=>Mr.readChildren(e,t),Er);return(0,c.useEffect)(()=>{Fr(i,n.fetchEntity)},[n,a,i]),o},zr=(e,t={})=>{let n=Nr(),r=fe(),i=I(e=>e.entityIds),a=(0,c.useMemo)(()=>Mr.readRecursiveChildren(e,t),[i,t,e]);return(0,c.useEffect)(()=>{Fr([e],n.fetchEntity)},[n,r,e]),a},Br=e=>e?.attributes??{},Vr=(e,t)=>Br(e)[t],Hr=e=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==`attributes`));function Ur(e){return(typeof e==`string`?e:e?.entity_type_id)?.split(`.`).pop()??``}function X(e){return[e?.display_name,Ur(e),e?.entity_id].find(e=>typeof e==`string`&&e.trim().length>0)??`Entity`}var Wr=()=>{let e=I(e=>e.entityIds,Er),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()},[])}},Gr=()=>{let e=xe(),{mergeEntities:t,clearEntities:n}=Wr(),{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 Gt(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(),lr.clear(),B(z());try{await $t()}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}},Kr=`graphcore.offlineAccess.tried:`;function qr(e){try{return window.sessionStorage.getItem(Kr+e)===`1`}catch{return!0}}function Jr(e){try{window.sessionStorage.setItem(Kr+e,`1`)}catch{}}async function Yr(e,t){let n=e.principal_entity_id;if(e.offline_access!==`needed`||qr(n))return!1;Jr(n);try{let e=await fetch(`${S()}/graphcore/api/offline-access/start/`,{method:`POST`,headers:{Authorization:`Bearer ${t}`,"Content-Type":`application/json`},body:JSON.stringify({return_to:window.location.href})});if(!e.ok)return console.warn(`Offline access was not started:`,e.status,await e.text()),!1;let{url:n}=await e.json();return typeof n!=`string`||!n?!1:(window.location.assign(n),!0)}catch(e){return console.warn(`Offline access was not started:`,e),!1}}var Xr=j(()=>null),Zr=e=>{Xr.setState(e,!0)},Qr=()=>R(Xr,e=>e),$r={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`},ei=()=>{let e=qn();if((0,c.useEffect)(()=>{if(!e)return;let t=setTimeout(()=>Gn(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 ${$r[e.type]||$r.info}`,children:[(0,u.jsx)(`span`,{className:`flex-1`,children:t}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>Gn(null),className:`text-lg leading-none opacity-60 hover:opacity-100`,"aria-label":`Dismiss notification`,children:`×`})]})})},ti=(0,c.createContext)(null),ni=ti.Provider;function ri(){let e=(0,c.useContext)(ti);if(!e)throw Error(`useViewRegistry() must be called within a <GraphCoreProvider registry={...}>.`);return e}function ii(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 ai(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 oi(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 si(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 ci(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 li(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 ui(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 di(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 fi=/version: (\S+)/,pi=0;async function mi(e){let t=await fetch(`${S()}/mcp`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,Authorization:`Bearer ${be.getState().token??``}`},body:JSON.stringify({jsonrpc:`2.0`,id:++pi,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:fi.exec(r)?.[1]??null}}var hi=`e/:backend_id/:local_id`,gi=`[0-9a-hjkmnp-tv-z]`,_i=RegExp(`gc:/+(${gi}{10})/(${gi}{12})(?![0-9A-Za-z])`);function vi(e){return`/e/${e.replace(/^gc:\/\//,``)}`}function yi(e){let{backend_id:t,local_id:n}=e;return t&&n?`gc://${t}/${n}`:null}function bi(e){let t=e;try{t=decodeURIComponent(e)}catch{}let n=_i.exec(t);return n?`gc://${n[1]}/${n[2]}`:null}var xi=`graphcore.agent_mirror`,Si=2e3,Ci=(0,c.createContext)(!1),wi=()=>{try{return localStorage.getItem(xi)===`1`}catch{return!1}},Ti=j(()=>({open:wi()}));function Ei(e){Ti.setState({open:e});try{localStorage.setItem(xi,e?`1`:`0`)}catch{}}function Di(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 mi(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=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 Oi=`[0-9a-hjkmnp-tv-z]`,ki=RegExp(`(gc://${Oi}{10}/${Oi}{12}|/e/${Oi}{10}/${Oi}{12})`,`g`);function Ai({text:e}){let t=e.split(ki);return(0,u.jsx)(u.Fragment,{children:t.map((e,t)=>t%2?(0,u.jsx)(d.Link,{to:e.startsWith(`gc://`)?vi(e):e,className:`text-blue-700 hover:underline`,children:e},t):e)})}function ji({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)(Ai,{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)(Ai,{text:e.slice(3)})},t):e.startsWith(`- `)?(0,u.jsxs)(`div`,{className:`break-all pl-3 -indent-3`,children:[`• `,(0,u.jsx)(Ai,{text:e.slice(2)})]},t):e.trim()?(0,u.jsx)(`div`,{className:`break-all text-gray-600`,children:(0,u.jsx)(Ai,{text:e})},t):(0,u.jsx)(`div`,{className:`h-2`},t))})}function Mi({address:e}){let{place:t,error:n,changed:r}=Di(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)(ci,{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:()=>Ei(!1),className:`shrink-0 rounded p-1 hover:bg-gray-100`,children:(0,u.jsx)(ai,{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)(ji,{text:t.text}):!n&&(0,u.jsxs)(`div`,{className:`text-xs text-gray-400`,children:[`Opening `,e,`…`]})]})]})}function Ni({address:e,children:t}){let n=(0,c.useContext)(Ci),r=R(Ti,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:()=>Ei(!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)(ci,{className:`h-3.5 w-3.5`}),`Agent view`]})]}),r&&(0,u.jsx)(Mi,{address:e})]}):(0,u.jsx)(u.Fragment,{children:t})}var Pi=-32601,Fi=-32603,Ii=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`RpcError`}};function Li(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`}var Ri=class{constructor(e,t,n){this.self=e,this.target=t,this.origin=n,this.nextId=1,this.pending=new Map,this.handlers=new Map,this.listener=e=>this.receive(e),e.addEventListener(`message`,this.listener)}request(e,t,n=1e4){let r=this.nextId++;return new Promise((i,a)=>{let o=setTimeout(()=>{this.pending.delete(r),a(new Ii(Fi,`${e} timed out`))},n);this.pending.set(r,{resolve:e=>{clearTimeout(o),i(e)},reject:e=>{clearTimeout(o),a(e)}}),this.post({jsonrpc:`2.0`,id:r,method:e,params:t})})}notify(e,t){this.post({jsonrpc:`2.0`,method:e,params:t})}handle(e,t){return this.handlers.set(e,t),()=>{this.handlers.get(e)===t&&this.handlers.delete(e)}}dispose(){this.self.removeEventListener(`message`,this.listener),this.pending.forEach(({reject:e})=>e(new Ii(Fi,`The channel closed`))),this.pending.clear(),this.handlers.clear()}post(e){this.target.postMessage(e,this.origin)}async receive(e){if(e.source!==this.target||e.origin!==this.origin||!Li(e.data))return;let t=e.data;if(t.method===void 0){let e=t.id===void 0?void 0:this.pending.get(t.id);if(!e)return;this.pending.delete(t.id),t.error?e.reject(new Ii(t.error.code,t.error.message)):e.resolve(t.result);return}let n=this.handlers.get(t.method);if(t.id===void 0)try{await n?.(t.params)}catch{}else if(!n)this.post({jsonrpc:`2.0`,id:t.id,error:{code:Pi,message:`Method not found: ${t.method}`}});else try{let e=await n(t.params);this.post({jsonrpc:`2.0`,id:t.id,result:e??{}})}catch(e){let n=e instanceof Ii?e.code:Fi;this.post({jsonrpc:`2.0`,id:t.id,error:{code:n,message:e instanceof Error?e.message:String(e)}})}}},zi=[`gc/navigate`];function Bi(e=window){try{return e.parent!==e}catch{return!0}}async function Vi(e=window){let t=e.location.origin;try{let e=await fetch(`${S()}/graphcore/api/auth/client/`),n=e.ok?await e.json():{};return[t,...(Array.isArray(n.frame_origins)?n.frame_origins.filter(e=>typeof e==`string`):[]).filter(e=>e!==t)]}catch{return[t]}}function Hi(e,{win:t=window,timeoutMs:n=500}={}){if(!Bi(t)||e.length===0)return Promise.resolve(null);let r=t.parent,i=new Map(e.map((e,t)=>[`gc-init-${t}`,e]));return new Promise(e=>{let a=n=>{t.removeEventListener(`message`,o),clearTimeout(s),e(n)},o=e=>{if(e.source!==r||!Li(e.data))return;let n=i.get(String(e.data.id));if(n===void 0||e.origin!==n)return;let o=e.data.result;!e.data.error&&o&&typeof o.token==`string`&&typeof o.expires_at==`number`&&a({channel:new Ri(t,r,n),origin:n,commands:Array.isArray(o.commands)?o.commands.filter(e=>typeof e==`string`):[],token:o.token,expiresAt:o.expires_at})},s=setTimeout(()=>a(null),n);t.addEventListener(`message`,o),i.forEach((e,t)=>{r.postMessage({jsonrpc:`2.0`,id:t,method:`gc/initialize`,params:{protocol:1,commands:zi}},e)})})}var Ui=`The workspace hosting this window stopped answering. Reload the workspace.`,Wi=(0,c.createContext)(null);function Gi({connection:e}){let{mergeEntities:t}=Wr();return(0,c.useEffect)(()=>{let n=!1,r,i=null,a=e=>{clearTimeout(r);let t=Math.max(0,e-60-Date.now()/1e3)*1e3;r=setTimeout(()=>{o()},Math.min(t,2**31-1))},o=()=>(i??=e.channel.request(`gc/token`).then(e=>{if(typeof e?.token!=`string`||typeof e.expires_at!=`number`)throw Error(`no token`);return n||(B(t=>({...t,token:e.token})),a(e.expires_at)),e.token}).catch(()=>(n||B({...z(),error:Ui}),null)).finally(()=>{i=null}),i);return B(t=>({...t,token:e.token})),T(o),a(e.expiresAt),(async()=>{try{let r=await K.me(e.token);if(n)return;B(t=>({...t,isAuthenticated:!0,isLoading:!1,error:null,token:t.token??e.token,principalEntityId:r.principal_entity_id,username:r.username}));let i=await K.getEntity(r.principal_entity_id,e.token);!n&&i&&t([i])}catch(e){if(n)return;B(t=>({...t,isLoading:!1,error:e instanceof Error?e.message:`The workspace could not sign you in here`}))}})(),()=>{n=!0,clearTimeout(r),T(null)}},[e,t]),null}function Ki(){let e=(0,c.useContext)(Wi),t=(0,d.useInRouterContext)();return e&&t?(0,u.jsx)(qi,{connection:e}):null}function qi({connection:e}){let t=(0,d.useLocation)(),n=(0,d.useNavigate)(),r=`${t.pathname}${t.search}`;return(0,c.useEffect)(()=>{e.commands.includes(`gc/notifications/navigated`)&&e.channel.notify(`gc/notifications/navigated`,{address:r,title:document.title})},[e,r]),(0,c.useEffect)(()=>e.channel.handle(`gc/navigate`,e=>{let t=e?.address;if(typeof t!=`string`||!t.startsWith(`/`))throw Error(`gc/navigate needs an address`);return n(t),{}}),[e,n]),null}function Ji(){let e=(0,c.useContext)(Wi),t=(0,d.useInRouterContext)()?(0,d.useNavigate)():null;return{hosted:e!==null,openWindow:async n=>{e&&e.commands.includes(`gc/open-window`)?await e.channel.request(`gc/open-window`,{address:n}):t?t(n):window.location.assign(n)}}}function Yi({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 Xi(){let{mergeEntities:e,clearEntities:t}=Wr();return(0,c.useEffect)(()=>{let n=!1,r=()=>{},i=Qt(()=>window.location.reload()),a=e=>{B(t=>t.isAuthenticated?{...t,token:e.access_token}:t)},o=()=>{t(),lr.clear(),B({...z(),error:Pt})},s=Yt(o);return(async()=>{try{let t=await Vt();t.events.addUserLoaded(a),t.events.addSilentRenewError(o),r=()=>{t.events.removeUserLoaded(a),t.events.removeSilentRenewError(o)};let i=await Zt();if(n)return;if(!i){B(e=>({...e,isLoading:!1}));return}let s=await K.me(i.access_token);if(n||await Yr(s,i.access_token))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 Zi({bridge:e}){let{isAuthenticated:t,token:n,principalEntityId:r}=Gr();return(0,c.useEffect)(()=>(e.setOnAuthError(async e=>{let t=E();(t?await t():!D()&&await Jt())||Gn({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 Qi(e){let[t,n]=(0,c.useState)(()=>!e&&Bi()?{state:`checking`}:{state:`standalone`});return(0,c.useEffect)(()=>{if(t.state!==`checking`)return;let e=!1;return Vi().then(e=>Hi(e)).then(t=>{e?t?.channel.dispose():n(t?{state:`hosted`,connection:t}:{state:`standalone`})}),()=>{e=!0}},[t.state]),(0,c.useEffect)(()=>()=>{t.state===`hosted`&&t.connection.channel.dispose()},[t]),t}function $i({apiUrl:e}){return(0,c.useEffect)(()=>{let e=!1;return K.getIdentity().then(t=>{e||Zr(t?.deployment_entity_id??null)}).catch(()=>{e||Zr(null)}),()=>{e=!0}},[e]),null}function ea({apiUrl:e,wsUrl:t,registry:n,getToken:r,principalEntityId:i,agentMirror:a=!1,basePath:o,children:s}){let l=(0,c.useMemo)(()=>xr(),[]),d=Qi(!!r);return _(e,t,r),y(o),(0,c.useEffect)(()=>()=>{l.dispose()},[l]),(0,u.jsx)(ni,{value:n,children:(0,u.jsx)(ee,{value:l,children:(0,u.jsxs)(Wi.Provider,{value:d.state===`hosted`?d.connection:null,children:[r?(0,u.jsx)(Yi,{getToken:r,principalEntityId:i}):d.state===`hosted`?(0,u.jsx)(Gi,{connection:d.connection}):d.state===`standalone`&&(0,u.jsx)(Xi,{}),(0,u.jsx)(Zi,{bridge:l}),(0,u.jsx)($i,{apiUrl:e}),(0,u.jsx)(Ci.Provider,{value:a,children:s}),(0,u.jsx)(ei,{})]})})})}function ta(){let[e,t]=(0,c.useState)(!1);return(0,c.useEffect)(()=>{let e=!0;return Ut().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}var na=`/invite`;function ra(e){return`${window.location.origin}${x(na)}#${e}`}var ia=e=>e.startsWith(`#`)?decodeURIComponent(e.slice(1)):``;function aa(){let{pathname:e,hash:t}=(0,d.useLocation)();return e===`/invite`&&!!ia(t)}function oa({onRedeemed:e}){let{hash:t}=(0,d.useLocation)(),n=(0,d.useNavigate)(),[r,i]=(0,c.useState)(null),a=(0,c.useRef)(null),o=ia(t);(0,c.useEffect)(()=>{o&&a.current!==o&&(a.current=o,K.redeemInvite(o).then(t=>{e?e(t):n(vi(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 sa=({className:e,title:t=`graphcore`})=>{let{login:n,register:r,isLoading:i,error:a}=Gr(),{hosted:o}=Ji(),s=ta(),c=aa();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...`:o?`Signed out of this window. Sign in again in the workspace.`:c?`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&&!o&&(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`}),s&&(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`})]})]})})},ca=null;function la(){let[e,t]=(0,c.useState)(null);return(0,c.useEffect)(()=>{let e=!1;return ca??=K.getRoutes().then(e=>e.routes),ca.then(n=>!e&&t(n)).catch(()=>{ca=null,e||t([])}),()=>{e=!0}},[]),e}function ua(){let e=Nr(),t=fe();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),Gn({message:e?.message||`Request failed. Please try again.`,type:`error`}),e}):r}catch(e){if(console.error(`Error sending strategy request:`,e),Gn({message:`Error sending request. Please try again.`,type:`error`}),n.awaitResponse)return Promise.reject(e)}},[e]),isConnected:t===`connected`,bridge:e}}var da=50,fa=250,pa=!1,ma={key:``,ids:[],cursor:null};function ha(e){let t=P(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 ga({typeIds:e,parentId:t,where:n,grantedToMe:r=!1,limit:i=da,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)(()=>ha(u)??ma),[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=ha(u);e&&p(e)}let x=f.key===u?f:ma,{ids:S,cursor:C}=x,w=d&&x.key!==u,T=m&&x.key===u;(0,c.useEffect)(()=>{f.key&&!f.forget&&te({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??[];pa=!0;try{L.mergeEntities(a)}finally{pa=!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;Kn(`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,fa)},i=he(r),a=ve(e=>{y.current<e&&r()}),c=F.subscribe((n,i)=>{if(pa||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 _a=j(()=>({contents:{},state:`loading`,error:null})),va=j(()=>({contents:{},state:`loading`,error:null})),ya=j(()=>({contents:{},state:`loading`,error:null})),ba=j(()=>({contents:[],state:`loading`,error:null})),xa=null,Sa=null,Ca=async()=>_a.getState().state===`hasValue`?_a.getState().contents:xa||(_a.setState(e=>({...e,state:`loading`,error:null})),xa=K.getStrategyDirectory().then(e=>{let t=e||{};return _a.setState({contents:t,state:`hasValue`,error:null}),t}).catch(e=>{throw _a.setState({contents:{},state:`hasError`,error:e}),e}).finally(()=>{xa=null}),xa),wa=async()=>va.getState().state===`hasValue`?va.getState().contents:Sa||(va.setState(e=>({...e,state:`loading`,error:null})),Sa=K.getEntityDirectory().then(e=>{let t=e?.entities||e||{};return va.setState({contents:t,state:`hasValue`,error:null}),ya.setState({contents:e?.declared||{},state:`hasValue`,error:null}),ba.setState({contents:e?.new_user_groups||[],state:`hasValue`,error:null}),t}).catch(e=>(console.error(`Failed to fetch available entities:`,e),va.setState({contents:{},state:`hasError`,error:e}),ya.setState({contents:{},state:`hasError`,error:e}),ba.setState({contents:[],state:`hasError`,error:e}),{})).finally(()=>{Sa=null}),Sa),Ta=()=>R(_a),Ea=()=>R(va),Da=()=>Ea(),Oa=()=>R(ya),ka=()=>R(ba),Aa=e=>{(0,c.useEffect)(()=>{wa()},[]);let t=Oa().contents;return e?t[e]:void 0},Z=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}}},Q={builder(){return new Z},createGrant(e,t,n){return new Z().withStrategyName(`CreateGrant`).withTargetEntity(e).withParams({subject_id:t,role_name:n}).build()},changeGrantRole(e,t){return new Z().withStrategyName(`ChangeGrantRole`).withTargetEntity(e).withParams({role_name:t}).build()},revokeGrant(e){return new Z().withStrategyName(`RevokeGrant`).withTargetEntity(e).build()},setAttributes(e,t){return new Z().withStrategyName(`SetAttributes`).withTargetEntity(e).withParams({attribute_map:t}).build()},removeAttribute(e,t){return new Z().withStrategyName(`RemoveAttribute`).withTargetEntity(e).withParams({attribute_name:t}).build()},createEntity(e,t,n={}){let r={entity_type_id:t,initial_attributes:n};return new Z().withStrategyName(`CreateEntity`).withTargetEntity(e).withParams(r).build()},createGroup(e,{parentId:t=null,key:n=null,adminManaged:r=!1}={}){return new Z().withStrategyName(`CreateGroup`).withTargetEntity(t).withParams({name:e,key:n,admin_managed:r}).build()},setNewUserDefaults(e,t){return new Z().withStrategyName(`SetNewUserDefaults`).withTargetEntity(e).withParams({group_ids:t}).build()},hideEntity(e,t=!0){return Q.setAttributes(e,{hidden:t})},deleteEntity(e){return new Z().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 Z().withStrategyName(`SetViewState`).withTargetEntity(e||null).withParams(i).build()},createView(e,{renders:t=null,component:n=null,state:r={}}={}){return new Z().withStrategyName(`CreateView`).withTargetEntity(e||null).withParams({renders:t,component:n,state:r}).build()},reparentChild(e,t){return new Z().withStrategyName(`ReparentChild`).withTargetEntity(e).withParams({parent_id:t}).build()},detachChild(e){return Q.reparentChild(e,null)},moveChildBefore(e,t){return new Z().withStrategyName(`ReorderChild`).withTargetEntity(e).withParams({before_child_id:t}).build()},moveChildAfter(e,t){return new Z().withStrategyName(`ReorderChild`).withTargetEntity(e).withParams({after_child_id:t}).build()}};function ja(e){return e.startsWith(`/`)?e.split(/[?#]/)[0].replace(/\/+$/,``)||`/`:null}function Ma(e,t=`web`){let n=ja(e);return n?{client:t,address:n,placement:[]}:null}function Na(e,t=`web`){return{client:t,view:e,placement:[]}}function Pa(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 Fa(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 Ia=(0,c.createContext)(null);function La(){return(0,d.useInRouterContext)()?(0,d.useLocation)().pathname:null}function Ra(e){let t=La(),n=(0,c.useMemo)(()=>e&&t?Ma(t):null,[e,t]),r=ur(n);return(0,c.useMemo)(()=>n?{position:n,view:r}:null,[n,r])}function za(){let e=(0,c.useContext)(Ia),t=Ra(!e);return e??t}var Ba=e=>{let t=e.slice(e.lastIndexOf(`.`)+1).replace(/_/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)};function Va(e,t){let n=za(),r=n?.position??null,i=!!n?.route;return(0,c.useMemo)(()=>r&&!i?Pa(r,e,t):r,[r,i,e,t])}function Ha({position:e,children:t}){let n=ur(e),r=(0,c.useMemo)(()=>({position:e,view:n}),[e,n]);return(0,u.jsx)(Ia.Provider,{value:r,children:t})}function Ua({address:e,children:t}){let n=(0,c.useMemo)(()=>Ma(e),[e]),r=ur(n),i=(0,c.useMemo)(()=>({position:n,view:r,route:!0}),[n,r]);return(0,u.jsx)(Ia.Provider,{value:i,children:t})}function Wa(e,t,n={}){if(!e)throw Error(`A view name must be a non-empty string`);let r=({slot:n,...r})=>{let i=Va(n??e,r.entityId);return(0,u.jsx)(Ha,{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??Ba(e),Component:t})}function Ga(e){return typeof e==`function`&&typeof e.viewName==`string`&&`Component`in e}var Ka=25;function qa({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}=ga({typeIds:e,limit:Ka}),h=Lr(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<Ka&&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 Ja=(e,t,n)=>Q.builder().withStrategyName(e).withTargetEntity(t).withParams(n).build();function Ya({entityId:e}){if(!e)throw Error(`This view needs an entity to show.`);let{sendStrategyRequest:t}=ua(),n=Y(e),r=n?.member_ids??[],i=Lr(r),[a,o]=(0,c.useState)(!1),s=async(n,r)=>{o(!0);try{await t(Ja(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)(qa,{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 Xa=Wa(`group_view`,Ya,{defaultFor:[J.GROUP]}),Za=new Map;function Qa(e,t){let n=Za.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()=>{Za.has(e)||o(!0),d(null);try{let t=await K.getAccess(e);Za.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)(()=>he(t=>{t===e&&f()}),[e,f]),(0,c.useEffect)(()=>ve(()=>{f()}),[f]);let p=!!r?.can_manage,m=(0,c.useMemo)(()=>p&&r?.grants||[],[p,r]);(0,c.useEffect)(()=>{wa()},[]);let h=Y(e),g=Da().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=Lr((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(Q.createGrant(e,t,n)),changeRole:(e,t)=>D(Q.changeGrantRole(e,t)),revoke:e=>D(Q.revokeGrant(e)),setPublicRead:()=>D(Q.createGrant(e,`*`,`viewer`)),revokePublicRead:()=>E?.grant_entity_id?D(Q.revokeGrant(E.grant_entity_id)):Promise.resolve()}}var $a=`/admin`,eo=`graphcore.admins`,to=`graphcore.members`,no=`member`,ro=[{id:`people`,label:`People`},{id:`groups`,label:`Groups`}];function io(e){let{ids:t,refresh:n}=ga({typeIds:[e],limit:100,all:!0});return{entities:Lr(t),refresh:n}}var $=e=>e.name||e.key||e.entity_id,ao=(e,t)=>e.find(e=>e.subject_id===t&&e.provenance===`direct`),oo=e=>{let t=e=>e.key===eo?0:e.key===to?1:2;return[...e].sort((e,n)=>t(e)-t(n)||$(e).localeCompare($(n)))},so=e=>e?.all_permissions?`Can do everything on the deployment`:e?.description||``;function co({sendStrategyRequest:e,className:t=``}){let{sendStrategyRequest:n}=ua(),r=e??n,i=Qr();return i?(0,u.jsx)(lo,{deploymentId:i,send:r,className:t}):(0,u.jsx)(`div`,{className:`p-6 text-sm text-slate-500 ${t}`,children:`Loading deployment…`})}function lo({deploymentId:e,send:t,className:n}){let r=Qa(e,t),[i,a]=(0,c.useState)(`people`),[o,s]=(0,c.useState)(null),l=io(J.USER),d=io(J.GROUP),f=Y(e),p=Da().contents[J.DEPLOYMENT]?.roles||[],m=ka().contents;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 h=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()])},g=r.summary.grants,_=oo(d.entities),v=f?.new_user_group_ids??[],y=e=>!!e.key&&m.includes(e.key)||v.includes(e.entity_id),b=g.find(e=>e.subject_id===`*`&&e.role===no&&e.provenance===`direct`);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:`People belong to groups. Each group has one role on this deployment, which decides what everyone in it can do here: create, or administer. People can also share their own things with a group; that access is managed where it is shared, not here.`})]}),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`})]}),b?.grant_entity_id&&(0,u.jsx)(uo,{grant:b,run:h}),(0,u.jsx)(`nav`,{className:`flex gap-1 border-b border-slate-200`,role:`tablist`,children:ro.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===`people`&&(0,u.jsx)(po,{users:l.entities,groups:_,grants:g,everyone:!!b,run:h}),i===`groups`&&(0,u.jsx)(mo,{groups:_,grants:g,roles:p,deploymentId:e,adminIds:v,settingKeys:m,joinsNewUsers:y,run:h})]})}function uo({grant:e,run:t}){return(0,u.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-900`,children:[(0,u.jsxs)(`p`,{children:[(0,u.jsx)(`span`,{className:`font-medium`,children:`Everyone signed in can create here`}),`, through a grant made before the Members group existed. Removing it stops anyone creating who is not in a group with a role. To keep your people creating, first give Members the member role and add them to it.`]}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>void t(Q.revokeGrant(e.grant_entity_id)),className:`rounded-md border border-amber-400 bg-white px-3 py-1.5 text-xs font-semibold text-amber-900`,children:`Remove the grant to everyone`})]})}var fo=(e,t,n)=>Q.builder().withStrategyName(e).withTargetEntity(t).withParams({principal_entity_id:n}).build();function po({users:e,groups:t,grants:n,everyone:r,run:i}){let[a,o]=(0,c.useState)(!1),s=e.map(e=>{let r=t.filter(t=>(t.member_ids||[]).includes(e.entity_id)),i=n.filter(t=>t.subject_id===e.entity_id&&t.provenance===`direct`);return{user:e,memberOf:r,direct:i,roleNames:[...new Set([...r.map(e=>ao(n,e.entity_id)?.role).filter(e=>!!e),...i.map(e=>e.role)])]}}),l=a?s.filter(e=>e.roleNames.length===0):s;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:a,onChange:()=>o(!a)}),`Only people without a role`]}),(0,u.jsxs)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:[l.length===0&&(0,u.jsx)(`li`,{className:`px-4 py-3 text-sm text-slate-500`,children:`Nobody here.`}),l.map(({user:e,memberOf:n,direct:a,roleNames:o})=>{let s=X(e),c=t.filter(e=>!n.includes(e));return(0,u.jsxs)(`li`,{className:`space-y-2 px-4 py-3 text-sm`,children:[(0,u.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:s}),(0,u.jsx)(`span`,{className:`ml-auto text-xs text-slate-500`,children:o.length>0?(0,u.jsxs)(u.Fragment,{children:[`Role on this deployment: `,(0,u.jsx)(`span`,{className:`font-mono`,children:o.join(`, `)})]}):r?`No role of their own; creates through the grant to everyone`:(0,u.jsx)(`span`,{className:`rounded bg-amber-100 px-1.5 py-0.5 text-amber-800`,children:`No role yet`})})]}),(0,u.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[n.map(t=>(0,u.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full bg-slate-100 py-0.5 pl-2.5 pr-1 text-xs text-slate-700`,children:[$(t),(0,u.jsx)(`button`,{type:`button`,"aria-label":`Remove ${s} from ${$(t)}`,onClick:()=>void i(fo(`RemoveMember`,t.entity_id,e.entity_id)),className:`rounded-full px-1 text-slate-500 hover:bg-slate-200 hover:text-slate-900`,children:`×`})]},t.entity_id)),a.map(e=>(0,u.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-slate-200 py-0.5 pl-2.5 pr-1 text-xs text-slate-600`,children:[(0,u.jsxs)(`span`,{children:[(0,u.jsx)(`span`,{className:`font-mono`,children:e.role}),`, given directly`]}),e.grant_entity_id&&(0,u.jsx)(`button`,{type:`button`,"aria-label":`Take ${e.role} from ${s}`,onClick:()=>void i(Q.revokeGrant(e.grant_entity_id)),className:`rounded-full px-1 text-slate-500 hover:bg-slate-200 hover:text-slate-900`,children:`×`})]},e.grant_entity_id??e.role)),c.length>0&&(0,u.jsxs)(`select`,{"aria-label":`Add ${s} to a group`,value:``,onChange:t=>{t.target.value&&i(fo(`AddMember`,t.target.value,e.entity_id))},className:`rounded-full border border-dashed border-slate-300 bg-white px-2 py-0.5 text-xs text-slate-600`,children:[(0,u.jsx)(`option`,{value:``,children:`+ Add to group`}),c.map(e=>(0,u.jsx)(`option`,{value:e.entity_id,children:$(e)},e.entity_id))]})]})]},e.entity_id)})]})]})}function mo({groups:e,grants:t,roles:n,deploymentId:r,adminIds:i,settingKeys:a,joinsNewUsers:o,run:s}){let l=Oa().contents,[d,f]=(0,c.useState)(``),[p,m]=(0,c.useState)(null),h=e.filter(o).map($);return(0,u.jsxs)(`div`,{className:`space-y-4`,children:[(0,u.jsx)(`p`,{className:`text-sm text-slate-600`,children:h.length>0?(0,u.jsxs)(u.Fragment,{children:[`New users join `,(0,u.jsx)(`strong`,{children:h.join(`, `)}),` when they first sign in.`]}):`New users join no group: they can sign in, and can do nothing here until you add them to one.`}),(0,u.jsx)(`ul`,{className:`divide-y divide-slate-200 rounded-xl border border-slate-200`,children:e.map(e=>{let c=p===e.entity_id,d=(e.member_ids||[]).length,f=!!e.key&&a.includes(e.key);return(0,u.jsxs)(`li`,{className:`space-y-3 px-4 py-3 text-sm`,children:[(0,u.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,u.jsx)(`span`,{className:`font-medium text-slate-900`,children:$(e)}),(0,u.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[d,` `,d===1?`person`:`people`]}),(0,u.jsx)(`button`,{type:`button`,onClick:()=>m(c?null:e.entity_id),"aria-expanded":c,"aria-label":`${c?`Close`:`Manage`} ${$(e)}`,className:`ml-auto rounded-md px-2 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-100`,children:c?`Close`:`Manage`})]}),(0,u.jsx)(go,{group:e,grant:ao(t,e.entity_id),roles:n,run:s,deploymentId:r}),e.key!==eo&&(0,u.jsxs)(`label`,{className:`flex flex-wrap items-center gap-2 text-xs text-slate-700`,children:[(0,u.jsx)(`input`,{type:`checkbox`,checked:o(e),disabled:f,onChange:()=>{let t=i.includes(e.entity_id)?i.filter(t=>t!==e.entity_id):[...i,e.entity_id];s(Q.setNewUserDefaults(r,t))}}),`New users join this group`,f&&(0,u.jsxs)(`span`,{className:`text-slate-500`,children:[`(set by `,(0,u.jsx)(`span`,{className:`font-mono`,children:`GRAPHCORE_NEW_USER_GROUPS`}),` in the project's settings)`]})]}),c&&(0,u.jsxs)(`div`,{className:`space-y-3 rounded-lg bg-slate-50 p-3`,children:[(0,u.jsx)(Xa,{entityId:e.entity_id}),e.key&&l[e.key]?(0,u.jsx)(`p`,{className:`text-xs text-slate-500`,children:`This group is built in, so it cannot be deleted.`}):(0,u.jsx)(_o,{group:e,run:s})]})]},e.entity_id)})}),(0,u.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),d.trim()&&s(Q.createGroup(d.trim(),{adminManaged:!0})).then(()=>f(``))},children:[(0,u.jsx)(`input`,{value:d,onChange:e=>f(e.target.value),placeholder:`New group name`,"aria-label":`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`})]})]})}var ho=``;function go({group:e,grant:t,roles:n,run:r,deploymentId:i}){let a=t?.role??ho,[o,s]=(0,c.useState)(null),l=o??a,d=l===ho?`Gives no access here on its own`:so(n.find(e=>e.name===l)),f=e=>e===ho?`no role`:e,p=async()=>{o!==null&&(o===ho?t?.grant_entity_id&&await r(Q.revokeGrant(t.grant_entity_id)):await r(Q.createGrant(i,e.entity_id,o)),s(null))};return(0,u.jsxs)(`div`,{className:`space-y-2`,children:[(0,u.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-slate-700`,children:[(0,u.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,u.jsx)(`span`,{className:`font-medium`,children:`Role on this deployment`}),(0,u.jsxs)(`select`,{"aria-label":`Role of ${$(e)}`,value:l,onChange:e=>s(e.target.value===a?null:e.target.value),className:`rounded-md border border-slate-300 bg-white px-2 py-1 font-mono text-xs`,children:[(0,u.jsx)(`option`,{value:ho,children:`no role`}),n.map(e=>(0,u.jsx)(`option`,{value:e.name,children:e.name},e.name))]})]}),d&&(0,u.jsx)(`span`,{className:`text-slate-500`,children:d})]}),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===ho?(0,u.jsxs)(u.Fragment,{children:[`Give `,(0,u.jsx)(`strong`,{children:$(e)}),` the role `,(0,u.jsx)(`strong`,{children:f(o)}),`?`]}):(0,u.jsxs)(u.Fragment,{children:[`Replace `,(0,u.jsx)(`strong`,{children:$(e)}),`'s role `,(0,u.jsx)(`strong`,{children:f(a)}),` with `,(0,u.jsx)(`strong`,{children:f(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 p(),className:`rounded-md bg-slate-900 px-2 py-1 font-medium text-white`,children:o===ho?`Remove role`:a===ho?`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 _o({group:e,run:t}){let[n,r]=(0,c.useState)(!1);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:$(e)}),`? 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(Q.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 vo(e=!0){let t=Qr(),[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 yo(e){return[{to:`/`,label:`home`},...e.map(e=>e.pattern).filter(e=>e!==`/`&&!e.includes(`{`)).map(e=>({to:e,label:e.slice(1)}))]}var bo=({isActive:e})=>`rounded-md px-2.5 py-1 text-sm ${e?`bg-gray-900 text-white`:`text-gray-600 hover:bg-gray-100`}`,xo=`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm hover:bg-gray-100`;function So({adminHref:e}){let{isAuthenticated:t,username:n,principalEntityId:r,logout:i}=Gr(),{hosted:a}=Ji(),o=vo(t),s=Y(r),[l,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),h=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(!l)return;let e=e=>{h.current?.contains(e.target)||f(!1)},t=e=>e.key===`Escape`&&f(!1);return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[l]);let g=s?.username||n||`User`;return(0,u.jsxs)(`div`,{ref:h,className:`relative`,children:[(0,u.jsxs)(`button`,{type:`button`,"aria-haspopup":`menu`,"aria-expanded":l,onClick:()=>f(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:[g,(0,u.jsx)(ui,{className:`h-2.5 w-2.5 text-gray-400`})]}),l&&(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),m(!0),setTimeout(()=>m(!1),2e3)}catch(e){console.error(`Failed to copy user entity ID:`,e)}},title:`Copy user entity ID`,className:xo,children:[p?(0,u.jsx)(di,{className:`h-3 w-3 shrink-0 text-green-600`}):(0,u.jsx)(li,{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})]}),o&&(0,u.jsxs)(d.Link,{to:e,role:`menuitem`,onClick:()=>f(!1),className:`${xo} text-gray-700`,children:[(0,u.jsx)(ii,{className:`h-3.5 w-3.5 text-gray-500`}),`Admin`]}),!a&&(0,u.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:i,className:`${xo} text-red-600 hover:bg-red-50`,children:[(0,u.jsx)(oi,{className:`h-3.5 w-3.5`}),`Logout`]})]})]})}var Co=({title:e=`graphcore`,places:t,className:n=``,adminHref:r=$a})=>{let{isAuthenticated:i}=Gr(),a=la();if(!i)return null;let o=yo(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:bo,children:e.label},e.to))}),(0,u.jsx)(`div`,{className:`ml-auto`,children:(0,u.jsx)(So,{adminHref:r})})]})},wo=({entityTypeId:e,className:t=`w-4 h-4`,size:n})=>{let r=Un(e);return c.default.createElement(r,{className:t,size:n})},To={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`}},Eo=({availableViewTypes:e,selectedValue:t,onSelect:n,theme:r=`light`,placeholder:i=`Search view types...`,autoFocus:a=!1})=>{let[o,s]=(0,c.useState)(``),l=To[r]||To.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)(si,{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)(di,{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 Do(e){let t=za(),{sendStrategyRequest:n}=ua(),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?Fa(s):void 0,state:e};t!==void 0&&(r.component=t);let i=Promise.resolve(n(Q.setViewState(o,r),{awaitResponse:!0}));return i.catch(()=>void 0),i},[s,n,o])]}function Oo(){let{sendStrategyRequest:e}=ua();return(0,c.useCallback)(async(t={})=>{try{return(await e(Q.createView(null,t),{awaitResponse:!0}))?.view_entity_id??null}catch{return null}},[e])}function ko(){(0,c.useEffect)(()=>{wa()},[]);let e=Da().contents;return(0,c.useMemo)(()=>Object.keys(e).filter(e=>e!==J.VIEW).sort(),[e])}var Ao=[{key:`entity_ide`,label:`Entity IDE`,icon:Ln,state:{sidebar_config:{allow_create:!0}}}],jo=`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 Mo({viewId:e,onRemove:t}){let n=(0,d.useNavigate)(),r=ri(),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&&Vr(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(vi(e)),className:`${jo} 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)(wo,{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)(Rn,{className:`h-4 w-4`})})]})}function No(){let e=(0,d.useNavigate)(),t=ri(),[{views:n},r]=Do({views:[]}),i=Oo(),a=Lr(n),o=(0,c.useRef)(n),s=(0,c.useRef)(n);(0,c.useEffect)(()=>{o.current=n,s.current=n},[n]);let l=ko(),[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=>Ao.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(vi(n.entity_id));return}let r=Ao.find(e=>e.key===t),i=await w(t,{component:t,state:r?.state??{}});i&&e(vi(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:[Ao.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)(wn,{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)(Mo,{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)(Bn,{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)(Eo,{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)(qa,{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 Po=Wa(`view_gallery`,No,{entry:!0});function Fo(){let{isAuthenticated:e}=Gr(),[t,n]=(0,c.useState)(null);return(0,c.useEffect)(()=>{if(!e){n(null);return}let t=!1;return K.getCatalog().then(e=>!t&&n(e)).catch(()=>!t&&n({deployments:[],entries:[]})),()=>{t=!0}},[e]),t}var Io=e=>e.replace(/(^|-)\w/g,e=>e.toUpperCase());function Lo({entityId:e,sendStrategyRequest:t,className:n=``}){let r=Qa(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:ra(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:Io(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:Io(e.name)},e.name))}),r.subjectTypeIds.length>0&&(0,u.jsx)(qa,{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 `,Io(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 Ro({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:Bo(e),component:t})}function zo(e){return typeof e==`object`&&!!e&&e.kind===`graphcore.page`}function Bo(e){return e.length>1?e.replace(/\/+$/,``):e}function Vo(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(zo)){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 Ho(e){return e==null||e===``?`Empty`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e,null,2)}function Uo(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 Wo(e){let t=Uo(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}):Ho(e)}function Go({entityId:e}){let t=Y(e),n=X(t),r=Ur(t),i=Object.entries(Br(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:Wo(t)})]},e))})})]})}var Ko=(0,c.createContext)([]);function qo(){return(0,c.useContext)(Ko)}function Jo({token:e,children:t}){let n=qo(),r=(0,c.useMemo)(()=>e?[...n,e]:n,[n,e]);return(0,u.jsx)(Ko.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 Xo({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 Zo=[],Qo=(0,c.createContext)(Zo),$o=()=>(0,c.useContext)(Qo);function es(e,t,n){return t&&e.get(t)?t:n?e.defaultViewFor(n):null}function ts({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 ns({cause:e,className:t=``}){return e===`forbidden`?(0,u.jsx)(Xo,{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 rs(){let e=ri();return(0,c.useMemo)(()=>Object.fromEntries(e.keys().map(t=>[t,e.get(t).label])),[e])}function is({current:e}){let[,t]=Do({}),n=rs(),[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)(Eo,{availableViewTypes:n,selectedValue:e??``,onSelect:e=>{i(!1),t({},e)},theme:`light`,placeholder:`Search views...`,autoFocus:!0})})]})}function as(){let[,e]=Do({}),t=rs();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)(Eo,{availableViewTypes:t,selectedValue:``,onSelect:t=>void e({},t),theme:`light`,placeholder:`Search views...`})]})}function os({name:e,entityId:t,className:n,inline:r}){let i=ri(),a=qo(),o=`${t??``}:${e??``}`;if(a.includes(o))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 s=e&&i.get(e)?.Component||Go;return(0,u.jsx)(Jo,{token:o,children:(0,u.jsxs)(`div`,{className:`${r?`inline-flex`:`group relative h-full min-h-0`} ${n??``}`,children:[!r&&(0,u.jsx)(is,{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)(s,{entityId:t})})]})})}function ss({entity:e,slot:t,className:n,inline:r}){let i=Va(t??`entity`,e.entity_id);return(0,u.jsx)(Ha,{position:i,children:(0,u.jsx)(cs,{entity:e,className:n,inline:r})})}function cs({entity:e,className:t,inline:n}){let r=ri(),i=za()?.view;if(i===void 0)return n?null:(0,u.jsx)(ts,{label:`Loading view…`});let a=es(r,typeof i?.component==`string`?i.component:null,e.entity_type_id);return(0,u.jsx)(os,{name:a,entityId:e.entity_id,className:t,inline:n})}function ls({view:e,className:t}){let n=ri(),r=(0,c.useMemo)(()=>Na(e.entity_id),[e.entity_id]),i=ur(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)(ns,{cause:`forbidden`,className:t});else if(s)d=(0,u.jsx)(ns,{cause:`not_found`,className:t});else if(a&&!o)d=(0,u.jsx)(ts,{label:`Loading entity…`});else{let e=es(n,typeof i.component==`string`?i.component:null,o?.entity_type_id);d=!e&&!a?(0,u.jsx)(as,{}):(0,u.jsx)(os,{name:e,entityId:a,className:t})}return(0,u.jsx)(Jo,{token:`view:${i.entity_id}`,children:(0,u.jsx)(Ia.Provider,{value:l,children:d})})}function us({entityKey:e,slot:t,className:n,inline:r}){let{entityId:i,notFound:a}=Ir(e);return a?(0,u.jsx)(ns,{cause:`not_found`,className:n}):i?(0,u.jsx)(ds,{entityId:i,slot:t,className:n,inline:r}):r?null:(0,u.jsx)(ts,{label:`Loading entity…`})}function ds({entityId:e,slot:t,className:n,inline:r}){let i=Y(e),a=I(t=>e?t.notFoundEntityIds.has(e):!1),o=qo();return e?i?.forbidden?(0,u.jsx)(ns,{cause:`forbidden`,className:n}):a?(0,u.jsx)(ns,{cause:`not_found`,className:n}):i?i.entity_type_id===J.VIEW?o.includes(`view:${i.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)(ls,{view:i,className:n}):(0,u.jsx)(ss,{entity:i,slot:t,className:n,inline:r}):r?null:(0,u.jsx)(ts,{label:`Loading entity…`}):null}function fs({entityId:e,entityKey:t,context:n,slot:r,className:i,inline:a}){return(0,u.jsx)(Qo.Provider,{value:n??Zo,children:t?(0,u.jsx)(us,{entityKey:t,slot:r,className:i,inline:a}):(0,u.jsx)(ds,{entityId:e,slot:r,className:i,inline:a})})}var ps=()=>{let e=yi((0,d.useParams)()),t=(0,d.useNavigate)(),{pathname:n}=(0,d.useLocation)(),{isAuthenticated:r}=Gr(),{isConnected:i}=ua();return r?i?(0,u.jsx)(`div`,{className:`h-full min-h-0`,children:(0,u.jsx)(Ni,{address:n,children:(0,u.jsx)(Ua,{address:n,children:(0,u.jsx)(fs,{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`})]})})},ms=()=>{let{pathname:e}=(0,d.useLocation)(),t=bi(e);return(0,u.jsx)(d.Navigate,{to:t?vi(t):`/`,replace:!0})},hs=new Set([`/`,`/e/{entity}`]),gs=e=>e.replace(`{entity}`,`:entityBackend/:entityLocal`);function _s({viewName:e}){let{pathname:t}=(0,d.useLocation)(),{entityBackend:n,entityLocal:r}=(0,d.useParams)(),i=ri(),a=n&&r?`gc://${n}/${r}`:null,o=i.get(e)??(e===`home`?i.get(Po.viewName):void 0),s;return s=o?(0,u.jsx)(o,{entityId:a}):a?(0,u.jsx)(fs,{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)(Ni,{address:t,children:(0,u.jsx)(Ua,{address:t,children:(0,u.jsx)(`div`,{className:`h-full min-h-0`,children:s})})})}function vs({fallback:e=null}){let t=la();return(0,u.jsxs)(d.Routes,{children:[(0,u.jsx)(d.Route,{index:!0,element:(0,u.jsx)(_s,{viewName:`home`})}),(t??[]).filter(e=>!hs.has(e.pattern)).map(e=>(0,u.jsx)(d.Route,{path:gs(e.pattern),element:(0,u.jsx)(_s,{viewName:e.view_name})},e.pattern)),(0,u.jsx)(d.Route,{path:`*`,element:t?e:null})]})}function ys({topBar:e=(0,u.jsx)(Co,{})}){let{isAuthenticated:t,principalEntityId:n}=Gr();return!t||!n?(0,u.jsx)(sa,{}):(0,u.jsxs)(d.Routes,{children:[(0,u.jsx)(d.Route,{path:hi,element:(0,u.jsx)(`div`,{className:`h-screen w-screen overflow-hidden bg-gray-50`,children:(0,u.jsx)(ps,{})})}),(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:$a.slice(1),element:(0,u.jsx)(`div`,{className:`h-full overflow-auto`,children:(0,u.jsx)(co,{})})}),(0,u.jsx)(d.Route,{path:na.slice(1),element:(0,u.jsx)(oa,{})}),(0,u.jsx)(d.Route,{path:`*`,element:(0,u.jsx)(vs,{fallback:(0,u.jsx)(ms,{})})})]})]})}var bs=[`/admin`,`/auth/callback`];function xs(e){return e.split(`/`).filter(Boolean).flatMap(e=>e===`{entity}`?[null,null]:e===`*`?[`*`]:e.startsWith(`:`)?[null]:[e])}function Ss(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 Cs(e,t,n){if(n)return[];let r=[...t,...bs,`/e/{entity}`],i=[];for(let t of e)for(let e of r)Ss(xs(t.path),xs(e))&&i.push({page:t.path,route:e});return i}function ws(){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 Ts(e,t){return e===t||e.startsWith(`${t}/`)}function Es({pages:e,basePath:t}){let n=la();return(0,c.useEffect)(()=>{if(!n)return;let r=Cs(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.`),Gn({message:`Pages collide with app routes: ${i}`,type:`error`})},[n,e,t]),null}function Ds(){return(0,u.jsx)(`div`,{className:`p-8 text-sm text-gray-500`,children:`Page not found.`})}function Os({registry:e,pages:t=[],config:n,basePath:r,app:i=(0,u.jsx)(ys,{}),notFound:a=(0,u.jsx)(Ds,{})}){let o=v(r);y(o);let s=ws(),c=(0,u.jsxs)(ea,{...n,registry:e,basePath:o,children:[(0,u.jsx)(Es,{pages:t,basePath:o}),(0,u.jsx)(Ki,{}),i]});return o&&Ts(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 ks=({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`})]})]})}),As=({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})]})},js=({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`})},Ms=({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 Ns({entityId:e}){let{sendStrategyRequest:t}=ua();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(Br(r)).map(([e,t])=>({key:e,value:t})).sort((e,t)=>e.key.localeCompare(t.key)),[r]),m=Hr(r),h=Aa(r?.key),g=e=>Object.prototype.hasOwnProperty.call(Br(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=Q.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(Q.removeAttribute(n,e)),d(null))},[n,t]),x=(0,c.useCallback)(()=>{let e=i.trim();if(!n||!e||Object.prototype.hasOwnProperty.call(Br(r),e))return;let c=_(o),l=Q.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)(As,{label:e,value:t,onUpdate:t=>v(e,t),onDebounced:t=>y(e,t,500)}):(0,u.jsx)(js,{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)(Ms,{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)(Ms,{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)(ks,{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 Ps=Wa(`entity_attributes`,e=>(0,u.jsx)(Ns,{...e},e.entityId)),Fs=e=>`${e.slot??``}@${e.entityId}`;function Is(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 Ls(e){let[t,n]=Do(e),r=t.panels;return{state:t,update:n,panels:r,addPanel:(0,c.useCallback)(e=>{let t={entityId:e},i=Is(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=>Fs(t)!==e),sizes:i})},[r,t.sizes,n])}}function Rs({onPick:e}){let t=ko(),[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)(Bn,{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)(qa,{typeIds:t,onPick:t=>{r(!1),e(t.entity_id)},placeholder:`Add an entity…`,autoFocus:!0,listPlacement:`below`},t.join(`,`))})]})}function zs({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)(Rn,{className:`h-3.5 w-3.5`})})}var Bs={panels:[],sizes:{}};function Vs({direction:e}){let{state:t,panels:n,addPanel:r,removePanel:i}=Ls(Bs),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)(Rs,{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=Fs(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)(zs,{onClick:()=>void i(n)})}),(0,u.jsx)(fs,{entityId:e.entityId,slot:e.slot,className:`h-full`})]},n)})})]})}var Hs=Wa(`composite_hbox`,()=>(0,u.jsx)(Vs,{direction:`row`})),Us=Wa(`composite_vbox`,()=>(0,u.jsx)(Vs,{direction:`column`})),Ws={panels:[],sizes:{},active:null};function Gs(){let{state:e,update:t,panels:n,addPanel:r,removePanel:i}=Ls(Ws),a=Lr((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=>Fs(t)===e.active)??n[0],l=s?Fs(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=Fs(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)(zs,{onClick:e=>{e.stopPropagation(),i(n)}})]},n)}),(0,u.jsx)(`div`,{className:`ml-auto px-1`,children:(0,u.jsx)(Rs,{onPick:e=>void r(e)})})]}),(0,u.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:s?(0,u.jsx)(fs,{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 Ks=Wa(`composite_tabs`,Gs);function qs({entityId:e}){if(!e)throw Error(`This view needs an entity to show.`);let{sendStrategyRequest:t}=ua(),[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=Rr(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=Vr(b,`list_purpose`),C=typeof S==`string`?S:``,w=Vr(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)},ee=(e,t)=>{e.stopPropagation(),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),s(t)},k=(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})},A=(e,n,r)=>{e&&n&&e!==n&&t(r===`before`?Q.moveChildBefore(e,n):Q.moveChildAfter(e,n))},j=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=o||e.dataTransfer.getData(`text/plain`),r=l?.entityId===t?l.position:`after`;A(n,t,r),O()},M=e=>{n===e&&r(null),t(Q.detachChild(e))},N=e=>{n===e&&r(null),a(e)},te=()=>{i&&(t(Q.deleteEntity(i)),a(null))},P=async()=>{let n=p.trim();if(n&&!h){g(!0);try{await t(Q.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=>k(e,n),onDrop:e=>j(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=>ee(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)(En,{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)(wo,{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(),M(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)(Rn,{className:`h-3.5 w-3.5`})}),(0,u.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),N(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)(Cn,{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)(Sn,{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:Ur(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)(fs,{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 Js=Wa(`list_view`,qs),Ys={ENTITY_ID:`application/x-entity-id`,ENTITY_DATA:`application/x-entity-data`,SOURCE_CONTEXT:`application/x-source-context`},Xs=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 Zs(e){return{onDragOver:t=>{Xs.handleDragOver(t,{dropEffect:e.dropEffect,acceptedTypes:e.acceptedTypes})&&e.onDragOver&&e.onDragOver(t.nativeEvent)},onDrop:t=>{Xs.handleDrop(t,e.onDrop)},onDragEnter:t=>{Xs.hasValidEntityData(t)&&e.onDragEnter&&e.onDragEnter(t.nativeEvent)},onDragLeave:t=>{e.onDragLeave&&e.onDragLeave(t.nativeEvent)}}}var Qs=Object.values(J),$s=tn(`parent_id`,null);function ec(e){if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=Qs.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=Qs.find(t=>t.endsWith(`.${e}`));if(t)return t}return t.includes(`.`)?t:null}function tc(e){let t=new Set,n=[];return e.forEach(e=>{let r=ec(e);r&&!t.has(r)&&(t.add(r),n.push(r))}),n}var nc=new Set([J.VIEW,J.GRANT,J.DEPLOYMENT,J.STRATEGY_REQUEST]);function rc(e){return Object.entries(e).filter(([e,t])=>!nc.has(e)&&!t?.principal).map(([e])=>e).sort()}var ic=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)(wo,{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)}),ac=({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)(wo,{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,`)`]})]}),oc=({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),[ee,k]=(0,c.useState)(!1),[A,j]=(0,c.useState)(!1),[M,N]=(0,c.useState)(null),[te,P]=(0,c.useState)(!1),[ne,re]=(0,c.useState)(new Set),[ie,ae]=(0,c.useState)(void 0),oe=(0,c.useRef)(null),se=(0,c.useRef)(null),ce=(0,c.useRef)(null),F=(0,c.useRef)(null),I=l.has(e),L=Rr(e,{types:v,enabled:!!O?.children_ids?.length}),le=L.length>0,R=I?L:[];if(w!==ie){ae(w);let e=new Set;w&&C&&L.forEach(t=>{(t.entity_id===w||T?.has(t.entity_id))&&e.add(t.entity_type_id||`unknown`)}),re(e)}let ue=(0,c.useCallback)(()=>{r?.(e)},[e,r]),de=(0,c.useCallback)(()=>{i(e)},[e,i]),fe=(0,c.useCallback)(t=>{t.preventDefault(),t.stopPropagation(),le&&d(e)},[e,le,d]);(0,c.useCallback)(()=>{a&&a(e)},[e,a]);let pe=(0,c.useMemo)(()=>{let e=v.length>0?new Set(v):null;return Object.entries(g).filter(([t])=>!e||e.has(t))},[g,v]),me=(0,c.useMemo)(()=>Object.fromEntries(pe),[pe]),he=(0,c.useCallback)(t=>{if(t.stopPropagation(),I||d(e),pe.length===1){let[t]=pe[0];s&&s(e,t),j(!1);return}let n=!A;if(n&&se.current){let e=se.current.getBoundingClientRect();N({top:e.bottom+4,left:Math.max(8,Math.min(e.right-256,window.innerWidth-256-8))})}j(n)},[pe,e,I,s,d,A]),ge=(0,c.useCallback)(t=>{I||d(e),s&&s(e,t),j(!1)},[e,I,s,d]);(0,c.useEffect)(()=>{let e=e=>{let t=e.target;oe.current&&!oe.current.contains(t)&&ce.current&&!ce.current.contains(t)&&j(!1)};if(A)return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[A]);let _e=(0,c.useCallback)(t=>{t.stopPropagation(),navigator.clipboard?.writeText(e),P(!1)},[e]),ve=(0,c.useCallback)(t=>{t.stopPropagation(),window.open(`${window.location.origin}${x(vi(e))}`,`_blank`,`noopener,noreferrer`),P(!1)},[e]),ye=(0,c.useCallback)(n=>{n.stopPropagation(),t&&h&&h(e,t),P(!1)},[e,h,t]);(0,c.useEffect)(()=>{let e=e=>{F.current&&!F.current.contains(e.target)&&P(!1)};if(te)return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[te]);let z=(0,c.useCallback)(n=>{if(!O)return;let r=O.entity_type_id,i=X(O);Xs.startDrag(n,{entityId:e,entityType:r,sourceContext:`entity-explorer`,sourceParentId:t},{dragEffect:`move`,dragImageText:i})},[O,e,t]),be=Zs({dropEffect:`move`,onDrop:t=>{console.log(`Entity dropped on EntityItem:`,t,`target:`,e),k(!1),t.entityId!==e&&(t.sourceContext===`entity-explorer`&&t.sourceParentId?p?.(t.entityId,e,t.sourceParentId):m?.(t.entityId,e))},onDragEnter:()=>{k(!0)},onDragLeave:()=>{k(!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)(Rn,{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)(zn,{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)(Rn,{className:`w-3.5 h-3.5`})})]})}let B=O?.entity_type_id||``,xe=n===e,V=Vr(O,`name`),Se=B===J.VIEW?typeof V==`string`&&V?V:O?.component||X(O):X(O),Ce={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 ${xe?`bg-blue-50 border border-blue-200 text-blue-700`:``} ${ee?`ring-2 ring-blue-500 ring-inset bg-blue-50`:``}`,style:Ce,onClick:ue,onDoubleClick:de,onDragStart:z,...be,title:`${B} • ${Se} • Double-click to open • Click pin to dock • Drag to move • Drop entities to add as children • ${e}`,children:[le&&(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:fe,title:`Click to expand/collapse`,children:I?`▼`:`▶`}),!le&&(0,u.jsx)(`div`,{className:`w-4 h-4 shrink-0`}),(0,u.jsx)(`div`,{className:`shrink-0`,children:(0,u.jsx)(wo,{entityTypeId:B,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:oe,children:[(0,u.jsx)(`button`,{ref:se,onClick:he,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:`+`}),A&&M&&(0,u.jsx)(ic,{ref:ce,position:M,options:me,onSelect:ge})]}),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)(Cn,{className:`w-3.5 h-3.5`})}),(0,u.jsxs)(`div`,{className:`relative shrink-0`,ref:F,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)(Nn,{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:_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)(In,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Copy entity ID`})]}),(0,u.jsxs)(`button`,{type:`button`,onClick:ve,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)(kn,{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:ye,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)(Rn,{className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{children:`Remove link from parent`})]})]})]})]}),I&&R.length>0&&(0,u.jsx)(`div`,{className:`mt-0.5 space-y-0.5`,children:C?(()=>{let t=new Map;return R.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)(ac,{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)(oc,{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)})})():R.map(t=>(0,u.jsx)(oc,{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))})]})},sc=Wa(`entity_explorer`,({entityId:e,uiHooks:t,onEntityDelete:n,onEntityOpen:r,onEntitySelect:i,onEntityPin:a,explorerConfig:o})=>{let{sendStrategyRequest:s}=ua(),l=e||``,[d,p]=Do({}),m=Da(),h=m.state===`hasValue`?m.contents:{};(0,c.useEffect)(()=>{wa()},[]);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=tc(Array.isArray(o?.filter_entity_types)?o.filter_entity_types:[]);return e.length>0?e:rc(h)},[o?.filter_entity_types,h]),ee=(0,c.useMemo)(()=>tc(Array.isArray(d.explorer_active_filter_entity_types)?d.explorer_active_filter_entity_types:[]),[d.explorer_active_filter_entity_types]),k=Array.isArray(d.explorer_active_filter_entity_types)?ee:O,A=!e,j=ga({typeIds:(0,c.useMemo)(()=>k.length>0?k:Object.keys(h).sort(),[k,h]),where:$s,enabled:A}),[M,N]=(0,c.useState)(null),te=(0,c.useRef)(null),P=(0,c.useRef)(null),ne=(0,c.useCallback)(()=>{N(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(!M)return;let e=e=>{let t=e.target;!P.current?.contains(t)&&!te.current?.contains(t)&&N(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[M]);let re=(0,c.useMemo)(()=>Object.fromEntries(Object.entries(h).filter(([e])=>k.length===0||k.includes(e))),[h,k]),[ie,ae]=(0,c.useState)(!1),[oe,se]=(0,c.useState)(``),[ce,F]=(0,c.useState)(null),I=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(!ie)return;let e=e=>{I.current&&!I.current.contains(e.target)&&ae(!1)};return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[ie]);let le=(0,c.useMemo)(()=>{let e=oe.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,oe]),R=(0,c.useCallback)(e=>{p({explorer_active_filter_entity_types:e})},[p]),ue=(0,c.useCallback)(e=>{y?.(e,l)},[y,l]),de=(0,c.useCallback)(e=>{F(e),x?.(e,l)},[x,l]),fe=(0,c.useCallback)(e=>{b?.(e,l)},[b,l]),pe=(0,c.useCallback)(e=>{be(e)},[]),me=(0,c.useCallback)((e,t,n)=>{if(console.log(`Moving entity:`,e,`from:`,n,`to:`,t),e===t||n===t)return;let r=Q.reparentChild(e,t);s(r)},[s]),he=(0,c.useCallback)((e,t)=>{if(console.log(`Adding entity:`,e,`to:`,t),e===t)return;let n=Q.reparentChild(e,t);s(n)},[s]),ge=(0,c.useCallback)(async(e,t)=>{try{let n=(await Promise.resolve(s(Q.createEntity(e,t),{awaitResponse:!0})))?.child_entity;n&&(e&&ye(t=>new Set(t).add(e)),F(n),x?.(n,e??``))}catch(e){console.error(`Failed to create entity:`,e)}},[x,s]),_e=(0,c.useCallback)((e,t)=>{console.log(`Removing child:`,e,`from parent:`,t);let n=Q.detachChild(e);s(n)},[s]),[ve,ye]=(0,c.useState)(new Set([l])),[z,be]=(0,c.useState)(null),B=Y(l),xe=Y(z||l),V=(0,c.useMemo)(()=>!z||!xe?`this entity`:X(xe),[z,xe]),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&&(ye(e=>new Set([...e,...Se])),F(D))},[D,Se]);let Ce=(0,c.useCallback)(e=>{ye(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),we=(0,c.useMemo)(()=>z?(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:()=>be(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)(Sn,{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:[`"`,V,`"`]}),`? 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:()=>be(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=z;be(null);try{await s(Q.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,[z,V,n,s]);return!A&&!B?(0,u.jsxs)(`div`,{className:`p-4 text-center text-gray-500 text-sm`,children:[(0,u.jsx)(zn,{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)(jn,{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:[A&&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`}),M&&(0,u.jsx)(ic,{ref:P,position:M,options:re,onSelect:e=>{N(null),ge(null,e)}})]}),(0,u.jsxs)(`div`,{className:`relative`,ref:I,children:[(0,u.jsxs)(`button`,{onClick:()=>{ae(e=>!e),se(``)},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)(Tn,{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:oe,onChange:e=>se(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:()=>R([]),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:()=>R(O),children:`Reset default`})]}),(0,u.jsxs)(`div`,{className:`max-h-64 overflow-auto p-2 space-y-1`,children:[le.map(([e,t])=>{let n=k.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=k.includes(e)?k.filter(t=>t!==e):[...k,e];R(t)}}),(0,u.jsx)(wo,{entityTypeId:e,className:`w-3.5 h-3.5`}),(0,u.jsx)(`span`,{className:`truncate`,children:t?.name||e})]},e)}),le.length===0&&(0,u.jsx)(`div`,{className:`text-xs text-gray-500 px-1 py-1`,children:`No matching entity types`})]})]})]})]})]}),A?(0,u.jsxs)(u.Fragment,{children:[j.ids.map(e=>(0,u.jsx)(oc,{entityId:e,parentId:void 0,selectedEntityId:ce,onSelect:de,onDoubleClick:ue,onPin:fe,onDelete:pe,onCreateChild:ge,expandedEntities:ve,onToggleExpanded:Ce,onEntityMove:me,onEntityAdd:he,onRemoveChild:_e,availableEntities:h,allowCreate:S,filterTypeIds:k,showDeleteAction:w,showCreateChildAction:T,groupByEntityType:E,revealEntityId:D||void 0,revealAncestors:Se,depth:0},e)),j.ids.length===0&&!j.loading&&(0,u.jsx)(`div`,{className:`px-2 py-1 text-xs text-gray-500`,children:`No top-level entities`}),j.hasMore&&(0,u.jsx)(`button`,{type:`button`,onClick:j.loadMore,disabled:j.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:j.loading?`Loading…`:`Load more`})]}):(0,u.jsx)(oc,{entityId:l,parentId:void 0,selectedEntityId:ce,onSelect:de,onDoubleClick:ue,onPin:fe,onDelete:pe,onCreateChild:ge,expandedEntities:ve,onToggleExpanded:Ce,onEntityMove:me,onEntityAdd:he,onRemoveChild:_e,availableEntities:h,allowCreate:S,filterTypeIds:k,showDeleteAction:w,showCreateChildAction:T,groupByEntityType:E,revealEntityId:D||void 0,revealAncestors:Se,depth:0})]}),we&&(0,f.createPortal)(we,document.body)]})}),cc={open_tab_entity_ids:[],active_tab_entity_id:null,root_entity_id:null,sidebar_config:{}},lc=Object.values(J);function uc(e){let t=Vr(e,`docName`);if(typeof t==`string`&&t.trim())return t;if(e?.entity_type_id===J.VIEW){let t=Vr(e,`name`);if(typeof t==`string`&&t.trim())return t;if(typeof e.component==`string`&&e.component)return e.component}return X(e)}function dc(e){if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=lc.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=lc.find(t=>t.endsWith(`.${e}`));if(t)return t}return t.includes(`.`)?t:null}function fc(e){let t=new Set,n=[];return e.forEach(e=>{let r=dc(e);r&&!t.has(r)&&(t.add(r),n.push(r))}),n}function pc({entityId:e,sidebarConfig:t,rootEntityId:n,explorerTitle:r,uiHooks:i}){let[a,o]=Do(cc),s={...a.sidebar_config||{},...t||{}},l=n||a.root_entity_id||e||null,d=!!s.allow_create,f=(0,c.useMemo)(()=>fc(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)(sc,{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)(mc,{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)(fs,{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)(Pn,{className:`w-10 h-10 mx-auto mb-3 text-gray-300`}),(0,u.jsx)(`div`,{className:`text-sm`,children:`No entity open`})]})})})]})]})}var mc=({entityId:e,isActive:t,onSelect:n,onClose:r})=>{let i=Y(e),a=uc(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)(wo,{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)(Rn,{className:`w-3.5 h-3.5`})})]})},hc=Wa(`entity_ide`,pc);function gc(){let e=new Map,t=new Map,n=[],r={register(n){if(!Ga(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))Ga(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 _c={app:`graphcore`,exports:{EntityAttributesView:Ps,CompositeHBox:Hs,CompositeVBox:Us,CompositeTabs:Ks,ListView:Js,EntityExplorer:sc,EntityIDE:hc,GroupView:Xa,ViewGallery:Po}};function vc(){let{sendStrategyRequest:e}=ua(),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 yc(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 bc=`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`,xc=`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 Sc(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 Cc(e){return e.enum?!0:e.type===`array`?e.items?.type===`string`&&!e.items.enum:[`string`,`number`,`integer`,`boolean`].includes(e.type??``)}function wc(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 Tc(e){return e==null||e===``||Array.isArray(e)&&e.every(e=>e===``)}function Ec(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!==``)),(!Tc(e)||n.has(i))&&(r[i]=e)}return r}function Dc({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:bc,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:bc,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:xc,"aria-label":`Remove ${i} ${n+1}`,onClick:()=>a(e.filter((e,t)=>t!==n)),children:`Remove`})]},n)),(0,u.jsx)(`button`,{type:`button`,className:xc,onClick:()=>a([...e,``]),children:`Add`})]})}else c=t.type===`number`||t.type===`integer`?(0,u.jsx)(`input`,{id:o,type:`number`,className:bc,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:bc,required:r,maxLength:t.maxLength,value:typeof n==`string`?n:``,onChange:e=>a(e.target.value)}):(0,u.jsx)(`input`,{id:o,className:bc,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 Oc({strategy:e,target:t,initial:n={},value:r,onChange:i,fields:a,hidden:o={},labels:s,submitLabel:l=`Save`,onDone:d}){let f=Ta(),{run:p,busy:m,error:h}=vc(),[g,_]=(0,c.useState)(null);if((0,c.useEffect)(()=>{Ca().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=Sc(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]&&Cc(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:{...Ec(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)(Dc,{name:e,schema:y[e],value:S[e],required:b.has(e),text:wc(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:xc,children:l})]})}exports.ADMIN_ROUTE=$a,exports.AccessPanel=Lo,exports.AdminPanel=co,exports.AgentMirror=Ni,exports.AppRoutes=vs,exports.AuthPage=sa,exports.BaseEntity=Go,exports.CompositeHBox=Hs,exports.CompositeTabs=Ks,exports.CompositeVBox=Us,exports.ENTITY_ROUTE=hi,exports.EntityAttributesView=Ps,exports.EntityExplorer=sc,exports.EntityIDE=hc,exports.EntityLinkRedirect=ms,exports.EntityPicker=qa,exports.EntityRoute=ps,exports.EntityView=fs,exports.GraphCoreApp=ys,exports.GraphCoreProvider=ea,exports.GraphCoreRouter=Os,exports.GroupView=Xa,exports.HostRouting=Ki,exports.INVITE_ROUTE=na,exports.InviteRoute=oa,exports.ListView=Js,exports.StrategyError=pe,exports.StrategyForm=Oc,exports.StrategyRequests=Q,exports.TopBar=Co,exports.ViewGallery=Po,exports.allOf=sn,exports.anyOf=cn,exports.baseViews=_c,exports.collectPages=Vo,exports.containsAny=an,exports.containsValue=rn,exports.createViewRegistry=gc,exports.definePage=Ro,exports.defineView=Wa,exports.entityGraph=Mr,exports.entityIdFromParams=yi,exports.entityPath=vi,exports.equal=tn,exports.findEntityId=bi,exports.getAttr=Vr,exports.getAttributes=Br,exports.getBasePath=b,exports.getDisplayName=X,exports.getFields=Hr,exports.inValues=nn,exports.inviteUrl=ra,exports.onResync=ve,exports.pageCollisions=Cs,exports.range=on,exports.typeShortName=Ur,exports.useAccess=Qa,exports.useAuth=Gr,exports.useBridgeStatus=fe,exports.useCatalog=Fo,exports.useChildren=Rr,exports.useCreateView=Oo,exports.useDeploymentEntityId=Qr,exports.useEditable=yc,exports.useEntities=Lr,exports.useEntity=Y,exports.useEntityIdByKey=Ir,exports.useEntityQuery=ga,exports.useGraphCoreBridge=Nr,exports.useHost=Ji,exports.useIsDeploymentAdmin=vo,exports.useOffersRegistration=ta,exports.usePendingInvite=aa,exports.usePlacementContext=$o,exports.useRecursiveChildren=zr,exports.useStrategy=vc,exports.useStrategyRequest=Pr,exports.useViewRegistry=ri,exports.useViewState=Do,exports.useWebSocketConsumer=ua,exports.webPath=x;
|